<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Wambui Gitau on Medium]]></title>
        <description><![CDATA[Stories by Wambui Gitau on Medium]]></description>
        <link>https://medium.com/@ywg?source=rss-5161d83115ae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6q4JPnrcfek76D2i</url>
            <title>Stories by Wambui Gitau on Medium</title>
            <link>https://medium.com/@ywg?source=rss-5161d83115ae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 16:33:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ywg/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[My Journal: Dagster + dlt + Local AI Setup, Part 5]]></title>
            <link>https://medium.com/@ywg/my-journal-dagster-dlt-local-ai-setup-part-5-d20794764a9c?source=rss-5161d83115ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/d20794764a9c</guid>
            <category><![CDATA[metabase]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[open-webui]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Wambui Gitau]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 06:01:01 GMT</pubDate>
            <atom:updated>2026-06-30T06:01:01.065Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@ywg/my-journal-dagster-dlt-duckdb-claude-part-4-f1d0dfa86bd4">Part 4</a>, I built two live dashboards by talking to my F1 data platform through Claude’s Cowork mode, and I ended with a question: <em>what if you want to self-host everything, model, interface, and data, with nothing leaving your machine?</em> This post is the answer. It is the most I have ever fought with a setup, and also the one that taught me the most about what local AI can and cannot do today.</p><h4>Why bother going local at all</h4><p>The Claude setup in Part 4 was genuinely good. So why spend two weeks rebuilding it with open source parts that are objectively worse?</p><p>One word: data policy. The F1 data I use is public, there is no privacy stake in sending it to a hosted model. But the whole point of this exercise is the <em>pattern</em>. Some settings do not allow data to leave for anyone’s cloud. Healthcare, finance, government, “just use Claude” is a non-starter before the conversation begins. If the serving layer only works against a hosted model, it does not work for them at all.</p><p>So the goal for Part 5 was strict: the data never leaves the machine, and neither does the model. A user asks a question, an agent queries the warehouse, builds a dashboard, and no row of data, and no prompt, crosses a boundary I do not control.</p><p>What I learned is that this is possible today, but it is a different kind of engineering. With a hosted frontier model you spend your time on <em>what</em> you want. With a local 7-billion-parameter model you spend your time making it <em>reliable</em>.</p><h4>Live artifacts</h4><p>I started exactly where Part 4 left off: Open WebUI talking to my F1 MCP server, with the silver layer sitting in a DuckDB file. What I was chasing was the thing that made Part 4 feel magical, Claude Cowork’s live artifacts: interactive dashboards rendered right inside the chat, refreshing against live data each time you open them. I wanted that, locally.</p><p>I started with <a href="https://openwebui.com/">Open WebUI</a>: self-hosted, Ollama-native, popular. The catch is that Open WebUI does not speak MCP&#39;s stdio protocol, it consumes OpenAPI tool servers, so the Part 4 MCP server is wrapped with <a href="https://github.com/open-webui/mcpo">mcpo</a>, which serves any MCP server as OpenAPI:</p><pre># infrastructure/docker-compose.yaml (excerpt)<br>services:<br>  open-webui:<br>    image: ghcr.io/open-webui/open-webui:main<br>    ports:<br>      - &quot;3000:8080&quot;<br>    environment:<br>      - OLLAMA_BASE_URL=http://host.docker.internal:11434   # Ollama on the host<br>      - WEBUI_SECRET_KEY=local-dev-only<br>    extra_hosts:<br>      - &quot;host.docker.internal:host-gateway&quot;<br>    depends_on:<br>      - mcpo-openapi<br><br>  mcpo-openapi:             # wraps the MCP server as an OpenAPI tool server<br>    build:<br>      context: ..<br>      dockerfile: infrastructure/mcpo.Dockerfile<br>    command: [&quot;mcpo&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8001&quot;, &quot;--&quot;, &quot;python&quot;, &quot;server.py&quot;]<br>    ports:<br>      - &quot;8001:8001&quot;<br></pre><p>The bridge image is the MCP server’s own image; mcpo is just one of its requirements. The Dockerfile (infrastructure/mcpo.Dockerfile):</p><pre>FROM python:3.11-slim<br>WORKDIR /app<br>RUN pip install --no-cache-dir uv<br>COPY mcp_server/requirements.txt ./requirements.txt<br>RUN uv pip install --system -r requirements.txt<br>COPY mcp_server/ ./mcp_server/<br>WORKDIR /app/mcp_server<br>CMD [&quot;python&quot;, &quot;server.py&quot;, &quot;http&quot;]</pre><p>In Open WebUI, Admin Panel, Settings, Integrations, Manage Tool Server pointed at http://mcpo-openapi:8001 (the compose service name) imports every endpoint as a callable tool. So far so good: chat, model, tools, all local.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7w4GkeogQnrc0WReq-qiZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6arSGL2FSUTNA4XWXALmwQ.png" /></figure><p>Then the artifacts. Open WebUI can render HTML artifacts, but only basic ones, a static chart or a simple table, nothing like Cowork’s rich, interactive, data-bound artifacts. It was not enough. So I went looking for a harness that could do better.</p><h4>Into LibreChat for artifacts, then out to Metabase</h4><p><a href="https://librechat.ai/">LibreChat</a> advertised exactly what I wanted: polished, self-hosted, MCP support, an agents feature, and artifacts. So I moved the setup over to it.</p><p>LibreChat needs a MongoDB, so it is two services, plus a config file and an env file:</p><pre># docker-compose.yaml (excerpt)<br>  librechat:<br>    image: ghcr.io/danny-avila/librechat:latest<br>    ports:<br>      - &quot;3080:3080&quot;<br>    env_file:<br>      - ./librechat.env<br>    extra_hosts:<br>      - &quot;host.docker.internal:host-gateway&quot;<br>    volumes:<br>      - ./librechat.yaml:/app/librechat.yaml:ro<br>    depends_on:<br>      - mongodb<br><br>  mongodb:<br>    image: mongo:7<br>    volumes:<br>      - librechat_mongo_data:/data/db</pre><p>The interesting file is librechat.yaml. Unlike Open WebUI, LibreChat speaks MCP natively, so there is no OpenAPI bridge: you point it straight at the MCP server over streamable-http (the same server.py, run in http mode). It also exposes a custom endpoint for the local Ollama model, and the artifacts toggle I was there for:</p><pre>version: 1.2.1<br>interface:<br>  artifacts: true                 # the whole reason I tried LibreChat<br>endpoints:<br>  custom:<br>    - name: &quot;Ollama&quot;<br>      apiKey: &quot;ollama&quot;<br>      baseURL: &quot;http://host.docker.internal:11434/v1&quot;<br>      models:<br>        default: [&quot;qwen2.5:7b&quot;]<br>        fetch: true<br>mcpServers:<br>  f1-data:<br>    type: streamable-http<br>    url: &quot;http://mcpo:8000&quot;         # MCP server in http mode, no bridge<br>    timeout: 60000</pre><p>librechat.env is mostly generated secrets and the Mongo connection:</p><pre># librechat.env<br>HOST=0.0.0.0<br>MONGO_URI=mongodb://mongodb:27017/LibreChat<br>CONFIG_PATH=/app/librechat.yaml<br>CREDS_KEY=&lt;openssl rand -hex 32&gt;<br>CREDS_IV=&lt;openssl rand -hex 16&gt;<br>JWT_SECRET=&lt;openssl rand -hex 32&gt;<br>JWT_REFRESH_SECRET=&lt;openssl rand -hex 32&gt;<br>ALLOW_REGISTRATION=true</pre><p>With all that wired up, the artifacts never worked the way I hoped, I tried a prompt and it did not recreate the dashboard. There was something I was missing and could not make it work. After days of chasing the artifact, I gave up and looked for an alternative.</p><p>So I changed the target, and Metabase is what I reached for, specifically because of its MCP server. Metabase ships its own MCP that promised the two things I wanted: the agent could create charts and dashboards, <em>and</em> render them as inline charts during the chat. On paper that was the Cowork experience, open source.</p><p>Two things stopped this from working. First, the inline charts only render in frontier harnesses, the supported clients are Claude, Cursor, and ChatGPT; a self-hosted harness like LibreChat is not on the list, so the inline part was off the table for me from the start. Second, Metabase’s MCP expects the model to drive it through a multi-step, structured query format, and a small open-source model simply could not produce that reliably.</p><p>I stopped trying to use Metabase’s MCP as-is and added my own Metabase functions to my own MCP server instead. Rather than expose Metabase’s MBQL tools to the model, I wrote a plain Python function that takes a SQL SELECT, a chart type, and a title, and calls Metabase&#39;s REST API to create the question. It is registered in my MCP server exactly like the data tools, so to the model it is just another tool to call, no MBQL anywhere:</p><pre># tools/metabase.py  (registered in server.py alongside the data tools)<br>import httpx<br><br>def create_metabase_question(name, sql, display=&quot;table&quot;,<br>                             x_axis=None, y_axis=None, series=None,<br>                             collection=&quot;F1 Analytics&quot;):<br>    headers = {&quot;x-api-key&quot;: MB_API_KEY}            # service-account auth<br>    with httpx.Client(base_url=MB_BASE_URL, headers=headers) as mb:<br>        db_id   = _database_id(mb)                  # look up the &quot;F1 Silver&quot; db<br>        coll_id = _collection_id(mb, collection)    # a shared collection, not a hidden personal one<br><br>        viz = {}<br>        if x_axis and y_axis:                       # one series per category for multi-line charts<br>            dims = [x_axis, series] if series else [x_axis]<br>            viz = {&quot;graph.dimensions&quot;: dims, &quot;graph.metrics&quot;: [y_axis]}<br><br>        card = mb.post(&quot;/api/card&quot;, json={<br>            &quot;name&quot;: name,<br>            &quot;collection_id&quot;: coll_id,<br>            &quot;display&quot;: display,                     # bar | line | table | pie | row ...<br>            &quot;visualization_settings&quot;: viz,<br>            &quot;dataset_query&quot;: {                      # native SQL, not MBQL<br>                &quot;type&quot;: &quot;native&quot;,<br>                &quot;database&quot;: db_id,<br>                &quot;native&quot;: {&quot;query&quot;: sql},<br>            },<br>        }).json()<br>        return {&quot;url&quot;: f&quot;{MB_PUBLIC_URL}/question/{card[&#39;id&#39;]}&quot;}</pre><p>That is the whole trick: Metabase’s /api/card endpoint accepts a dataset_query of type native, which is just raw SQL. So I let the model do what it is good at, write a SELECT, and my function does the Metabase-specific part (auth header, look up the database id, drop it in a shared collection, set the chart type). The model never sees Metabase&#39;s API; it sees one tool: name, sql, display. Plain SQL is something even a 7B can produce (especially with the grounding I describe later); MBQL was not. (The real function also validates the SQL and retries on error, which I come to in the reliability section.) The chat became the place you <em>ask</em>; Metabase became the place the answer <em>lives</em>.</p><h4>Metabase forced a real database: DuckDB to Postgres</h4><p>Adding Metabase immediately broke an assumption I had carried over from Part 4: that the silver layer could live in a DuckDB file. That was fine when a single MCP process read it. But Metabase wants to hold a connection open, the pipeline wants to write, and the agent wants to read, all at once, and DuckDB is an embedded engine: one writer, file locks, no first-class Metabase driver. The single file was suddenly the bottleneck.</p><p>So I moved the serving copy of the silver layer into PostgreSQL, which was already in my stack. People hear “OLAP” and reach for something columnar, but at F1 data size, tens of thousands of rows, Postgres answers every one of these queries in milliseconds. Columnar engines like ClickHouse only start to matter at hundreds of millions of rows.</p><p>For the moment I left the transformation side alone: dbt still built silver in DuckDB and a small sync pushed it into a Postgres f1_silver schema, with the MCP reading that schema (at first through DuckDB&#39;s postgres extension, so my existing SQL kept working). More moving parts than I liked, but it worked, and I still had a bigger problem to solve. I come back and remove that DuckDB layer entirely near the end of this post.</p><h4>The model kept hanging, so I went back to Open WebUI</h4><p>With dashboards handled by Metabase, I was still using LibreChat as the chat interface, and that is where the real pain started. The model kept <em>hanging</em>. It would answer “I’m calling get_season_standings now…” and then just… stop. Or print the tool call as plain text instead of invoking it. At one point it stopped answering in English altogether and replied in a different language, a tell-tale sign the prompt had overflowed and the model was adrift. I genuinely should have taken a screenshot of that one, it captured the whole week. I tried everything: fewer tools, a bigger context window, a stricter system prompt, even renaming the endpoint to dodge special-casing.</p><p>The maddening part: the model itself was fine. When I called Ollama’s OpenAI-compatible API directly, the exact same model returned a clean, structured tool call every time. The problem lived entirely in how LibreChat’s agent harness fed tools to a small local model.</p><p>So I went back to Open WebUI, the same install and tool server I had set up at the start, this time not for artifacts but for the basic job LibreChat could not do: reliably call tools. The thing I had skipped over the first time turned out to be the whole game, one setting: Function Calling, set to Native.</p><p>In a chat’s model settings, Advanced Params, Function Calling has two modes. The default (“Default”) is prompt-based: it describes the tools in text and asks the model to format a call, which is exactly the brittle path that failed in LibreChat. Native uses the model’s real tool-calling API instead. I switched it to Native, created a Workspace model on f1-qwen with the system prompt and the tool server attached, and asked my first question. First try, it called the tool and answered correctly. LibreChat came out of the stack for good.</p><h4>The brutal reality of 16GB</h4><p>I am running this on a 16GB MacBook Air. Docker’s VM reserves about 7.6GB, macOS takes its share, and that leaves roughly 5–6GB for the model. A 14-billion-parameter model needs about 9–10GB, so it does not fit. It swaps to disk, and the whole thing hangs.</p><p>That forced me down to a 7B model. And a default Ollama context window (2048 tokens) was too small to even hold the tool definitions, so the model produced garbled, sometimes wrong-language output. I built a custom model, qwen2.5:7b with the context bumped to 16k and temperature dropped, and that fixed the garbling.</p><p>Here is the whole model setup, start to finish:</p><pre># 1. Install Ollama<br>#    macOS: download the app from https://ollama.com/download<br>#    Linux:<br>curl -fsSL https://ollama.com/install.sh | sh<br><br># 2. Pull a tool-capable model, then CHECK it actually supports tools<br>ollama pull qwen2.5:7b<br>ollama show qwen2.5:7b | grep -iA3 Capabilities<br>#   Capabilities<br>#     completion<br>#     tools        &lt;-- you need this line</pre><p>That check is not optional. I lost an afternoon to phi4:14b, which downloads fine but lists only completion under Capabilities, no tools, so it cannot drive an agent at all. Always confirm tools before building anything on a model.</p><p>Next, give the model a real context window with a Modelfile:</p><pre>cat &gt; Modelfile &lt;&lt;&#39;EOF&#39;<br>FROM qwen2.5:7b<br>PARAMETER num_ctx 16384<br>PARAMETER temperature 0.1<br>SYSTEM &quot;You are an F1 data assistant. Always respond in English. Use the provided tools to answer; never invent data.&quot;<br>EOF<br><br>ollama create f1-qwen -f Modelfile<br>ollama run f1-qwen &quot;say hi&quot;   # warms it into memory</pre><p>f1-qwen is what the rest of the stack points at.</p><p>But a 7B is a 7B. Left to its own devices it hallucinates column names, invents tables, filters on YEAR(race_date) when there is a perfectly good season column. The model fitting in memory is not the same as the model being <em>useful</em>.</p><h4>Making a weak model reliable</h4><p>This is the heart of Part 5. You cannot make a 7B smarter, but you can build scaffolding so it rarely needs to be. Four things, in order of impact:</p><p><strong>1. Validate before you save:</strong> My “make a chart” tool does not trust the model’s SQL. It dry-runs the SQL against the database first. If it fails, the tool returns the actual error <em>plus the schema</em> and refuses to save a broken chart. The model then tries again with the correction. A 7B usually gets there in two or three attempts, but the user only ever sees the working result.</p><p>2. <strong>Aggregate server-side; hand the model a sentence: </strong>When I asked for a Hamilton-vs-Verstappen head-to-head, the tool first returned all 135 races. The model choked on the volume and produced one word before giving up. The fix was to compute the answer in the tool and return a ready-made headline: <em>&quot;Across 135 shared races, Verstappen finished ahead 89 times to Hamilton&#39;s 44.&quot;</em> Small models are far better at repeating a sentence than at aggregating rows.</p><p><strong>3. Expose computed metrics as views:</strong> “Season completeness” is not a table, it is a calculation. So I made it a Postgres view. Now the model just SELECTs from season_completeness and charts it, instead of trying to derive coverage from scratch.</p><p><strong>4. Retrieve the semantic layer:</strong> This is the part I found genuinely interesting, and it gets its own section.</p><h4>The honest question: isn’t this cheating?</h4><p>Partway through, I had a crisis of confidence. I had started adding worked SQL examples to the tool descriptions, and the model “succeeded” mostly because I had handed it the answer. For instance, to get “wins per driver in 2023” working, I had pinned the exact query into the tool’s hint:</p><pre>-- a worked example baked into the tool description<br>SELECT d.full_name AS driver, SUM(f.is_win) AS wins<br>FROM f1_silver.fact_race_results f<br>JOIN f1_silver.dim_driver d ON f.driver_key = d.dim_driver_key<br>WHERE f.season = 2023<br>GROUP BY d.full_name ORDER BY wins DESC</pre><p>Of course the model nailed that question, I had written its answer. But ask for podiums per constructor, or anything I had not pre-written, and it was lost again. That is not intelligence; that is teaching to the test. Writing a bespoke example for every question means I am doing the work and taking the model’s credit, and it falls apart the moment someone asks something I did not anticipate.</p><p>The legitimate version of the same idea is retrieval. I already had a semantic layer from Part 4: a hand-written catalog of metric formulas, a glossary of F1 terms, and a library of query patterns (window functions, rolling averages, head-to-head, points gaps). Instead of pasting all of it into every prompt (which overflows a 7B), I added a search_knowledge step: given the question, score the patterns/metrics/glossary by relevance and feed back only the two or three that match.</p><p>The difference is real. A bespoke example is <em>the answer to one question</em>. A retrieved metric formula or query pattern is <em>a reusable building block the model composes itself</em>.</p><p>To check whether this actually generalised, I deliberately tested query shapes I had never written an example for. One was a rolling N-race form chart, a driver’s average finishing position over the last few races. For that, search_knowledge scores the library and returns the closest pattern, rolling_form, a parameterised template, not an answer:</p><pre>-- retrieved pattern: rolling_form<br>-- &quot;rolling average finishing position over the last N races&quot;<br>WITH driver_results AS (<br>  SELECT r.round, f.position<br>  FROM silver.fact_race_results f<br>  JOIN silver.dim_driver d ON f.driver_key = d.dim_driver_key<br>  JOIN silver.dim_races r  ON f.race_key   = r.dim_race_key<br>  WHERE d.full_name ILIKE &#39;%{driver_name}%&#39; AND f.season = {season}<br>)<br>SELECT round, position,<br>  AVG(position) OVER (<br>    ORDER BY round<br>    ROWS BETWEEN {window_size} PRECEDING AND CURRENT ROW<br>  ) AS rolling_avg_position<br>FROM driver_results ORDER BY round</pre><p>The model fills in the blanks itself, {driver_name} = Verstappen, {season} = 2024, {window_size} = 2 (two preceding rows plus the current one makes a 3-race window), and gets it right on the first try. I never wrote that query. I wrote the <em>pattern</em>, once, and the model adapted it. (The same retrieval also surfaces metric formulas, so a question about &quot;DNF rate per circuit&quot;, which I had never templated, pulls back dnf_rate = COUNT(*) FILTER (WHERE position_text = &#39;R&#39;)::numeric / COUNT(*) and the model composes it with a circuit join.) That is generalisation, not memorisation.</p><p>There was one more problem. A small model will not reliably <em>choose</em> to call a “search first” tool, even when told to. So I deliver retrieval three ways: as a tool it can call, pushed automatically into context before the model runs (in my reference script), and, the trick that made it work in Open WebUI, auto-attached to the validation error. When the model’s SQL fails, the tool retrieves the matching pattern and includes it in the error it sends back. Retrieval rides along on the tool the model already calls, so I do not depend on it remembering to ask.</p><h4>Where it breaks: valid but wrong</h4><p>Once it was working, I sat down and tested it properly: a handful of questions I could check against the database. Most came back right. The failures were the interesting part, because they were never broken SQL. They were SQL that ran cleanly and answered the wrong question.</p><p>Here is the actual scorecard, every answer verified against the warehouse:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4KCYKxWM2YIG9Gob7RVDGg.png" /></figure><ul><li>Points gap, Verstappen vs Norris, 2024 — <em>correct.</em> 55 points (399 − 344), exactly right.</li><li>Hamilton’s longest winning streak — <em>mostly correct.</em> It got 5 wins in 2020 (rounds 11 to 15), but mislabeled the race names at the ends of the streak.</li><li>Best average finishing position, 2023 — <em>wrong.</em> It answered “Hamilton.” The real answer is Verstappen at 1.27; Hamilton was third at 5.57.</li><li>Circuit with highest DNF rate — <em>correct.</em> Reims-Gueux, 88.9% (16 of 18), though it skipped the obvious small-sample caveat.</li></ul><p>The sharpest failure is the average-finishing-position one. Retrieval did its job: it surfaced <em>both</em> the avg_finishing_position metric (what the question needs, averaged across all drivers, then ranked) <em>and</em> the rolling_form pattern (one driver&#39;s form over a season). The model reached for the pattern, picked a driver out of nowhere (Hamilton), computed his rolling average, and declared him &quot;the best&quot;, without ever comparing drivers. The real answer is Max Verstappen at an average finish of 1.27; Hamilton was third at 5.57. The query ran without error. The answer was confidently, completely wrong.</p><p>The pattern across the tests is clear. Metric-on-a-dimension questions (“DNF rate per circuit”) and single-entity questions (“Hamilton’s longest win streak”) work: retrieval hands over the right formula or template and the model fills in the blanks. But superlatives that require ranking across entities (“which driver had the best…”) break: the model grabs a single-entity pattern, invents a subject, and asserts a winner it never actually computed. Even the wins it got right came with small slips, the streak’s endpoints were mislabeled, and the DNF answer skipped the obvious “that is an 18-race sample” caveat.</p><h4>What this costs in hardware</h4><p>Because the point of this is client deployments, here is the sizing I landed on. The binding constraint is running a model large enough for reliable analytical SQL <em>alongside</em> the data stack:</p><ul><li>16GB unified, a 7B model — proof of concept only. Reliable for simple aggregates, unreliable for nuanced analysis (this is the machine I built on).</li><li>32GB unified (or 16GB plus a 16 to 24GB GPU), a 14B model — the realistic minimum for a <em>good</em> single-user experience.</li><li>64GB unified (or a 24GB GPU), a 32B model — best local reasoning; light multi-user.</li></ul><p>A few honest caveats: on a Mac it is unified memory; on a Linux box the model lives in GPU VRAM and system RAM is separate. Fitting the model is not the same as it being <em>fast</em>, that tracks memory bandwidth and GPU. And concurrency pushes you up a tier, because one model instance serves one request at a time.</p><p>For a serious deployment, the architecture already decouples the model from the data services, so the clean shape is one GPU inference server with a lightweight data stack pointed at it.</p><h4>Cutting DuckDB loose</h4><p>By the time the agent was answering questions and publishing to Metabase, I went back to that transformation layer I had promised to tidy, and it embarrassed me. dbt built silver in DuckDB, a sync script copied it into Postgres, and the MCP read Postgres back <em>through</em> DuckDB’s postgres extension. Three hops where one would do, with DuckDB earning its keep at none of them. It had been the right tool in Part 4 and was now a middle layer that existed only because it used to.</p><p>So I cut it. dbt now builds silver directly in Postgres with the dbt-postgres adapter, reading the bronze schema dlt already loads there. The profile is just:</p><pre>data_platform_f1:<br>  target: prod<br>  outputs:<br>    prod:<br>      type: postgres<br>      host: &quot;{{ env_var(&#39;POSTGRES_HOST&#39;, &#39;postgres&#39;) }}&quot;<br>      port: &quot;{{ env_var(&#39;POSTGRES_PORT&#39;, &#39;5432&#39;) | int }}&quot;<br>      user: &quot;{{ env_var(&#39;POSTGRES_USER&#39;, &#39;dagster&#39;) }}&quot;<br>      password: &quot;{{ env_var(&#39;POSTGRES_PASSWORD&#39;, &#39;dagsterpass&#39;) }}&quot;<br>      dbname: &quot;{{ env_var(&#39;POSTGRES_DB&#39;, &#39;dagster&#39;) }}&quot;<br>      schema: f1_silver<br>      threads: 4</pre><p>The migration was almost free, because the silver models were already plain SQL. The only DuckDB-ism I had to rewrite was date formatting in the date dimension (strftime to Postgres to_char). The sync script was deleted, and the MCP server now reads Postgres directly with psycopg, no engine in between. One store, one query path.</p><h4>Running the whole stack</h4><p>The same docker-compose.yaml from the first section grew to its final shape: the open-webui and mcpo-openapi services I started with, now joined by postgres (the serving layer) and metabase. Four services, one command. Ollama is the deliberate exception, it runs on the host (not in Docker) so the model gets the machine’s full memory and GPU. Because Metabase sits on the same data_platform network, the MCP server reaches it at <a href="http://metabase:3000/">http://metabase:3000</a>, with an API key to publish.</p><pre>services:<br>  postgres:        # serving layer: the f1_silver schema<br>    image: postgres:15<br>    ports:<br>      - &quot;5432:5432&quot;<br><br>  mcpo-openapi:    # MCP server exposed as OpenAPI on :8001<br>    build:<br>      context: ..<br>      dockerfile: infrastructure/mcpo.Dockerfile<br>    command: [&quot;mcpo&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8001&quot;, &quot;--&quot;, &quot;python&quot;, &quot;server.py&quot;]<br>    environment:<br>      - PG_HOST=postgres<br>      - PG_PORT=5432<br>      - PG_DB=dagster<br>      - PG_USER=dagster<br>      - PG_PASSWORD=dagsterpass<br>      - PG_SILVER_SCHEMA=f1_silver<br>      - MB_BASE_URL=http://metabase:3000        # for publishing charts<br>      - MB_PUBLIC_URL=http://localhost:3002<br>      - MB_API_KEY=${METABASE_API_KEY}<br>      - MB_DATABASE_NAME=F1 Silver<br>      - MB_DEFAULT_COLLECTION=F1 Analytics<br>    ports:<br>      - &quot;8001:8001&quot;<br>    depends_on:<br>      - postgres<br>      - metabase<br><br>  metabase:        # BI / dashboards on :3002<br>    image: metabase/metabase:latest<br>    ports:<br>      - &quot;3002:3000&quot;<br>    environment:<br>      MB_DB_TYPE: h2<br>      MB_DB_FILE: /metabase-data/metabase.db<br>    volumes:<br>      - metabase_data:/metabase-data<br>    depends_on:<br>      - postgres<br><br>  open-webui:      # chat interface on :3000<br>    image: ghcr.io/open-webui/open-webui:main<br>    environment:<br>      - OLLAMA_BASE_URL=http://host.docker.internal:11434<br>      - WEBUI_SECRET_KEY=local-dev-only<br>    extra_hosts:<br>      - &quot;host.docker.internal:host-gateway&quot;<br>    volumes:<br>      - open_webui_data:/app/backend/data<br>    ports:<br>      - &quot;3000:8080&quot;<br>    depends_on:<br>      - mcpo-openapi</pre><pre>docker compose up -d</pre><p>Metabase needs a one-time setup: create the admin account, connect it to the same Postgres f1_silver database, and mint an API key (Settings, Admin, API Keys) that the MCP server uses to publish questions. After that, when the agent calls create_metabase_question, the chart appears in Metabase and the agent hands back the URL.</p><p>That is the entire loop: ask in Open WebUI, the model calls a tool over the OpenAPI bridge, the MCP server queries Postgres or writes a Metabase chart, and the answer (or a link) comes back, with nothing leaving the machine.</p><h3>Conclusion</h3><p>I set out to prove the Part 4 experience could run with nothing leaving the machine. It can. The data lives in Postgres, the model runs in Ollama, Open WebUI is the interface, and Metabase holds the dashboards, all local, all open source.</p><p>But the lesson is not “local is as good as hosted.” It is that local AI is an engineering discipline of its own. A hosted frontier model lets you be lazy about grounding; a local 7B punishes every gap in your semantic layer immediately. The work moves from <em>asking</em> to <em>scaffolding</em>, validation, retrieval, server-side aggregation, views. Do that work and a small local model becomes genuinely useful for a real class of questions.</p><p>Three things I am carrying forward:</p><ol><li>Retrieval over a semantic layer beats hand-fed examples. It is the difference between a model that generalises and a demo that only works on the questions you rehearsed.</li><li>Size the hardware to the model you actually need, not the one that fits. 32GB and a 14B is where the models are impressive for open weights.</li><li>Remove the tool that no longer earns its place. DuckDB was right in Part 4 and dead weight by Part 5. Cutting it left dbt building straight into Postgres and the agent reading straight from it: one store, one query path, fewer things to break.</li></ol><p>Still open: inline chart rendering in the chat and per-user identity for proper RBAC on created dashboards. And, when the hardware allows, a 14B or 32B to push past the comprehension ceiling I hit.</p><p><em>The local stack, PostgreSQL, an MCP server, Metabase, and Open WebUI with Ollama, is open source end to end. Code for the data pipeline and MCP server can be found </em><a href="https://github.com/yvonnegitau/Data-Platform-Agent-Builder/tree/feature/openwebui-coverage-dashboard"><em>here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d20794764a9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Journal: Dagster + dlt + DuckDB + Claude — Part 4]]></title>
            <link>https://medium.com/@ywg/my-journal-dagster-dlt-duckdb-claude-part-4-f1d0dfa86bd4?source=rss-5161d83115ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1d0dfa86bd4</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[duckdb]]></category>
            <category><![CDATA[dagster]]></category>
            <dc:creator><![CDATA[Wambui Gitau]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 05:01:01 GMT</pubDate>
            <atom:updated>2026-06-09T05:01:01.576Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@ywg/my-journal-dagster-dlt-duckdb-dbt-part-3-fa155ab6ebcd">Part 3</a>, I promised to start a new series on making the F1 data warehouse conversational. I said I was planning to use a custom LangChain + dbt + Streamlit stack. Well, that plan changed.<br>I ended up using <a href="https://claude.ai/">Claude’s Cowork mode</a> instead (I discovered live artifacts and i’m like a child in playing with their new toy), which let me talk directly to the data platform I had built and produce a fully interactive monitoring dashboard without writing a frontend framework from scratch. This post is about what I found when I finally looked at my own data.</p><h3>Context</h3><p>Just to recap where we are: over the first three parts of this series, I built a data pipeline for F1 data using Dagster, dlt, PostgreSQL, dbt, and DuckDB. The architecture ingests data from the Ergast/Jolpi F1 API, stages it in PostgreSQL and models it into a silver layer in DuckDB using the Kimball approach.</p><p>The silver layer has these tables:</p><ul><li>fact_race_results — one row per driver per race</li><li>dim_driver, dim_constructor, dim_circuit, dim_races, dim_status</li></ul><p>Up to Part 3, I was focused on the pipeline. I had never really sat down and asked: <em>is my data any good?</em> This part is that reckoning.</p><h3>The AI Layer I Actually Used</h3><p>My original plan was LangChain + Streamlit. A lot has changed since I wrote Part 3.</p><p>When I wrote the first three parts of this series, AI tools were largely conversational; you described a problem, got a suggestion, copied it into your editor, and took it from there. That is still the mode I was in when I wrote Part 1. Since then, the shift has not just been about better code generation. The bigger change is that AI moved from chat to agents. Models can now take actions: read files, run queries, call APIs, produce artifacts. People are no longer just talking about their data, they are having agents do actual work on it, like building dashboards or generating reports, without a separate frontend project in the way.</p><p>That context problem is exactly what the MCP (Model Context Protocol) server pattern solves. Instead of describing my schema to an AI and hoping it generates correct SQL, I connected Claude directly to my DuckDB silver layer via an F1 MCP server. Claude could inspect the actual tables, run queries, see the results, and iterate all within a single conversation.</p><p>The reason I chose this approach over Streamlit was the <strong>live artifacts</strong> feature in Claude’s Cowork mode. Rather than building a dashboard in a separate app and deploying it, I could produce interactive HTML artifacts that query the MCP server live each time they are opened. The loop was: ask a question, get SQL results, turn those results into a dashboard, reopen it next week and get fresh data. No infrastructure to manage on the frontend side.</p><p>I was skeptical about how well this would work in practice. Code assistants have let me down before on data engineering tooling (see Lesson 1 in Part 1). But this felt different, the model was not guessing at my schema, it was reading it directly. What I did not expect was how much the process would reveal about my own data.</p><h4>The MCP Server and the Semantic Layer</h4><p>Before getting to what I found in the data, it is worth explaining what the MCP server actually does, because it is not just a query endpoint.</p><p>The server (server.py) connects to Claude via stdin/stdout using the <a href="https://modelcontextprotocol.io/">Model Context Protocol</a>. When Claude opens the connection it sees a list of tools, reads their descriptions and decides which ones to call based on what you ask. The key design decision was splitting the tools into three groups.</p><p><strong>Semantic layer tools — </strong>these exist so that Claude understands the data before writing any SQL:</p><ul><li>get_schema — returns the full column definitions and join keys for any table. Every column has a business description, not just a data type.</li><li>get_metric_definition — returns the exact SQL formula for metrics like win_rate, dnf_rate, podium_rate. This avoids Claude inventing its own definition of &quot;win rate&quot; each time.</li><li>get_query_pattern — returns worked SQL templates for common patterns: window functions, rolling averages, head-to-head comparisons, streaks. Claude adapts these rather than writing from scratch.</li><li>get_glossary — F1 domain terms with their meaning in the data. For example: what DNF means, that the points system changed in 2010, that comparing raw points across eras is misleading.</li></ul><p>All of this lives in YAML files in the semantic/ folder: catalog.yaml for table and metric definitions, glossary.yaml for domain terms, query_patterns.yaml for SQL templates. The semantic layer is not generated — it is hand-written and it is the most important part of the whole setup.</p><blockquote>The quality of the AI’s SQL is directly proportional to the quality of the semantic layer. If the catalog is vague, the queries will be wrong. If the metric definitions are precise, the answers will be precise.</blockquote><p><strong>Raw SQL tool</strong> — execute_sql runs any read-only SELECT against the DuckDB silver layer. Claude uses this when the pre-built tools do not cover the question being asked.</p><p><strong>Data product tools</strong> — pre-built analytical tools for the most common questions: get_driver_career, get_season_standings, compare_drivers, get_greatest_races, get_constructor_history, get_circuit_stats. These are Python functions that run curated SQL, format the output, and return structured results. They are faster and more consistent than letting Claude write the same query repeatedly.</p><p>The combination means Claude almost never has to guess. It reads the schema, checks the metric definition if needed, picks up a query pattern if one fits, and falls back to raw SQL only for novel questions.</p><h4>Discovery 1: My Data Coverage Was… Interesting</h4><p>The first thing I asked was a simple overview: how many seasons, races, drivers, constructors are in the database?</p><p>The answer: 14 seasons, spanning 1950 to 2026. F1 has run 77 seasons since 1950. That means my pipeline had loaded <strong>18% of all seasons</strong>.</p><p>I was not surprised by this, the backfill is deliberate and ongoing. What I was curious about was <em>which</em> seasons. Turns out:</p><ul><li><strong>1950–1956</strong>: present (7 seasons, early era)</li><li><strong>1957–2019</strong>: completely missing (63 seasons)</li><li><strong>2020–2026</strong>: present (modern era, 2026 in progress)</li></ul><p>The gap from 1957 to 2019 is my main backfill target. This is expected since I prioritised the modern era for the initial load. But seeing it laid out clearly made it feel more real and more urgent.</p><p>What I did not expect was what came next when I drilled into the round-level coverage.</p><p>My first query on fact_race_results showed only 4–5 rounds loaded per modern season specifically rounds 1, 6, 11, 16, and 21. I spent a while looking at this, assuming the pipeline had sampled every fifth race during the backfill. I wrote this in my notes: <em>&quot;fact table appears to be sampled at ~20% per season, rounds 1, 6, 11, 16, 21.&quot;</em></p><p>My first instinct was to blame the query. The MCP execute_sql tool has a default row limit of 100, and a full season with 22 rounds × 20 drivers = 440 rows. It was plausible that the result set was being silently truncated. So I re-ran the query correctly — grouping by season and round directly against fact_race_results with no JOIN and no row cap:</p><pre>SELECT season, round, COUNT(*) as entries<br>FROM silver.fact_race_results<br>GROUP BY season, round<br>ORDER BY season, round</pre><p>The same 4–5 rounds came back. This time I could not blame the query. The data really was sparse.</p><p>The actual cause was in the pipeline. The dlt resource was only processing the first page of the API response. The F1 API paginates race results, and the pagination processing was not implemented correctly — it fetched page one and stopped. Rounds 1, 6, 11, 16, 21 happened to fall on the first page boundary for the offset and limit values I had configured.</p><p>This is exactly the kind of bug that a monitoring dashboard surfaces and a unit test does not. The pipeline ran successfully every time — no errors, no failures, clean Dagster logs. It was just quietly loading partial data on each run.</p><blockquote>A pipeline that runs without errors is not the same as a pipeline that loads complete data. Silent pagination bugs are particularly hard to catch because the success signal is genuine — just incomplete.</blockquote><h4>Discovery 2: SQL Can Lie to You Politely</h4><p>This is the lesson I am most embarrassed to write about, because it is something I should have caught.</p><p>The first pass at coverage analysis used INNER JOINs throughout:</p><pre>SELECT f.season, COUNT(DISTINCT f.driver_key) as drivers<br>FROM silver.fact_race_results f<br>JOIN silver.dim_driver d ON f.driver_key = d.dim_driver_key<br>GROUP BY f.season<br>ORDER BY f.season</pre><p>This returned results only for seasons where both the fact rows <em>and</em> the dimension records existed and matched. The early era seasons (1950–1956) vanished completely, not because the data was missing, but because the INNER JOIN silently dropped any rows it could not match across both tables.</p><p>The fix was simple, use LEFT JOINs from dim_races outward, so unmatched rows show up as nulls rather than disappearing:</p><pre>SELECT r.season,<br>  COUNT(DISTINCT r.round) AS dim_rounds,<br>  COUNT(DISTINCT CASE WHEN f.race_key IS NOT NULL THEN r.round END) AS fact_rounds<br>FROM silver.dim_races r<br>LEFT JOIN silver.fact_race_results f ON f.race_key = r.dim_race_key<br>GROUP BY r.season<br>ORDER BY r.season</pre><p>With this query, the early era seasons came back — with fact data intact. The dimension key joins were clean for all 14 seasons. The data was never broken. I just was not looking for it properly.</p><blockquote>A query that returns no rows is not the same as data that does not exist. Always LEFT JOIN when you are auditing coverage, not when you are querying for analysis.</blockquote><h4>Discovery 3: How I Was Measuring DNFs Was Wrong</h4><p>Once the coverage checks were sorted, I moved on to building a results dashboard. One of the summary cards showed DNF counts per season. For all seasons, it showed zero. I knew that was wrong — there are always retirements in F1.</p><p>The assumption in my code was:</p><pre>dnfs = rows.filter(r =&gt; r.position === null).length</pre><p>I assumed DNF drivers would have a null position. They do not. Every driver gets a position value in the database, including those who retired. The actual retirement information is in status_category:</p><pre>SELECT DISTINCT status_category, status_description<br>FROM silver.dim_status<br>ORDER BY status_category</pre><p>The categories are: Completed, Lapped, Mechanical Failure, Accident, Did Not Start, Disqualified, Other. A &quot;finished&quot; result is only Completed or Lapped. Everything else is a non-finish.</p><p>So the correct logic was:</p><pre>const FINISHED = new Set([&#39;Completed&#39;, &#39;Lapped&#39;]);<br>const dnfs = rows.filter(r =&gt; !FINISHED.has(r.status_category)).length;</pre><p>For 2024 this gave 54 non-finishes (49 retirements, 2 disqualifications, 3 DNS). That is much more believable.</p><blockquote>If a field is described as “finishing position,” test the assumption that non-finishers have a null value. They may not.</blockquote><h4>Discovery 4: Sprint Races Do Not Exist in My Database</h4><p>The final thing I noticed was that championship points in my dashboard were consistently lower than the official F1 website. For 2026 after 5 rounds, my dashboard showed Kimi Antonelli on 118 points. The official site showed 131. A 13-point gap.</p><p>The reason: sprint races. Since 2021, some rounds include a sprint race with its own points (8–7–6–5–4–3–2–1 for P1–P8). My pipeline only ingests main race results. Sprint results were never loaded for any season.</p><p>This affects 6 seasons in my database:</p><pre>| Season | Sprints |<br>|--------|---------|<br>| 2021   | 3       |<br>| 2022   | 3       |<br>| 2023   | 6       |<br>| 2024   | 6       |<br>| 2025   | 6       |<br>| 2026   | ongoing |</pre><p>There are no sprint entries in dim_races at all. This is a schema-level gap, not just missing rows — the data model needs to be extended to support sprint results as a separate entity.</p><blockquote>An incomplete pipeline is not just about missing rows. It can mean entire event types were never modelled.</blockquote><h4>What I Built</h4><p>Using Claude’s Cowork mode throughout this investigation, I ended up with two live dashboards:</p><p><strong>Coverage Dashboard</strong> — an overview of what is actually in the database: season timeline, round-level heatmap per season, table coverage by layer, and the sprint gap prominently flagged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*387XYcZD56wXDnFnZnZP0w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UJSXCTXoXPWvfffeo0kDNA.jpeg" /><figcaption>Coverage Dashboard on Live Artifacts</figcaption></figure><p><strong>Results Dashboard</strong> — a season explorer with four tabs:</p><ul><li><strong>Races</strong>: full race-by-race results with round/driver filters and correct DNF/DNS/DSQ badges</li><li><strong>Drivers</strong>: an animated bar chart race showing the championship standings evolving round by round (the one I am most proud of)</li><li><strong>Constructors</strong>: cumulative points chart per team with standings table</li><li><strong>Schedule</strong>: full race calendar with completion status</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tslzrq_dIqb2tVhTwqbsoQ.jpeg" /><figcaption>Results Dashboard on Live artifacts</figcaption></figure><p>The animated championship viz was built entirely in vanilla JavaScript — no charting library — using CSS transitions on absolutely-positioned div elements. Bars slide up and down as the standings change, with play/pause/speed controls and a round scrubber.</p><h3>Conclusion</h3><p>I came into this expecting to spend most of the time on the AI interface. I ended up spending most of the time rediscovering gaps in my own data. That is probably the right order of events for any data project since you cannot trust a dashboard you have not stress-tested and stress-testing means going back to the queries.</p><p>The three key things I will carry forward:</p><ol><li><strong>LEFT JOIN for auditing, INNER JOIN for analysis.</strong> These are different queries with different purposes. Mixing them up hides data you actually have.</li><li><strong>Always check tool and query limits before concluding data is missing.</strong> A 100-row default cut off a 440-row result set and I misread it as a data gap for most of a session.</li><li><strong>Sprint races need their own modelling.</strong> The Ergast API has sprint results at /ergast/f1/{year}/sprint.json. I need to add this as a new resource in the dlt source and extend the dbt models to include it.</li></ol><p>The backfill for 1957–2019 and the sprint race modelling are the two main things left before the data layer is reliable enough for deeper analysis.</p><h4>What If You Want to Self-Host Everything?</h4><p>Everything I have described so far uses Claude as the AI layer. Claude is not open source, and Cowork mode is a hosted product. For teams or individuals who want to run the full stack themselves — model, interface, and data — there is an open source path worth thinking about.</p><p>The good news is that the most important parts are already portable. The MCP protocol is open — the F1 MCP server will work with any MCP-compatible client, not just Claude. The semantic layer (the YAML catalog, glossary, and query patterns) is plain files. The DuckDB silver layer is already self-hosted. The only things that need replacing are the model and the agent interface.</p><p>For the model, <a href="https://ollama.com/">Ollama</a> is the obvious starting point — it handles local model serving with a single command and supports models that perform well on SQL generation.</p><p>For the interface, this is where I am still doing research. All this will form part of what I will be implementing next. Hoping to discover interesting open source tools.</p><p>The dashboards were built using <a href="https://claude.ai/">Claude’s Cowork mode</a> with an F1 MCP server connected to the DuckDB silver layer. Code for the data pipeline and MCP server can be found<a href="https://github.com/yvonnegitau/Data-Platform-Agent-Builder/tree/feature/mcp-server"> here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1d0dfa86bd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Journal: Dagster + dlt + DuckDB + dbt Part 3]]></title>
            <link>https://medium.com/@ywg/my-journal-dagster-dlt-duckdb-dbt-part-3-fa155ab6ebcd?source=rss-5161d83115ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa155ab6ebcd</guid>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[dlt]]></category>
            <category><![CDATA[dagster]]></category>
            <category><![CDATA[duckdb]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Wambui Gitau]]></dc:creator>
            <pubDate>Mon, 08 Sep 2025 05:02:01 GMT</pubDate>
            <atom:updated>2025-09-08T05:02:01.640Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will highlight how dbt, DuckDB and Dagster work together. I will explore data modeling in dbt that will use Dagster to orchestrate the jobs.</p><h4>Duckdb or Duckengine as I want to call it</h4><blockquote>I finally get to work with DuckDB in the project. Just a heads up for those who choose it: it needs patience. It took me 1 week of troubleshooting (2 hours a day) to figure out why I kept getting permission denied when I ran dbt models. At first, I thought it was an issue with Docker file permissions. The problem: I had DBeaver running while running the dbt job on Dagster.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*jtHAH7vi7RuLHia4Po3UzA.gif" /></figure><p>I have been treating DuckDB like traditional databases, and that is why I found it difficult to work with. The concurrency issue is bigger than people think, and you only need to experience the frustration to comprehend it.</p><p>So when people say they have it as a data warehouse in production, I’m genuinely curious about how they’ve architected around the concurrency limitations. In my experience, I think I will wait until this is addressed, or alternatively use it as a query engine, which it truly excels at. Hence my personal nickname ‘DuckEngine.’ I’d love to hear from others who have successfully deployed DuckDB as a production data warehouse. What patterns and workarounds have worked for you?</p><p>Another use case would be to set up workstations as containers for internal analysts to do their internal data analysis, as long as they are not sharing the data file (back to concurrency).</p><p><em>Note: I will update you on whether you can run dbt jobs while a dashboard that is getting data from DuckDB is connected.</em></p><p><strong>Before we start, some quick fixes:</strong></p><ul><li>The partition was not getting to 2025. Had to add end_offset=1 in the f1_assets.py</li></ul><pre>yearly_partitions = TimeWindowPartitionsDefinition(<br>    cron_schedule=&quot;0 0 1 1 *&quot;,  # Yearly: Jan 1st at midnight<br>    start=&quot;1950-01-01&quot;,<br>    fmt=&quot;%Y-%m-%d&quot;,<br>    end_offset=1,<br>)</pre><ul><li>The scheduler was not working. This was because it was not getting the partition key. Changed the schedule jobs in repo.py</li></ul><pre>current_partition = yearly_partitions_def.get_partition_keys(<br>        context.scheduled_execution_time<br>    )</pre><ul><li>There is a new way for starting the Dagster code server. I tried it and had to revert to the old one since the containers kept dropping during runs. Below is the new command:</li></ul><pre>dagster code-server start</pre><h4>Integrating dbt and Dagster</h4><p>The first step is to integrate the two components. My implementation has dbt in a separate directory. I followed the following steps:</p><ul><li>Create a <a href="https://docs.getdbt.com/guides/manual-install?step=3">dbt project</a> and make sure it has <strong>project.yml</strong> and <strong>dbt_project.yml</strong></li><li>Add the dbt code to the dagster code image</li></ul><pre>COPY code/data-platform/core/processing/dbt/data_platform_f1/ /opt/dbt/app/</pre><ul><li>Add the configs to the project.yml file</li></ul><pre>data_platform_f1:<br>  target: dev<br>  outputs:<br>    dev:<br>      type: postgres<br>      host: &quot;{{ env_var(&#39;DAGSTER_POSTGRES_HOST&#39;) }}&quot;<br>      user: &quot;{{ env_var(&#39;DAGSTER_POSTGRES_USER&#39;) }}&quot;<br>      password: &quot;{{ env_var(&#39;DAGSTER_POSTGRES_PASSWORD&#39;) }}&quot;<br>      dbname: &quot;{{ env_var(&#39;DAGSTER_POSTGRES_DB&#39;) }}&quot;<br>      port: 5432<br>      schema: f1_bronze<br>      threads: 4</pre><ul><li>Create the data/medallion folder where you will store the .duckdb file on your local machine. An option would have been to use Docker volumes. However, if you would like to use a client to view the data, you will need to mount the folder on a local folder which can be connected to a client like DBeaver.</li><li>Add the arg and env on the dockerfile</li></ul><pre>ARG DAGSTER_POSTGRES_HOST<br>ARG DAGSTER_POSTGRES_PORT<br>ARG DAGSTER_POSTGRES_DB<br>ARG DAGSTER_POSTGRES_USER<br>ARG DAGSTER_POSTGRES_PASSWORD<br><br>ENV DAGSTER_POSTGRES_HOST=${DAGSTER_POSTGRES_HOST}<br>ENV DAGSTER_POSTGRES_PORT=${DAGSTER_POSTGRES_PORT}<br>ENV DAGSTER_POSTGRES_DB=${DAGSTER_POSTGRES_DB}<br>ENV DAGSTER_POSTGRES_USER=${DAGSTER_POSTGRES_USER}<br>ENV DAGSTER_POSTGRES_PASSWORD=${DAGSTER_POSTGRES_PASSWORD}<br><br>RUN mkdir -p /tmp/build-logs &amp;&amp; chmod 755 /tmp/build-logs<br><br>WORKDIR /opt/dbt/app<br>RUN dbt deps --profiles-dir /opt/dbt/app || echo &quot;No packages to install&quot;<br><br><br>RUN echo &quot;=== DBT COMPILE START ===&quot; &amp;&amp; \<br>    dbt compile --profiles-dir /opt/dbt/app --profile data_platform_f1 2&gt;&amp;1 | tee /tmp/build-logs/dbt-compile.log &amp;&amp; \<br>    echo &quot;=== DBT COMPILE COMPLETE ===&quot; &amp;&amp; \<br>    echo &quot;=== DBT COMPILE LOG ===&quot; &amp;&amp; \<br>    cat /tmp/build-logs/dbt-compile.log &amp;&amp; \<br>    echo &quot;=== END DBT COMPILE LOG ===&quot; || \<br>    (echo &quot;=== DBT COMPILE FAILED ===&quot; &amp;&amp; \<br>     echo &quot;=== ERROR LOG ===&quot; &amp;&amp; \<br>     cat /tmp/build-logs/dbt-compile.log &amp;&amp; \<br>     echo &quot;=== END ERROR LOG ===&quot; &amp;&amp; \<br>     echo &quot;Will retry at runtime&quot;)</pre><p>For the asset to run, the manifest.json file needs to exist hence the <strong>dbt compile</strong> command.</p><ul><li>Add the env to the dagster.yml file</li></ul><pre>run_launcher:<br>  module: dagster_docker<br>  class: DockerRunLauncher<br>  config:<br>    env_vars:<br>      - DAGSTER_POSTGRES_USER<br>      - DAGSTER_POSTGRES_PASSWORD<br>      - DAGSTER_POSTGRES_DB<br>      - DAGSTER_POSTGRES_HOST</pre><ul><li>Create an asset</li></ul><pre>from pathlib import Path<br>from dagster_dbt import (<br>    DbtCliResource,<br>    DbtProject,<br>    dbt_assets,<br>)<br>import dagster as dg<br><br># Define your dbt project<br>dbt_project = DbtProject(project_dir=Path(&quot;/opt/dbt/app&quot;))<br><br><br>@dbt_assets(manifest=dbt_project.manifest_path, project=dbt_project, select=&#39;staging&#39;) # Running only staging models<br>def my_dbt_assets(context: dg.AssetExecutionContext, dbt: DbtCliResource):<br>    yield from dbt.cli([&quot;build&quot;], context=context).stream()</pre><ul><li>Add the asset to the definition</li></ul><pre>from dbt_pipeline import asset<br><br>all_assets = load_assets_from_modules([f1_assets, asset])<br><br># Define dbt resource<br>dbt_resource = DbtCliResource(<br>    project_dir=&quot;/opt/dbt/app&quot;,<br>    profiles_dir=&quot;/opt/dbt/app&quot;,<br>    profile_name=&quot;data_platform_f1&quot;,  # Explicit profile name<br>    target=&quot;dev&quot;,<br>)<br><br>defs = Definitions(<br>    assets=all_assets,<br>    jobs=[f1_static_job, f1_race_details_job, f1_yearly_job],<br>    resources={<br>        &quot;dlt&quot;: DagsterDltResource(),<br>        &quot;io_manager&quot;: dg.fs_io_manager,<br>        &quot;dbt&quot;: dbt_resource,<br>    },<br>    executor=dg.in_process_executor,<br>    schedules=[<br>        f1_race_season_schedule,<br>        f1_static_yearly_schedule,<br>        f1_yearly_schedule,<br>    ],<br>)</pre><p>You should be able to see the asset in the Dagster UI.</p><h4>Staging Area</h4><p>Before I started data modeling, I cleaned and standardized the data. This is where we create the base models that will be used downstream. The big questions I had when working on the staging models were:</p><ul><li>Does it belong to bronze or silver layer?<br>- <em>This should be bronze because there is no joins or aggregation taking place. Some people however place it in the silver layer. It depends on the organization.</em></li><li>Should I use incremental table or view and should I also used SCD here<br>- <em>You should use a materialized table here. Since there is nothing being joined or aggregated, it is faster to rebuild the whole table and also easier to rollback</em></li></ul><p>I created a staging folder in dbt and added the staging models there. The models that I will use for this use case are:</p><ul><li>drivers</li><li>constructors</li><li>circuits</li><li>races</li><li>results</li><li>status</li><li>driver_standings</li><li>constructor_standings</li></ul><p>I indexed the models using btree. The reason behind this is because:</p><ul><li>it maintains sorted order</li><li>it is efficient for ranges and exact matches</li><li>uses O(log n) lookup time</li></ul><p>The main addition of the models to the raw table was the data quality column. This column was used to filter out the rows that were not valid. Valid rows had to have the primary keys and other main columns. Below is an example of the circuits staging model:</p><pre>{{<br>    config(<br>        indexes=[<br>            {&#39;columns&#39;: [&#39;circuit_id&#39;], &#39;type&#39;: &#39;btree&#39;, &#39;unique&#39;:true}<br>        ]<br>    )<br>}}<br><br>with source_data as (<br>    select<br>     -- primary key<br>     &quot;circuit_id&quot; as circuit_id,<br><br>     -- circuit information<br>        &quot;circuit_name&quot; as circuit_name,<br>        &quot;location_country&quot; as circuit_country,<br>        &quot;location_lat&quot; as circuit_latitude,<br>        &quot;location_long&quot; as circuit_longitude,<br>        &quot;location_locality&quot; as circuit_locality,<br>        &quot;url&quot; as circuit_url,<br><br>        -- data quality<br>        case <br>            when &quot;circuit_id&quot; is null then &#39;MISSING_CIRCUIT_ID&#39;<br>            when &quot;circuit_name&quot; is null then &#39;MISSING_CIRCUIT_NAME&#39;<br>            when &quot;location_country&quot; is null then &#39;MISSING_COUNTRY&#39;<br>            else &#39;VALID&#39;<br>        end as data_quality,<br><br>        date_extracted_at::timestamp as extracted_at,<br>        CURRENT_TIMESTAMP as processed_at<br><br>        from {{ source(&#39;f1_bronze&#39;,&#39;circuits&#39;)}}<br>        where &quot;circuit_id&quot; is not null<br>), <br><br>cleaned_circuits as (<br>    select *<br>    from source_data<br>    where data_quality = &#39;VALID&#39;<br>)<br>select *<br>from cleaned_circuits   </pre><p>In the schema file, I added some data quality checks to the models. Some checks included ensuring that the combination of columns that were used as indexes were unique, making sure that the correct options for the data quality column were used, and the other was just data types.</p><pre>- name: stg_constructors<br>    description: &quot;Cleaned and standardized constructor data&quot;<br>    tests:<br>      - dbt_utils.unique_combination_of_columns:<br>          combination_of_columns: [constructor_id, season]<br>    columns:<br>      - name: constructor_id<br>        description: &quot;Unique identifier for the constructor&quot;<br>        data_type: VARCHAR<br>        tests:<br>          - not_null<br>      - name: constructor_name<br>        description: &quot;Name of the constructor&quot;<br>        data_type: VARCHAR<br>        tests:<br>          - not_null<br>      - name: nationality<br>        description: &quot;Nationality of the constructor&quot;<br>        data_type: VARCHAR<br>        tests:<br>          - not_null<br>      - name: constructor_url<br>        description: &quot;URL for more information about the constructor&quot;<br>        data_type: VARCHAR<br>      - name: data_quality_flag<br>        description: &quot;Flag indicating data quality issues&quot;<br>        data_type: VARCHAR<br>        tests:<br>          - accepted_values:<br>              values: [&#39;VALID&#39;, &#39;MISSING_NAME&#39;, &#39;INVALID&#39;]<br>      - name: extracted_at<br>        description: &quot;Timestamp when the data was extracted&quot;<br>        data_type: TIMESTAMP<br>        tests:<br>          - not_null<br>      - name: processed_at<br>        description: &quot;Timestamp when the data was processed&quot;<br>        data_type: TIMESTAMP<br>        tests:<br>          - not_null</pre><h4>Understanding Kimball Data Modelling with the F1 data</h4><blockquote>This is more for my own notes since I have been reading the Kimball book again.</blockquote><p>The Kimball methodology focuses on creating a star schema with fact tables and dimension tables optimized for analytics. Below are the methodology steps to follow:</p><ul><li><strong>Identify Business Process</strong></li></ul><p>For this use case, the business process is <strong>F1 race performance analysis</strong>. This is analyzing driver and constructor performance across races, seasons, and circuits.</p><ul><li><strong>Declare the Grain</strong></li></ul><p>The lowest grain to analyse is results for this data set. We will use <strong>one row per result per driver per race. </strong>I would like to go deeper and add more data to the laps information from <a href="https://openf1.org/#introduction">OpenF1</a></p><ul><li><strong>Identify Dimensions and Facts</strong></li></ul><p>I created dimension tables for the main objects and added some more information about them. The dimensions created are as follows:</p><ul><li>races</li><li>circuit</li><li>driver</li><li>constructor</li><li>status</li><li>date</li></ul><p>Now to the fact table. One table per business process. The whole point was to create a table that will have driver race results per row.</p><p>In dbt, I added tests which came in handy to identify interesting facts about the data. An example is that a car can have two results in the same race; Behra in 1955 race 1 finished in positions 17 and 13. Same as Trintignant in the same race. I have a check that each race should have a unique driver, but it failed because of this issue.</p><h3>Finally DuckDB</h3><p>The silver layer was placed in DuckDB. To do that, I had to attach PostgreSQL to the DuckDB connection since I needed to read from staging tables to create the dim and fact tables. This is the new profiles.yaml:</p><pre>data_platform_f1:<br>  target: dev  # Use DuckDB target to write silver tables<br>  outputs:<br>    dev:<br>      type: postgres<br>      host: &quot;{{ env_var(&#39;DAGSTER_POSTGRES_HOST&#39;) }}&quot;<br>      user: &quot;{{ env_var(&#39;DAGSTER_POSTGRES_USER&#39;) }}&quot;<br>      password: &quot;{{ env_var(&#39;DAGSTER_POSTGRES_PASSWORD&#39;) }}&quot;<br>      dbname: &quot;{{ env_var(&#39;DAGSTER_POSTGRES_DB&#39;) }}&quot;<br>      port: 5432<br>      schema: f1_bronze<br>      threads: 4<br>    <br>    duckdb_cross:<br>      type: duckdb<br>      path: &quot;/data/medallion/f1_analytics.duckdb&quot;  <br>      schema: silver<br>      threads: 4<br>      extensions:<br>        - httpfs<br>        - parquet<br>      attach:<br>        - path: &quot;postgresql://{{ env_var(&#39;DAGSTER_POSTGRES_USER&#39;) }}:{{ env_var(&#39;DAGSTER_POSTGRES_PASSWORD&#39;) }}@{{ env_var(&#39;DAGSTER_POSTGRES_HOST&#39;) }}:5432/{{ env_var(&#39;DAGSTER_POSTGRES_DB&#39;) }}&quot;<br>          alias: postgres_bronze<br>          type: postgres</pre><p>The cross-database setup (PostgreSQL for raw data, DuckDB for modeling) might seem unconventional, but it solves a critical problem. ETL tools like dlt need to run concurrent operations during ingestion, which causes failures with DuckDB’s single-writer limitation. By keeping raw data in PostgreSQL and using dbt for the modeling layer (which runs one job at a time), we avoid concurrency issues entirely. The performance impact is minimal since PostgreSQL is only holding raw data; all the analytical heavy lifting happens in DuckDB where it excels.</p><p>In the model files, to create the staging files which are in PostgreSQL, I needed to create the sources.yml file to add the already existing tables which will be referenced by the staging files.</p><pre>version: 2<br><br>sources:<br>  - name: f1_bronze<br>    description: &quot;Raw F1 data from DLT ingestion&quot;<br>    schema: f1_bronze<br>    tables:<br>      - name: races<br>      - name: drivers  <br>      - name: circuits<br>      - name: constructors<br>      - name: results<br>      - name: status<br>      - name: constructor_standings<br>      - name: driver_standings</pre><p>For the dim and fact tables, to be able to reference the files in PostgreSQL, I used the attached reference:</p><pre>from postgres_bronze.f1_bronze_staging.stg_circuits</pre><p>Now to run the jobs, I created two targets and their jobs with the dbt command. This was in the form of Dagster assets. I created a dbt asset folder for this.</p><pre>from pathlib import Path<br>from dagster_dbt import (<br>    DbtCliResource,<br>    DbtProject,<br>    dbt_assets,<br>)<br>import dagster as dg<br>import os<br>from pathlib import Path<br><br><br>dbt_project_dir = &quot;/opt/dbt/app&quot;<br># Define your dbt project<br>dbt_project = DbtProject(project_dir=Path(&quot;/opt/dbt/app&quot;))<br><br>dbt_manifest_path = f&quot;{dbt_project_dir}/target/manifest.json&quot;<br><br><br>@dbt_assets(<br>    project=dbt_project,<br>    manifest=dbt_manifest_path,<br>    name=&quot;f1_bronze_staging_assets&quot;,<br>    select=&quot;staging&quot;,<br>    required_resource_keys={&quot;dbt&quot;},<br>)<br>def dbt_staging_assets(context: dg.AssetExecutionContext):<br>    dbt = context.resources.dbt<br>    # Ensure manifest exists by running compile first<br>    if not os.path.exists(dbt_manifest_path):<br>        context.log.info(&quot;Manifest not found, compiling dbt project first...&quot;)<br>        yield from dbt.cli([&quot;compile&quot;], context=context).stream()<br>    yield from dbt.cli([&quot;build&quot;], context=context).stream()<br><br><br>@dbt_assets(<br>    project=dbt_project,<br>    manifest=dbt_manifest_path,<br>    name=&quot;f1_silver_assets&quot;,<br>    select=&quot;silver&quot;,<br>    required_resource_keys={&quot;dbt_silver&quot;},<br>)<br>def dbt_silver_assets(context: dg.AssetExecutionContext):<br>    # verify_s3_database(context)<br>    dbt = context.resources.dbt_silver<br><br>    if not os.path.exists(dbt_manifest_path):<br>        context.log.info(&quot;Manifest not found, compiling dbt project first...&quot;)<br>        yield from dbt.cli([&quot;compile&quot;], context=context).stream()<br><br>    yield from dbt.cli([&quot;build&quot;], context=context).stream()</pre><p>The tricky part here was the manifest. Dagster could not start without the manifest.json file. The required_resource_keys is what differentiates the targets. This is set in repo.py:</p><pre>bronze_dbt_resource = DbtCliResource(<br>    project_dir=&quot;/opt/dbt/app&quot;,<br>    profiles_dir=&quot;/opt/dbt/app&quot;,<br>    profile_name=&quot;data_platform_f1&quot;,  # Explicit profile name<br>    target=&quot;dev&quot;,<br>)<br><br>silver_dbt_resource = DbtCliResource(<br>    project_dir=&quot;/opt/dbt/app&quot;,<br>    profiles_dir=&quot;/opt/dbt/app&quot;,<br>    profile_name=&quot;data_platform_f1&quot;,  # Explicit profile name<br>    target=&quot;duckdb_cross&quot;,<br>)<br><br>defs = Definitions(<br>    assets=all_assets,<br>    jobs=[<br>        f1_static_job,<br>        f1_race_details_job,<br>        f1_yearly_job,<br>        f1_dbt_staging_job,<br>        f1_dbt_silver_job,<br>    ],<br>    resources={<br>        &quot;dlt&quot;: DagsterDltResource(),<br>        &quot;io_manager&quot;: dg.fs_io_manager,<br>        &quot;dbt&quot;: bronze_dbt_resource,<br>        &quot;dbt_silver&quot;: silver_dbt_resource,<br>    },<br>    executor=dg.in_process_executor,<br>    schedules=[<br>        yearly_schedule,<br>        static_yearly_schedule,<br>        weekly_yearly_schedule,<br>    ],<br>)</pre><p>With this, you should be able to run the jobs.</p><h3>Recap</h3><p>I was able to:</p><ul><li>Integrate dlt and Dagster</li><li>Integrate dlt and PostgreSQL</li><li>Integrate Dagster with dbt</li><li>Integrate Dagster with DuckDB and have it communicate with PostgreSQL</li></ul><p>The code can be found <a href="https://github.com/yvonnegitau/Data-Platform-Agent-Builder/tree/feature/dbt-integration">here</a>.</p><p>This has created a good foundation for understanding how AI will come in when you would like to explore the data. Up to here, I believe I will mainly need it for SQL generation, which had some errors. While working with dlt, Dagster and dbt, I would recommend using their documentation which has AI, and it will be better than using the general models on your IDE.</p><p>I will finish this series here, then start a new one where I add AI on top of the modeled data. I’m planning to use a custom LangChain + dbt + Streamlit stack. This is still a draft architecture and may change based on my research. I initially wanted to use Wren AI, but since it cannot connect to .duckdb files, I had to explore alternatives.</p><p>Stay tuned for the next series where we’ll explore how to make this F1 data warehouse truly conversational!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa155ab6ebcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Journal: Dagster + dlt + DuckDB Part 2]]></title>
            <link>https://medium.com/@ywg/my-journal-dagster-dlt-duckdb-part-2-6549ae30fb27?source=rss-5161d83115ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/6549ae30fb27</guid>
            <category><![CDATA[dlt]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[dagster]]></category>
            <dc:creator><![CDATA[Wambui Gitau]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 05:02:00 GMT</pubDate>
            <atom:updated>2025-08-11T05:02:00.389Z</atom:updated>
            <content:encoded><![CDATA[<p>This is my upgrade of my first implementation of this stack. In <a href="https://medium.com/@ywg/my-journal-dagster-dlt-duckdb-part-1-15051f20e597">Part 1</a>, I highlighted how one can implement this stack and make it work in the not-so-good practice. These were the key issues that I had highlighted:</p><ul><li>DuckDB allows one write at a time</li><li>How not to implement REST API data source in dlt</li><li>Dagster Backfill is not straightforward</li><li>There are things called Resources in Dagster</li></ul><p>Below is how I addressed each issue and hopefully applied the best practices in each of the components.</p><h4>Handling Multi-processing in DuckDB</h4><p>I went back to the DuckDB documentation to understand how best to handle multi-processing. For context, I need to simulate how F1 data was ingested to the data storage from 1950. Some of the data is ingested monthly, meaning there is a need for a lot of processes running concurrently. What I discovered is that DuckDB does not allow multiple processes to write at the same time. Therefore, there were a lot of failed runs.</p><p>To fix that, I have 3 options according to the documentation:</p><ul><li>Using a mutex lock. This is handled from the application level. This is what I attempted to do, and the fail rate reduced but did not have a 100% success rate</li><li>Using DBs that allow multi-process transactions such as MySQL, PostgreSQL, or SQLite. Then use DuckDB extensions for analytical queries</li><li>Writing data to Parquet files and having DuckDB read from the files</li></ul><p>Based on cost analysis, Parquet files in an object storage + DuckDB will be the best choice for big data. However, it would not be a good choice for my project since the data is small, less than 10 GB, and the data in each file will be really small; hence, I will have a lot of small Parquet files, which makes it less efficient. I will also need a table format to implement ACID.</p><p>My approach is to use PostgreSQL for bronze and silver layers, then DuckDB for the gold layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*12NFpnyahE4CadiYYKZDow.png" /><figcaption>New Data Flow</figcaption></figure><h4>dlt Sources</h4><p>When working with data sources, I need to understand how I would like to ingest the data. This will help in selecting asset configurations. In the case of F1 data, I have identified 3 groups of endpoints:</p><ul><li>Endpoints where the data does not need any filter parameters parsed. This means that if you query the endpoint, you will find the latest data. In F1 data, these are Seasons and Circuits. I simply need to merge the results</li><li>Endpoints where data changes each new season. This means that I will need to parse the season. Examples are Drivers and Constructors</li><li>Endpoints where data changes every month. These are the race details such as results, qualifying, laps, standings, sprint, etc. As much as I will only need to parse the season, the fact that there is a lot of data makes the processing different, and I may want more processing threads to be used. I used this to learn how multi-processing in Dagster works</li></ul><p>It took a while to understand the dlt source. At first, based on the endpoint groups, I thought that I needed different sources since I wanted to use RestApiConfig for group 1 and use RestClient for the rest. However, using RestClient proved to be all I needed; hence, I settled for only one source. Logically, it makes sense. If I’m to add a new source, I will create a new source.</p><p>dlt sources contain resources. In this use case, all the endpoints will be resources. At this point, you get to define the primary key and write disposition. An example of the implementation is:</p><pre>@dlt.source(name=&quot;f1_source&quot;)<br>def f1_api_source(<br>    base_url: str = &quot;https://api.jolpi.ca/ergast/f1&quot;,<br>    years: Optional[Union[List[int], range]] = None,<br>) -&gt; List[DagsterDltResource]:<br>    &quot;&quot;&quot;<br>    Source for the F1 API.<br>    &quot;&quot;&quot;<br>    if years is None:<br>        years = [datetime.now().year]<br><br>    @dlt.resource(<br>        name=&quot;seasons&quot;,<br>        primary_key=&quot;season&quot;,<br>        write_disposition=&quot;merge&quot;,<br>    )<br>    def seasons():<br>        logger.info(&quot;Processing F1 seasons&quot;)<br><br>        # Create a REST client with the correct paginator<br>        client = RESTClient(<br>            base_url=base_url,<br>            paginator=OffsetPaginator(<br>                limit=100,<br>                offset=0,<br>                total_path=&quot;MRData.total&quot;,<br>            ),<br>            data_selector=&quot;MRData.SeasonTable.Seasons&quot;,<br>        )<br><br>        # Make the request with pagination<br>        for page in client.paginate(<br>            &quot;/seasons.json&quot;,<br>        ):<br>            logger.info(f&quot;Extracted {len(page)} seasons&quot;)<br>            logger.info(f&quot;Seasons data: {page}&quot;)<br>            for season in page:<br><br>                yield season<br>    @dlt.resource(<br>        name=&quot;races&quot;,<br>        primary_key=[&quot;season&quot;, &quot;round&quot;],<br>        write_disposition=&quot;merge&quot;,<br>    )<br>    def races(year: Optional[int] = None):<br>        &quot;&quot;&quot;<br>        Resource for races.<br>        &quot;&quot;&quot;<br>        years_to_process = [year] if year is not None else years<br><br>        logger.info(f&quot;Processing F1 races for years: {years_to_process}&quot;)<br>        for year in years_to_process:<br>            logger.info(f&quot;Processing races for {year}&quot;)<br>            # Create a REST client with the correct paginator<br>            client = RESTClient(<br>                base_url=base_url,<br>                paginator=OffsetPaginator(<br>                    limit=100,<br>                    offset=0,<br>                    total_path=&quot;MRData.total&quot;,<br>                ),<br>                data_selector=&quot;MRData.RaceTable.Races&quot;,<br>            )<br>            # Make the request with pagination<br>            for page in client.paginate(<br>                f&quot;{year}/races.json&quot;,<br>            ):<br>                logger.info(f&quot;Extracted {len(page)} pages for year {year}&quot;)<br><br>                for race in page:<br>                    race[&quot;extracted_at&quot;] = datetime.now().isoformat()<br>                    yield race</pre><p>All the other resources follow a similar syntax. At the end, I return the resources. The best thing about this approach is that dlt handles the pagination and data extraction while managing the JSON schema. This reduces the lines of code and also optimizes the performance.</p><pre>return seasons, circuits, drivers, constructors, races</pre><p>They will then be called in the assets file.</p><h4>Dagster Assets</h4><p>In this use case, I wanted to run each resource individually. In Dagster, one has the option to run all resources in a single job. However, they will all share the same backfill and partition definition. An example is as follows:</p><pre>from dagster_dlt import dlt_assets<br><br><br>@dlt_assets(<br>    group_name=&quot;f1_test&quot;,<br>    partitions_def=reference_partitions,<br>    backfill_policy=single_run_backfill,<br>    dlt_source=f1_api_source(),<br>    dlt_pipeline=pipeline,<br>)<br>def f1_test(<br>    context: AssetExecutionContext,<br>) -&gt; None:<br>    &quot;&quot;&quot;Extract F1 pit stops reference data.&quot;&quot;&quot;<br><br>    context.log.info(&quot;Extracting F1 pit stops reference data&quot;)<br><br>    yield from dlt.run(context=context)</pre><p>On the dagster UI the assets will look as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-MC7RlGO6WbzKxAYoloZGQ.png" /></figure><p>I have created multiple asset groups because I would like to run them differently. These are the asset groups:</p><ul><li>Static — Resources that change only once, e.g., season and circuit</li><li>Yearly — Resources that change each year and are considered different each year even if they are the same, e.g., drivers and constructors</li><li>Race details — Resources that give granular information about the race, e.g., driver standings, laps, qualifying, constructor standings</li></ul><p>The Race details assets run monthly and use multi_run_backfill.</p><p>This is a sample of one of the assets:</p><pre>@asset(<br>    compute_kind=&quot;dlt&quot;,<br>    group_name=&quot;f1_bronze_race&quot;,<br>    description=&quot;F1 race results data from Ergast API&quot;,<br>    partitions_def=monthly_partitions,<br>    backfill_policy=multi_run_backfill,<br>    deps=[&quot;f1_races&quot;],<br>)<br>def f1_results(context: AssetExecutionContext, config: F1BronzeConfig) -&gt; None:<br>    simulation_date = get_simulation_date_from_partition(context, config)<br><br>    context.log.info(<br>        f&quot;Extracting results for simulation date: {simulation_date.strftime(&#39;%Y-%m-%d&#39;)}&quot;<br>    )<br><br>    source = f1_api_source(years=[simulation_date.year])<br><br>    bronze_pipeline.run(source.resources[&quot;results&quot;])<br>    return None</pre><h4>Dagster Asset Dependency</h4><p>Dagster allows data to be passed from one asset to another. This was necessary when working with the laps endpoint, where you need to pass the rounds. I had to alter the races asset to return the races data, which contains all the rounds in that season as of the date the job is being run. This data is what gets passed to the laps asset. With the current implementation of assets where I run the pipeline, I could not get the data from <strong>pipeline.run()</strong> . I had to pass the sources object to get the data.</p><pre>def get_race_metadata_from_source(source, year: int) -&gt; List[Dict[str, Any]]:<br>    &quot;&quot;&quot;<br>    Extract race metadata directly from the source data instead of the database.<br>    This ensures we have the metadata even if the database write fails.<br>    &quot;&quot;&quot;<br>    try:<br>        race_metadata = []<br><br>        # Get the race data from the source<br>        for race in source.races:<br>            race_info = {<br>                &quot;season&quot;: race.get(&quot;season&quot;, str(year)),<br>                &quot;round&quot;: race.get(&quot;round&quot;),<br>                &quot;race_name&quot;: race.get(&quot;raceName&quot;),<br>                &quot;date&quot;: race.get(&quot;date&quot;),<br>                &quot;circuit_id&quot;: (<br>                    race.get(&quot;Circuit&quot;, {}).get(&quot;circuitId&quot;)<br>                    if isinstance(race.get(&quot;Circuit&quot;), dict)<br>                    else None<br>                ),<br>                &quot;completed&quot;: (<br>                    True if race.get(&quot;date&quot;) else False<br>                ),  # You might want to improve this logic<br>            }<br>            race_metadata.append(race_info)<br><br>        return race_metadata</pre><p>The result of this function is what is returned by the asset. The data is stored in an I/O manager. There are different types of <a href="https://docs.dagster.io/guides/build/io-managers/#built-in">I/O managers</a>. In my case, I started with in-memory, but the disadvantage of it is that you cannot re-execute the run if it fails. You need to create a new run. Therefore, I changed to FilesystemIOManager. For more robust data storage, you can use S3, DuckDB, or other data warehouses.</p><blockquote>Note: This is not the optimal implementation since it runs the API requests twice. There is a cleaner way, and I will implement it when I add a caching mechanism like Redis.</blockquote><pre>@asset(<br>    compute_kind=&quot;dlt&quot;,<br>    description=&quot;F1 race data from Ergast API&quot;,<br>    group_name=&quot;f1_bronze_race_details&quot;,<br>    partitions_def=yearly_partitions,<br>    backfill_policy=multi_run_backfill,<br>    io_manager_key=&quot;io_manager&quot;,<br>)<br>def f1_races(<br>    context: AssetExecutionContext,<br>    config: F1BronzeConfig,<br>) -&gt; List[Dict[str, Any]]:<br>    simulation_date = get_simulation_date_from_partition(context, config)<br><br>    context.log.info(<br>        f&quot;Extracting Races for simulation date: {simulation_date.strftime(&#39;%Y-%m-%d&#39;)}&quot;<br>    )<br><br>    source = f1_api_source(years=[simulation_date.year])<br>    try:<br>        bronze_pipeline.run(source.resources[&quot;races&quot;])<br><br>        race_metadata = get_race_metadata_from_source(source, simulation_date.year)<br><br>        context.log.info(f&quot;Returning race metadata: {race_metadata}&quot;)<br><br>        # Return the properly typed race metadata<br>        return race_metadata<br>    except Exception as e:<br>        context.log.error(<br>            f&quot;Error running DLT pipeline for races on {simulation_date.strftime(&#39;%Y-%m-%d&#39;)}: {e}&quot;<br>        )<br>        raise e</pre><p>Below is how to add the data as an input for the next asset.</p><pre>@asset(<br>    compute_kind=&quot;dlt&quot;,<br>    description=&quot;F1 laps data from Ergast API&quot;,<br>    group_name=&quot;f1_bronze_race_details&quot;,<br>    partitions_def=yearly_partitions,<br>    backfill_policy=multi_run_backfill,<br>    deps=[&quot;f1_races&quot;],<br>    ins={&quot;race_metadata&quot;: AssetIn(&quot;f1_races&quot;)},<br>)<br>def f1_laps(<br>    context: AssetExecutionContext,<br>    config: F1BronzeConfig,<br>    race_metadata: List[Dict[str, Any]],<br>) -&gt; None:<br>    &quot;&quot;&quot;Extract all F1 laps data for a given simulation date.&quot;&quot;&quot;<br><br>    simulation_date = get_simulation_date_from_partition(context, config)<br>    context.log.info(<br>        f&quot;Extracting comprehensive F1 data for: {simulation_date.strftime(&#39;%Y-%m-%d&#39;)}&quot;<br>    )<br>    context.log.info(f&quot;Received race metadata: {race_metadata}&quot;)<br><br>    # Collect ALL rounds and determine the year<br>    rounds_to_process = []<br>    year = simulation_date.year  # Default to simulation date year<br><br>    for item in race_metadata:<br>        if &quot;round&quot; not in item or &quot;season&quot; not in item:<br>            context.log.warning(f&quot;Skipping item without &#39;round&#39; or &#39;season&#39;: {item}&quot;)<br>            continue<br><br>        round_num = int(item[&quot;round&quot;])<br>        season_year = int(item[&quot;season&quot;])<br><br>        rounds_to_process.append(round_num)<br>        year = season_year  # Update year (should be consistent across all items)<br><br>        context.log.info(f&quot;Added round {round_num} for season {season_year}&quot;)<br><br>    if not rounds_to_process:<br>        context.log.warning(<br>            &quot;No valid rounds found in race metadata, skipping laps extraction.&quot;<br>        )<br>        return<br><br>    # Remove duplicates and sort<br>    rounds_to_process = sorted(list(set(rounds_to_process)))<br><br>    context.log.info(<br>        f&quot;Extracting laps for {len(rounds_to_process)} rounds: {rounds_to_process} in season {year}&quot;<br>    )<br><br>    # Process all rounds at once<br>    source = f1_api_source(years=[year], rounds=rounds_to_process)<br>    bronze_pipeline.run(source.resources[&quot;laps&quot;])<br><br>    context.add_output_metadata(<br>        {<br>            &quot;rounds_processed&quot;: len(rounds_to_process),<br>            &quot;rounds_list&quot;: str(rounds_to_process),<br>            &quot;season&quot;: year,<br>        }<br>    )<br><br>    return None</pre><p>To be able to run the two assets in such a way that the <strong>laps </strong>asset is triggered after the <strong>races </strong>asset, you need to create a single job that has the two assets or create a sensor. For simple implementation, which this was, I went with the depends implementation.</p><pre>f1_race_details_job = define_asset_job(<br>    &quot;f1_bronze_race_details_job&quot;,<br>    selection=AssetSelection.groups(&quot;f1_bronze_race_details&quot;),<br>    description=&quot;Monthly refresh of Race details data&quot;,<br>)<br><br># The definition<br>defs = Definitions(<br>    assets=all_assets,<br>    jobs=[f1_static_job, f1_race_details_job, f1_yearly_job],<br>    resources={&quot;dlt&quot;: DagsterDltResource(), &quot;io_manager&quot;: dg.fs_io_manager},<br>    executor=dg.in_process_executor,<br>    schedules=[<br>        f1_race_season_schedule,<br>        f1_static_quarterly_schedule,<br>        f1_yearly_schedule,<br>    ],<br>)</pre><h4>Dagster Jobs and Schedule</h4><p>Since the API only has year as the filter, I used the yearly partition but scheduled the jobs to run every Monday for the assets that contain race details. This is because the F1 schedule does not have specific times in the months that it takes place. Sometimes it can run 3 times a month and sometimes not run at all.</p><pre>f1_race_season_schedule = ScheduleDefinition(<br>    job=f1_race_details_job,<br>    cron_schedule=&quot;0 7 * 3-12 1&quot;,<br>    default_status=DefaultScheduleStatus.RUNNING,<br>)<br><br>f1_static_yearly_schedule = ScheduleDefinition(<br>    job=f1_static_job,<br>    cron_schedule=&quot;0 1 1 3 *&quot;,  # First day of March at 1 AM<br>    default_status=DefaultScheduleStatus.RUNNING,<br>)<br><br>f1_yearly_schedule = ScheduleDefinition(<br>    job=f1_yearly_job,<br>    cron_schedule=&quot;0 1 1 3 *&quot;,  # First day of March at 1 AM<br>    default_status=DefaultScheduleStatus.RUNNING,<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uEgrCW-treI8EKuXvMNzsA.png" /><figcaption>Example of the race details job</figcaption></figure><p>In summary, I was able to:</p><ul><li>Change from DuckDB to Postgres as data storage. This mostly works for small data; for big data, I may need to move to more robust data storage such as a data lake or data lakehouse.</li><li>Implement Dagster Sources, which reduced the amount of manual implementation of the API request. Most of the work was handled by the dlt connector.</li><li>Add I/O manager so that I can pass data from one asset to another</li><li>Add a schedule for the jobs</li></ul><p>The code for this changes can be found <a href="https://github.com/yvonnegitau/Data-Platform-Agent-Builder/tree/upgrade/ingestion">here</a>.</p><p>Next, I will start data modeling. I will be using dbt and the Kimball approach. One hypothesis I would like to test is: Should we stop at dimensional and fact tables then use LLMs for creating the semantic layer on the fly? Basically, using LLMs to create reports based on the fact tables and not data marts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6549ae30fb27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Journal: Dagster + dlt + DuckDB Part 1]]></title>
            <link>https://medium.com/@ywg/my-journal-dagster-dlt-duckdb-part-1-15051f20e597?source=rss-5161d83115ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/15051f20e597</guid>
            <category><![CDATA[dagster]]></category>
            <category><![CDATA[duckdb]]></category>
            <category><![CDATA[dlt]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <dc:creator><![CDATA[Wambui Gitau]]></dc:creator>
            <pubDate>Sun, 08 Jun 2025 18:16:21 GMT</pubDate>
            <atom:updated>2025-06-08T18:16:21.494Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>TL;DR: These are lessons on how not to set up a data pipeline with <a href="https://dagster.io/">Dagster </a>+ <a href="https://dlthub.com/">d</a>lt+ <a href="https://duckdb.org/docs/installation/?version=stable&amp;environment=cli&amp;platform=macos&amp;download_method=direct">DuckDB</a>. If you prefer to experience these shortcomings like me before moving to doing it the right way, this is your blog post.</blockquote><p>With the boom in GenAI models, instead of vibe coding a product, I chose to vibe code a data warehouse solution for learning purposes. To be honest, I began this project before the models became good and code generation was just starting. This is my first time using this set of tools.</p><h3><strong>Context</strong></h3><p>This is a portfolio project that I’m using to learn about Dagster, dlt and DuckDB. The objective is to build a data pipeline and visualization platform for F1. Below is the architecture that I followed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_1iHgwSHIhOYbZMSWFyT1A.png" /><figcaption>Data platform Architecture</figcaption></figure><h3>Lessons</h3><p><strong>Lesson 1: Code Assistants are not as good at DE open source tools as they are with full-stack frameworks</strong></p><p>It is better to start by looking at the documentation of tools before you start vibe-coding. I spent a couple of hours trying to debug generated code. I had to write the code on my own from scratch using examples from Dagster and dlt.</p><p><strong>Lesson 2: Working with Windows WSL2 and DBeaver</strong></p><p>For those working from a Windows machine and using WSL2, you probably have your code in the $wsl folder. If you would like to use DBeaver as a client to connect to DuckDB, you will need to mount the OS to a new drive on Windows. Otherwise, you will not be able to connect to the .duckdb file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*ieiTFHuMPk5rrQ7HugYbcw.png" /></figure><p><strong>Lesson 3: Duckdb allows one write at a time</strong></p><p>This is something that I did not know when picking DuckDB as data storage. Most blogs that I have seen using DuckDB did not mention this as the number one con. This means when I was ingesting the data, I had a high fail rate because the file was locking. I tried to implement wait and retry; this reduced the failures, but I still had a considerable number of failures.</p><pre>for attempt in range(1, max_retries + 1):<br>            try:<br>                if context:<br>                    context.log.info(<br>                        f&quot;Pipeline execution attempt {attempt}/{max_retries}&quot;<br>                    )<br><br>                start_time = datetime.now()<br>                info = pipeline.run([resource()])<br>                end_time = datetime.now()<br><br>                if context:<br>                    context.log.info(f&quot;✅ Pipeline run successful on attempt {attempt}&quot;)<br><br>                success = True<br>                break<br><br>            except Exception as e:<br>                if context:<br>                    context.log.warning(f&quot;Pipeline attempt {attempt} failed: {str(e)}&quot;)<br><br>                if attempt &lt; max_retries:<br>                    wait_time = retry_delay * (<br>                        2 ** (attempt - 1)<br>                    )  # Exponential backoff<br>                    if context:<br>                        context.log.info(f&quot;Waiting {wait_time}s before retry...&quot;)<br>                    time.sleep(wait_time)<br>                else:<br>                    if context:<br>                        context.log.error(<br>                            f&quot;Pipeline failed after {max_retries} attempts&quot;<br>                        )<br>                    raise</pre><blockquote>The best approach would be to either have data ingested into Parquet files or use Postgres or any other RDBMS of choice and then move the data to a DuckDB file.</blockquote><p><strong>Lesson 4: How not to implement REST API data source in dlt</strong></p><p>I created a class that had a Python implementation of the API endpoint requests and JSON formatting of the response. This took a lot of lines of code. I had to implement rate limits and pagination. dlt has abstracted all this.</p><p>Below is an example from their documentation:</p><pre>pokemon_source = rest_api_source(<br>    {<br>        &quot;client&quot;: {<br>            &quot;base_url&quot;: &quot;https://pokeapi.co/api/v2/&quot;,<br>        },<br>        &quot;resource_defaults&quot;: {<br>            &quot;endpoint&quot;: {<br>                &quot;params&quot;: {<br>                    &quot;limit&quot;: 1000,<br>                },<br>            },<br>            # For the `berry` and `location` resources, we keep<br>            # the `replace` write disposition<br>            &quot;write_disposition&quot;: &quot;replace&quot;,<br>        },<br>        &quot;resources&quot;: [<br>            # We create a specific configuration for the `pokemon` resource<br>            # using a dictionary instead of a string to configure<br>            # the primary key and write disposition<br>            {<br>                &quot;name&quot;: &quot;pokemon&quot;,<br>                &quot;primary_key&quot;: &quot;name&quot;,<br>                &quot;write_disposition&quot;: &quot;merge&quot;,<br>            },<br>            # The `berry` and `location` resources will use the default<br>            &quot;berry&quot;,<br>            &quot;location&quot;,<br>        ],<br>    }<br>)</pre><p>This was my implementation with get_seasons as an example:</p><pre>class ErgastClient:<br>    &quot;&quot;&quot;<br>    A client for the Ergast API.<br>    &quot;&quot;&quot;<br><br>    def __init__(<br>        self,<br>        base_url: str = &quot;https://api.jolpi.ca/ergast/f1&quot;,<br>        request_per_second: float = 4.0,<br>    ):<br>        self.base_url = base_url<br>        self.session = requests.Session()<br>        self.requests_per_second = request_per_second<br>        self.min_interval = 1.0 / request_per_second<br>        self.last_request_time = 0<br><br>        self.cache = {}<br><br>    def _wait_for_rate_limit(self):<br>        current_time = datetime.now().timestamp()<br>        elapsed_time = current_time - self.last_request_time<br><br>        if elapsed_time &lt; self.min_interval:<br>            sleep_time = self.min_interval - elapsed_time<br>            logger.debug(f&quot;Rate limiting: sleeping for {sleep_time:.2f} seconds&quot;)<br>            time.sleep(sleep_time)<br><br>    def _get_cache_key(<br>        self, endpoint: str, params: Optional[Dict[str, Any]] = None<br>    ) -&gt; str:<br>        &quot;&quot;&quot;<br>        Generate a cache key based on the endpoint and parameters.<br>        &quot;&quot;&quot;<br>        if params:<br>            param_str = &quot;&amp;&quot;.join([f&quot;{k}={v}&quot; for k, v in sorted(params.items())])<br>            return f&quot;{endpoint}?{param_str}&quot;<br>        return endpoint<br><br>    @retry(<br>        retry=retry_if_exception_type(<br>            (<br>                requests.exceptions.ConnectionError,<br>                requests.exceptions.Timeout,<br>                requests.exceptions.HTTPError,<br>            )<br>        ),<br>        stop=stop_after_attempt(5),<br>        wait=wait_exponential(multiplier=1, min=1, max=10),<br>        before_sleep=before_sleep_log(logger, logging.INFO),<br>        after=after_log(logger, logging.INFO),<br>        reraise=True,<br>    )<br>    def make_request(<br>        self,<br>        endpoint: str,<br>        params: Optional[Dict[str, Any]] = None,<br>        use_cache: bool = True,<br>    ) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;<br>        Make a GET request to the Ergast API.<br>        &quot;&quot;&quot;<br>        cache_key = self._get_cache_key(endpoint, params)<br>        if use_cache and cache_key in self.cache:<br>            logger.debug(f&quot;Cache hit for {cache_key}&quot;)<br>            return self.cache[cache_key]<br><br>        url = f&quot;{self.base_url}/{endpoint}.json&quot;<br><br>        if params is None:<br>            params = {}<br><br>        self._wait_for_rate_limit()<br><br>        try:<br>            logger.info(f&quot;Making request to {url} with params {params}&quot;)<br>            response = self.session.get(url, params=params)<br><br>            if response.status_code == 429:<br>                # Fix: Handle missing Retry-After header<br>                retry_after = response.headers.get(&quot;Retry-After&quot;)<br>                if retry_after:<br>                    try:<br>                        retry_after = int(retry_after)<br>                        logger.warning(<br>                            f&quot;Rate limit exceeded. Retrying after {retry_after} seconds.&quot;<br>                        )<br>                        time.sleep(retry_after)<br>                    except ValueError:<br>                        # Handle non-integer Retry-After values<br>                        default_wait = 5<br>                        logger.warning(<br>                            f&quot;Invalid Retry-After header: {retry_after}. Using default wait: {default_wait} seconds.&quot;<br>                        )<br>                        time.sleep(default_wait)<br>                else:<br>                    # Default wait time if no Retry-After header<br>                    default_wait = 5<br>                    logger.warning(<br>                        f&quot;Rate limit exceeded. No Retry-After header found, waiting {default_wait} seconds.&quot;<br>                    )<br>                    time.sleep(default_wait)<br>                raise requests.exceptions.HTTPError(&quot;Rate limit exceeded, retrying...&quot;)<br><br>            response.raise_for_status()<br>            data = response.json()<br><br>            if use_cache:<br>                logger.debug(f&quot;Caching response for {cache_key}&quot;)<br>                self.cache[cache_key] = data<br><br>            # Update last request time for rate limiting<br>            self.last_request_time = datetime.now().timestamp()<br><br>            return data<br><br>        except requests.exceptions.RequestException as e:<br>            logger.error(f&quot;Request failed: {e}&quot;)<br>            raise<br>        except json.JSONDecodeError as e:<br>            logger.error(f&quot;Failed to decode JSON response: {e}&quot;)<br>            raise<br>        except Exception as e:<br>            logger.error(f&quot;An unexpected error occurred: {e}&quot;)<br>            raise<br><br>    @retry(<br>        retry=retry_if_exception_type(requests.exceptions.RequestException),<br>        stop=stop_after_attempt(3),<br>        wait=wait_exponential(multiplier=1, min=1, max=10),<br>        before_sleep=before_sleep_log(logger, logging.WARNING),<br>    )<br>    def get_seasons(self):<br>        &quot;&quot;&quot;Get all F1 seasons with pagination handling.&quot;&quot;&quot;<br>        all_seasons = []<br>        page = 1<br>        limit = 100  # Maximum allowed by Ergast API<br><br>        while True:<br>            endpoint = &quot;seasons&quot;<br>            params = {&quot;limit&quot;: limit, &quot;offset&quot;: (page - 1) * limit}<br>            logger.info(f&quot;Fetching seasons page {page}, offset: {(page - 1) * limit}&quot;)<br><br>            response = self.make_request(endpoint, params)<br><br>            if not response or &quot;MRData&quot; not in response:<br>                logger.error(f&quot;Invalid response from API: {response}&quot;)<br>                break<br><br>            season_data = (<br>                response[&quot;MRData&quot;][&quot;SeasonTable&quot;][&quot;Seasons&quot;]<br>                if &quot;SeasonTable&quot; in response[&quot;MRData&quot;]<br>                else []<br>            )<br>            logger.info(f&quot;Got {len(season_data)} seasons in page {page}&quot;)<br><br>            if not season_data:<br>                break<br><br>            all_seasons.extend(season_data)<br><br>            # Check if we&#39;ve reached the end of data<br>            total = int(response[&quot;MRData&quot;][&quot;total&quot;])<br>            fetched = min(int(response[&quot;MRData&quot;][&quot;limit&quot;]), total) * page<br><br>            logger.info(f&quot;Progress: fetched {len(all_seasons)}/{total} seasons&quot;)<br><br>            if fetched &gt;= total:<br>                logger.info(f&quot;✅ All {total} seasons fetched successfully&quot;)<br>                break<br><br>            page += 1<br><br>        logger.info(f&quot;Total seasons fetched: {len(all_seasons)}&quot;)<br>        return all_seasons</pre><blockquote>I have to redo this implementation to match what DLT has. It caters to pagination, low memory usage, and retries.</blockquote><p><strong>Lesson 5: Dagster Backfill is not straightforward</strong></p><p>The one thing that I was interested in when working with Dagster is seeing how it handles backfill. F1 started in 1950, and I wanted to simulate data being stored yearly for some objects such as drivers, seasons, circuits, and constructors, while also simulating how monthly ingestions will look like. For this to be accomplished, one needs:</p><ul><li>Partition the data. This will be yearly and monthly partitions.</li><li>Backfill Policy: It can either be a single run or multiple runs.</li></ul><p>What I expected was to be able to set the period I would like to simulate (1950–2025), then in the context, be able to get the current date and use it in the endpoint URL to get data for that particular year. This can only be done if you use a multirun policy with max partition being 1.</p><pre>multi_run_backfill = BackfillPolicy.multi_run(max_partitions_per_run=1)</pre><p>When you have a date range, it will pick each year as a partition (1950–1951), and you can get the current year as `start_date`. I did this since I wanted to see metadata for each partition, and this was the only way I have found so far.</p><pre>def get_simulation_date_from_partition(<br>    context: AssetExecutionContext, config: F1BronzeConfig<br>) -&gt; datetime:<br>    &quot;&quot;&quot;Get simulation date from the current partition.&quot;&quot;&quot;<br><br>    # Debug logging<br>    context.log.info(&quot;=== PARTITION DEBUG ===&quot;)<br><br>    # For single partition runs<br>    if hasattr(context, &quot;partition_key&quot;) and context.partition_key:<br>        partition_key = context.partition_key<br>        context.log.info(f&quot;Using partition key: {partition_key}&quot;)<br><br>        # Handle static partition &quot;current&quot;<br>        if partition_key == &quot;current&quot;:<br>            context.log.info(&quot;Using current date for static partition&quot;)<br>            return datetime.now()<br><br>        # Parse date string<br>        try:<br>            simulation_date = datetime.strptime(partition_key, &quot;%Y-%m-%d&quot;)<br>            context.log.info(f&quot;Parsed simulation date: {simulation_date}&quot;)<br>            return simulation_date<br>        except ValueError:<br>            context.log.error(f&quot;Could not parse partition key as date: {partition_key}&quot;)<br><br>    # For multi-partition backfills<br>    if hasattr(context, &quot;partition_key_range&quot;) and context.partition_key_range:<br>        # Use the start of the range<br>        start_date = context.partition_key_range.start<br>        context.log.info(f&quot;Using start date from range: {start_date}&quot;)<br><br>        try:<br>            simulation_date = datetime.strptime(start_date, &quot;%Y-%m-%d&quot;)<br>            context.log.info(f&quot;Parsed simulation date: {simulation_date}&quot;)<br>            return simulation_date<br>        except ValueError:<br>            context.log.error(f&quot;Could not parse range start date: {start_date}&quot;)<br><br>    # Ultimate fallback<br>    context.log.info(&quot;No valid partition info found, using config fallback&quot;)<br>    return get_simulation_date(config)<br><br><br>def get_simulation_date(config: F1BronzeConfig) -&gt; datetime:<br>    if config.simulation_date:<br>        return datetime.strptime(config.simulation_date, &quot;%Y-%m-%d&quot;)<br>    elif config.months_to_run:<br>        return datetime(config.start_year, 1, 1) + relativedelta(<br>            months=config.months_to_run<br>        )<br>    else:<br>        return datetime.now()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AzFq72Ra_KZZHqMuYrXjgw.png" /><figcaption>Metadata details for year 2024 of the race asset</figcaption></figure><p>For endpoints where I knew data only changes once a year, I used a single run and looped through the years to simulate the backfill. For these endpoints, you could get all the data without adding the year to the endpoint. Otherwise, I would have implemented it with multirun.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VJSVNspqZ8bF0WfAkzzGUg.png" /></figure><p><strong>Lesson 6: There are things called Resources in Dagster</strong></p><p>For every run, Dagster creates a container to run it. If you do not have resources such as API connections or DB connections, for each container being created, new connections will be created. If you would like the run to share resources, this is the best approach.</p><blockquote>I have to rewrite the implementation to make sure that the API client connection is a resource. I will also look into having the database/Minio connection as a resource (not sure at the moment what I will use).</blockquote><p><strong>Final Lesson: Agile is the best approach</strong></p><p>Having something running from end to end as fast as possible makes it easier to see what needs to be optimized. With the code assistants, the optimization takes minimal effort. However, make sure to go through the tools’ documentation (Dagster Scout, we will have sessions next week :) ) for best practices.</p><p><strong>Conclusion</strong></p><p>This implementation works with some kinks. It is the first step and was able to give me insights into dlt, Dagster, and DuckDB. It is not the way to go, and I will have to rework this implementation. Part 2 of this blog will have improvements and DBT added to the architecture.</p><p>Code can be found <a href="https://github.com/yvonnegitau/Data-Platform-Agent-Builder/tree/feature/ingestion-f1">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15051f20e597" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Engineering Startup code: Flask Appbuilder]]></title>
            <link>https://medium.com/@ywg/data-engineering-startup-code-flask-appbuilder-94878e7b12b7?source=rss-5161d83115ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/94878e7b12b7</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Wambui Gitau]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 05:02:13 GMT</pubDate>
            <atom:updated>2025-02-06T05:02:13.788Z</atom:updated>
            <content:encoded><![CDATA[<p>There are levels of Data Engineering projects: The ones that only require a couple of scripts to pull data from source, simple transforms and processing then send to destination and The ones that have a whole group of tools pieced together to extract data fro multiple sources, perform complex transformations and data modelling and finally serve the data. This article majorly focuses on the first one, those projects where simplicity isn’t just a virtue, it’s a necessity. Surprisingly, you will find most of the projects are simple and do not need over engineering.</p><p>Most days, the data sources we’re working with are as familiar as our favorite playlists — think Excel or Google Sheets. When that’s the scene, my weapon of choice is AppScript. Now, if the data needs an extra oomph of processing power, I pair it with Lambda functions for that extra punch. The sweetest part? The cost usually comes out to somewhere between zero and a dollar. However, there are cases where multiple people want to access the data which raises a need for user management. Then there might be a need to add a project management if we have different projects that need to do the same transformations. This is where Falsk Appbuilder comes in. I dont need anything complex, something that I can spin up in a day.</p><p>You can choose to set it up on your own or you can fork the already set up <a href="https://github.com/yvonnegitau/Flask-AppBuilder-Boilerplate">code</a>.</p><h4>Setting up (This is optional. Mainly for learning purpose)</h4><p><strong>Step 1: Create the python virtual environment</strong></p><pre>mkdir Flask-AppBuilder-Boilerplate<br>cd Flask-AppBuilder-Boilerplate<br>python3 -m venv venv<br>source venv/bin/activate </pre><p><strong>Step 2: Install flask-appbuilder</strong></p><pre>pip install flask-appbuilder</pre><p><strong>Step 3: Initialise AppBuilder Project</strong></p><p>The pre-requisite will be a secret key. You can generate one by using: <a href="https://djecrety.ir/">https://djecrety.ir/</a></p><pre>flask fab create-app</pre><p>You may get a jinja2 error :</p><pre>ImportError: cannot import name ‘escape’ from ‘jinja2’</pre><p>In my case, the flask I was using was not the one in the virtual env. To make sure that you are using the right flask:</p><pre>python -m flask fab create-app</pre><p>I named my project boiler. This is the skeleton generated</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*8OdLwJC2K2bpoLXyamoJoA.png" /></figure><p><strong>Step 4: Start App</strong></p><pre>cd boiler<br>python -m flask run</pre><p>You can access the application through <a href="http://localhost:5000/">http://localhost:5000</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yzh7jamUE8lUR4Cl0HPdvg.png" /><figcaption>Flask Appbuilder Landing page</figcaption></figure><h4>Adding Docker and Admin</h4><p>Once you have the skeleton ready, We will create a requirements.txt file that will hold all required packages. This will be followed by the Dockerfile</p><pre>Werkzeug==3.1.3<br>wrapt==1.17.0<br>WTForms==3.2.1<br>gunicorn==23.0.0<br>psycopg2-binary<br>Flask-Mail<br>Flask-Migrate</pre><pre><br>FROM python:3.10-slim<br><br># Set environment variables to control the runtime behavior of your application.<br>ENV PYTHONDONTWRITEBYTECODE 1<br>ENV PYTHONUNBUFFERED 1<br><br>WORKDIR /app<br><br>COPY ./requirements.txt /app/requirements.txt<br><br>RUN pip install --no-cache-dir -r requirements.txt<br><br>COPY . /app<br><br>CMD [&quot;gunicorn&quot;, &quot;-b&quot;, &quot;0.0.0.0:8000&quot;, &quot;app:app&quot;]</pre><p>I will be using postgresql database for this code but fill free to make the necessary chnages. The default database is sqlite. We need to add the database credential details to an environment file.</p><p>To add the admin flask appbuilder uses cli command, however, I added it through code. I found this easier since I can have the admin email and password as environment variables. Below is the .env file</p><pre>ADMIN_PASSWORD=password<br>ADMIN_FIRST_NAME=admin<br>ADMIN_LAST_NAME=admin_p<br>ADMIN_EMAIL=admin@example.com<br>SECRET_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXX<br>POSTGRES_USER=test_user<br>POSTGRES_PASSWORD=password<br>POSTGRES_DB=test_db<br>POSTGRES_HOST=db<br>POSTGRES_PORT=5432</pre><p>In the __init__.py, we will add a function that will create the admin on start if they do not exist.</p><pre>from flask_appbuilder.security.sqla.models import User, Role<br>import os<br><br>user_name = os.getenv(&quot;ADMIN_EMAIL&quot;)<br>email = os.getenv(&quot;ADMIN_EMAIL&quot;)<br>password = os.getenv(&quot;ADMIN_PASSWORD&quot;)<br>first_name = os.getenv(&quot;ADMIN_FIRST_NAME&quot;)<br>last_name = os.getenv(&quot;ADMIN_LAST_NAME&quot;)<br><br><br>def create_admin_user(appbuilder):<br>    with app.app_context():<br>        session = appbuilder.get_session<br>        admin_user = session.query(User).select_from(User).join(Role, User.roles).filter(Role.name == &#39;Admin&#39;).first()<br>        if not admin_user:<br>            role_admin = session.query(Role).filter_by(name=&#39;Admin&#39;).first()<br>            new_admin = appbuilder.sm.add_user(<br>                username=user_name,<br>                email=email,<br>                role=role_admin,<br>                password=password,<br>                first_name=first_name,<br>                last_name=last_name<br><br>            )<br>            session.commit()<br><br>create_admin_user(appbuilder)<br></pre><p>Add the db url to the config.py file</p><pre>postgres_user=os.getenv(&quot;POSTGRES_USER&quot;)<br>postgres_password=os.getenv(&quot;POSTGRES_PASSWORD&quot;)<br>postgres_host=os.getenv(&quot;POSTGRES_HOST&quot;)<br>postgres_db=os.getenv(&quot;POSTGRES_DB&quot;)<br><br># The SQLAlchemy connection string.<br>SQLALCHEMY_DATABASE_URI = f&#39;postgresql://{postgres_user}:{postgres_password}@{postgres_host}/{postgres_db}&#39;</pre><p>To make sure that the changes to the database through the models are updated well, we will use Flask-Migrate.</p><blockquote>I find it interesting that this Falsk-Appbuilder does not come with this already built-in.</blockquote><pre>from flask_migrate import Migrate<br>Migrate(app, db, compare_type=True)</pre><p>To wrap everything up, we will create a docker-compose file that will be used to run the app and postgres database. The first time we will use flask init to initialize the database. Then afterwards we will use flask db migrate and flask db update. I have setup a service for doing this.</p><pre>version: &#39;3&#39;<br>services:<br>  db:<br>    image: postgres:15<br>    container_name: db<br>    environment:<br>      POSTGRES_USER: ${POSTGRES_USER}<br>      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}<br>      POSTGRES_DB: ${POSTGRES_DB}<br>    ports:<br>      - &#39;5432:5432&#39;<br>    volumes:<br>      - &quot;postgres_data:/var/lib/postgresql/data&quot;<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;pg_isready&quot;, &quot;-d&quot;, &quot;${POSTGRES_DB}&quot;, &quot;-U&quot;, &quot;${POSTGRES_USER}&quot;]<br>      interval: 1m30s<br>      timeout: 30s<br>      retries: 5<br>      start_period: 30s<br><br>  webapp:<br>    build: .<br>    container_name: flask_app<br>    command: gunicorn &quot;app:app&quot; -b 0.0.0.0:8000 --reload<br>    env_file:<br>      - .env<br>    ports:<br>      - &quot;8000:8000&quot;<br>    volumes:<br>      - &quot;.:/app&quot;<br>    depends_on:<br>      migrate:<br>        condition: service_completed_successfully<br>      db:<br>        condition: service_healthy<br>  migrate:<br>    build: .<br>    container_name: flask_app_migrate<br>    command: sh -c &#39;export FLASK_APP=app/__init__.py flask init&#39;<br>    env_file:<br>      - .env<br>    ports:<br>      - &quot;8001:8001&quot;<br>    volumes:<br>      - &quot;.:/app&quot;<br>    depends_on:<br>      db:<br>        condition: service_healthy<br>volumes:<br>  postgres_data:</pre><p>We will then start the application by running docker compose up — build</p><p>You can access the application through <a href="http://localhost:8000/">http://localhost:8000</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QmKxkaPccote2wXnlMn6Zg.png" /><figcaption>Landing Page</figcaption></figure><p>Login using the credentials in your .env file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gupTiNDdiKOywLl8oyOZkA.png" /><figcaption>Admin View</figcaption></figure><p>With this you can begin your work. If you need to allow users to self-register, you will add Mail, since you will need to verify the user. You can also choose to use some Auth providers such as google.</p><h4>Adding Mail and OAUTH 2</h4><p>Add the email client configs to he .env file</p><pre>MAIL_PASSWORD=&quot;XXXXXXX&quot;<br>MAIL_USERNAME=&quot;YYYYYYYYY&quot;<br>MAIL_DEFAULT_SENDER=&quot;YYYYYYY&quot;</pre><p>Add the environment variables to the config.py file</p><pre>MAIL_PASSWORD = os.getenv(&quot;MAIL_PASSWORD&quot;)<br>MAIL_USERNAME = os.getenv(&quot;MAIL_USERNAME&quot;)<br>MAIL_DEFAULT_SENDER = os.getenv(&quot;MAIL_DEFAULT_SENDER&quot;)<br>MAIL_SERVER = &#39;smtp.XXXXX.com&#39;<br>MAIL_PORT = 587 # or 465 for secure, or 587 for TLS<br>MAIL_USE_TLS = True # or False<br>MAIL_USE_SSL = False # or True if using SSL</pre><p>To add google OAUTH 2, you will need to get the credentials from google cloud console. I used this <a href="https://support.google.com/cloud/answer/6158849?hl=en">link</a> as a guide.</p><p>Add the credentials in the .env file.</p><pre>GOOGLE_SECRET=&quot;GGGGGGGGGGGGGGGGGGGG&quot;<br>GOOGLE_CLIENT_ID=&quot;SSSSSSSSSSSSSSSS&quot;</pre><p>Make sure to add the redirect url properly in your google console. This part took some time.</p><p>In the config.py, add this set of code.</p><pre><br>AUTH_TYPE = AUTH_OAUTH<br>OAUTH_PROVIDERS = [<br>    {<br>        &quot;name&quot;: &quot;google&quot;,<br>        &quot;icon&quot;: &quot;fa-google&quot;,<br>        &quot;token_key&quot;: &quot;access_token&quot;,<br>        &quot;remote_app&quot;: {<br>            &quot;client_id&quot;: GOOGLE_CLIENT_ID,<br>            &quot;client_secret&quot;: GOOGLE_SECRET,<br>            &quot;api_base_url&quot;: &quot;https://www.googleapis.com/oauth2/v2/&quot;,<br>            &quot;client_kwargs&quot;: {&quot;scope&quot;: &quot;email profile&quot;},<br>            &quot;request_token_url&quot;: None,<br>            &quot;access_token_url&quot;: &quot;https://accounts.google.com/o/oauth2/token&quot;,<br>            &quot;authorize_url&quot;: &quot;https://accounts.google.com/o/oauth2/auth&quot;,<br>            &quot;jwks_uri&quot;: &quot;https://www.googleapis.com/oauth2/v3/certs&quot;,<br>        },<br>    }]<br>AUTH_ROLES_MAPPING = {<br>    &quot;FAB_USERS&quot;: [&quot;User&quot;],<br>    &quot;FAB_ADMINS&quot;: [&quot;Admin&quot;],<br>}</pre><p>You will need to add Authlib and requests to the requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lfxlWqs4pMEtAB-qDperFg.png" /></figure><p>That is it. This will save you some hours in your project. I may just turn this into a series of startup code for DE projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94878e7b12b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blue/Green Deployment on AWS ECS With Terraform]]></title>
            <link>https://medium.com/@ywg/blue-green-deployment-on-aws-ecs-with-terraform-7dfd67502b5b?source=rss-5161d83115ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dfd67502b5b</guid>
            <category><![CDATA[codedeploy]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[aws-ecs]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Wambui Gitau]]></dc:creator>
            <pubDate>Tue, 18 Jul 2023 05:02:20 GMT</pubDate>
            <atom:updated>2023-07-18T05:02:20.985Z</atom:updated>
            <content:encoded><![CDATA[<p>Blue/Green deployment strategy means having two identical but separate environments. The blue environment is running the current version of the application and the green is running the new version of the application. Why is Blue/Green deployment important? It minimises downtime of applications during deployment. Applications on ECS tasks take sometime to deploy because of the draining process of ECS services.</p><h4>How does it work?</h4><p>The main concept of Blue/Green deployment is the shift of traffic from the current running application to the new version of the application. For this to be accomplished on AWS, there has to be 2 target groups and a load balancer. During deployment, the following steps take place:</p><ul><li>A new environment similar to the current running environment is created. The new environment is in target group 2</li><li>The new version of the application is deployed to the new environment</li><li>The new version of the application is tested using traffic testing. This is to make sure that the application is running well</li><li>The traffic is shifted from the current version to the new version</li><li>The old environment is deleted.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*qIZol95KNSsHQbpu_-9FkQ.png" /><figcaption>Blue/Green Concept</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*d767c6NYILOqgUUTK6khUg.png" /><figcaption>After deployment</figcaption></figure><h4>ECS Architecture</h4><p>For an application deployed on ECS Cluster, we use AWS CodeDeploy for Blue/Green Deployment. An example of an architecture of a service and task on ECS Cluster looks like the diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdImUwXt-nRZuZ0oK2CuJw.png" /><figcaption>AWS ECS Architecture Example</figcaption></figure><p><em>NB: Assumption is that you have a VPC already setup with public subnets</em></p><p>The resources used are:</p><ul><li>Application Load balancer for directing traffic to the different ports.</li></ul><pre>variable &quot;elb_sg_ingress_ports&quot; {<br>  type    = list(number)<br>  default = [80, 443, 8080]<br>}<br><br>resource &quot;aws_security_group&quot; &quot;application_elb_sg&quot; {<br>  vpc_id = var.vpc_id<br>  name   = &quot;application_elb_sg&quot;<br>}<br><br>resource &quot;aws_security_group_rule&quot; &quot;application_elb_sg_ingress&quot; {<br>  count             = length(var.elb_sg_ingress_ports)<br>  type              = &quot;ingress&quot;<br>  from_port         = var.elb_sg_ingress_ports[count.index]<br>  to_port           = var.elb_sg_ingress_ports[count.index]<br>  protocol          = &quot;tcp&quot;<br>  cidr_blocks       = [&quot;0.0.0.0/0&quot;]<br>  security_group_id = aws_security_group.application_elb_sg.id<br>} </pre><pre>resource &quot;aws_lb&quot; &quot;app_lb&quot; {<br>  name               = &quot;application_load_balancer&quot;<br>  load_balancer_type = &quot;application&quot;<br>  subnets            = var.public_subnets[*].id<br>  idle_timeout       = 60<br>  security_groups    = [aws_security_group.application_elb_sg.id]<br>}</pre><ul><li>Two target groups, blue and green</li></ul><pre>variable &quot;lb_target_group_name&quot; {<br>  type    = string<br>  default = &quot;tg&quot;<br>}<br><br>locals {<br>  target_groups = [<br>    &quot;green&quot;,<br>    &quot;blue&quot;,<br>  ]<br>}<br><br>resource &quot;aws_lb_target_group&quot; &quot;tg&quot; {<br>  count = length(local.target_groups)<br><br>  name        = &quot;${var.lb_target_group_443_name}-${element(local.target_groups, count.index)}&quot;<br>  port        = 443<br>  protocol    = &quot;HTTP&quot;<br>  target_type = &quot;instance&quot;<br>  vpc_id      = var.vpc_id<br>  health_check {<br>    matcher = &quot;200,301,302,404&quot;<br>    path    = &quot;/&quot;<br>  }<br><br>}</pre><ul><li>AWS Listeners: We will have 3 listeners — 443 which will be the one users communicate with, 80 as the main port and 8080 as the alternative port</li></ul><pre>resource &quot;aws_alb_listener&quot; &quot;l_80&quot; {<br>  load_balancer_arn = aws_lb.app_lb.arn<br>  port              = &quot;80&quot;<br>  protocol          = &quot;HTTP&quot;<br>  default_action {<br>    type = &quot;redirect&quot;<br>    redirect {<br>      port        = &quot;443&quot;<br>      protocol    = &quot;HTTPS&quot;<br>      status_code = &quot;HTTP_301&quot;<br>    }<br>  }<br>}<br><br>resource &quot;aws_alb_listener&quot; &quot;l_8080&quot; {<br>  load_balancer_arn = aws_lb.app_lb.id<br>  port              = 8080<br>  protocol          = &quot;HTTP&quot;<br><br>  default_action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.tg[1].arn<br>  }<br>}<br><br>resource &quot;aws_alb_listener&quot; &quot;l_443&quot; {<br>  load_balancer_arn = aws_lb.app_lb.arn<br>  port              = &quot;443&quot;<br>  protocol          = &quot;HTTPS&quot;<br>  certificate_arn   = XXXX<br>  default_action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.tg[0].arn<br>  }<br>  depends_on = [aws_lb_target_group.tg]<br><br>  lifecycle {<br>    ignore_changes = [default_action]<br>  }<br>}</pre><p>Port 80 redirects traffic to port 443. This is the HTTPS link that the users will be accessing. Traffic from 443 is forwarded to port 80. When the new environment is created, the port used will be 8080, the traffic will be forward to port 80.</p><ul><li>ECS Cluster, ECS Service and ECS Task Definition. Any environment variables that will be used by the Task will be defined in the Task Definition. For this example, the container will be on EC2, an alternative would have been AWS Fargate.</li></ul><pre>resource &quot;aws_ecr_repository&quot; &quot;app_ecr_repo&quot; {<br>  name         = &quot;app-ecr-repository&quot;<br>  force_delete = true<br>}<br><br>resource &quot;aws_ecs_cluster&quot; &quot;app_cluster&quot; {<br>  name = &quot;application_cluster&quot;<br>}<br><br>resource &quot;aws_ecs_service&quot; &quot;frontend&quot; {<br>  name                               = &quot;frontend&quot;<br>  cluster                            = aws_ecs_cluster.app_cluster.id<br>  task_definition                    = aws_ecs_task_definition.frontend_task.arn<br>  deployment_minimum_healthy_percent = 50<br>  deployment_maximum_percent         = 200<br>  health_check_grace_period_seconds  = 300<br>  launch_type                        = &quot;EC2&quot;<br>  scheduling_strategy                = &quot;REPLICA&quot;<br>  desired_count                      = 1<br><br><br>  force_new_deployment = true<br>  load_balancer {<br>    target_group_arn = aws_lb_target_group.tg[0].arn<br>    container_name   = &quot;app&quot; <br>    container_port   = &quot;80&quot; # Application Port<br>  }<br>  deployment_controller {<br>    type = &quot;CODE_DEPLOY&quot;<br>  }<br><br><br>  # workaround for https://github.com/hashicorp/terraform/issues/12634<br>  depends_on = [aws_lb.app_cluster]<br>  # we ignore task_definition changes as the revision changes on deploy<br>  # of a new version of the application<br>  # desired_count is ignored as it can change due to autoscaling policy<br>  lifecycle {<br>    ignore_changes = [task_definition, desired_count, load_balancer]<br>  }<br>}<br><br><br>resource &quot;aws_ecs_task_definition&quot; &quot;frontend_task&quot; {<br>  family = &quot;frontend-task&quot; <br>  container_definitions = jsonencode([{<br><br><br>    name      = &quot;app&quot;,<br>    image     = &quot;${var.aws_account_id}.dkr.ecr.${var.aws_account_region}.amazonaws.com/app-ecr-repository:&lt;revision_number&gt;&quot;,<br>    essential = true,<br>    portMappings = [<br>      {<br>        &quot;containerPort&quot; : 80 # Application Port<br>      }<br>    ],<br><br><br><br><br>    logConfiguration = {<br>      logDriver = &quot;awslogs&quot;<br>      options = {<br>        awslogs-group         = aws_cloudwatch_log_group.main.name<br>        awslogs-stream-prefix = &quot;ecs&quot;<br>        awslogs-region        = var.region<br>      }<br>    }<br>  }])<br>  requires_compatibilities = [&quot;EC2&quot;] # Stating that we are using ECS Fargate # Using awsvpc as our network mode as this is required for Fargate<br>  memory                   = 1800    # Specifying the memory our container requires<br>  cpu                      = 512     # Specifying the CPU our container requires<br>  execution_role_arn       = aws_iam_role.app_task_role.arn<br><br>}</pre><ul><li>AWS IAM Role</li></ul><pre>resource &quot;aws_iam_role&quot; &quot;app_task_role&quot; {<br>  name = &quot;app-task-role&quot;<br><br>  assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [<br>      {<br>        Effect = &quot;Allow&quot;,<br>        Principal = {<br>          Service = &quot;ecs-tasks.amazonaws.com&quot;<br>        },<br>        Action = &quot;sts:AssumeRole&quot;<br>      }<br>    ]<br>  })<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;ECS_task_execution&quot; {<br>  role       = aws_iam_role.app_task_role.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy&quot;<br>}</pre><h4>Deployment</h4><p>To deploy the application, AWS CodeDeploy will be used. CodeDeploy enables deployment using Blue/Green deployment. CodeDeploy handles the process of creation of the new task and assign the target group, test the traffic of the new application, shift the traffic and delete the old task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*20nIKGxMyDpdQl8PGAbqMA.png" /><figcaption>ECS Architecture after Deployment</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gyjCDcrsSrAWVZgc" /><figcaption>AWS CodeDeploy Deployment</figcaption></figure><p>CodeDeploy will need permissions to perform the above tasks. On the code section, the permissions needed are stated.</p><p>To shift the traffic, there are multiple ways of doing this and can be configured on CodeDeploy. One of the way is ECSAllAtOnce, this means that the traffic will be transferred all at once. Other options can be found <a href="https://docs.aws.amazon.com/codedeploy/latest/userguide/deployment-configurations.html">here</a>.</p><pre>resource &quot;aws_codedeploy_app&quot; &quot;frontend&quot; {<br>  compute_platform = &quot;ECS&quot;<br>  name             = &quot;frontend-deploy&quot;<br>}<br>resource &quot;aws_codedeploy_deployment_group&quot; &quot;frontend&quot; {<br>  app_name               = aws_codedeploy_app.frontend.name<br>  deployment_group_name  = &quot;frontend-deploy-group&quot;<br>  deployment_config_name = &quot;CodeDeployDefault.ECSAllAtOnce&quot;<br>  service_role_arn       = aws_iam_role.codedeploy.arn<br><br>  blue_green_deployment_config {<br>    deployment_ready_option {<br>      action_on_timeout = &quot;CONTINUE_DEPLOYMENT&quot;<br>    }<br><br>    terminate_blue_instances_on_deployment_success {<br>      action                           = &quot;TERMINATE&quot;<br>      termination_wait_time_in_minutes = 1<br>    }<br>  }<br><br>  ecs_service {<br>    cluster_name = aws_ecs_cluster.app_cluster.name<br>    service_name = aws_ecs_service.frontend.name<br>  }<br><br>  deployment_style {<br>    deployment_option = &quot;WITH_TRAFFIC_CONTROL&quot;<br>    deployment_type   = &quot;BLUE_GREEN&quot;<br>  }<br>  auto_rollback_configuration {<br>    enabled = true<br>    events  = [&quot;DEPLOYMENT_FAILURE&quot;]<br>  }<br><br>  load_balancer_info {<br>    target_group_pair_info {<br>      prod_traffic_route {<br>        listener_arns = [aws_alb_listener.l_443.arn]<br>      }<br><br>      target_group {<br>        name = aws_lb_target_group.tg[0].name<br>      }<br><br>      target_group {<br>        name = aws_lb_target_group.tg[1].name<br>      }<br><br>      <br>    }<br>  }<br><br>}<br><br>data &quot;aws_iam_policy_document&quot; &quot;assume_by_codedeploy&quot; {<br>  statement {<br>    sid     = &quot;&quot;<br>    effect  = &quot;Allow&quot;<br>    actions = [&quot;sts:AssumeRole&quot;]<br><br>    principals {<br>      type        = &quot;Service&quot;<br>      identifiers = [&quot;codedeploy.amazonaws.com&quot;]<br>    }<br>  }<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;codedeploy&quot; {<br>  name               = &quot;codedeploy&quot;<br>  assume_role_policy = data.aws_iam_policy_document.assume_by_codedeploy.json<br>}<br><br><br>data &quot;aws_iam_policy_document&quot; &quot;codedeploy&quot; {<br>  statement {<br>    sid    = &quot;AllowLoadBalancingAndECSModifications&quot;<br>    effect = &quot;Allow&quot;<br><br>    actions = [<br>      &quot;ecs:CreateTaskSet&quot;,<br>      &quot;ecs:DeleteTaskSet&quot;,<br>      &quot;ecs:DescribeServices&quot;,<br>      &quot;ecs:UpdateServicePrimaryTaskSet&quot;,<br>      &quot;elasticloadbalancing:DescribeListeners&quot;,<br>      &quot;elasticloadbalancing:DescribeRules&quot;,<br>      &quot;elasticloadbalancing:DescribeTargetGroups&quot;,<br>      &quot;elasticloadbalancing:ModifyListener&quot;,<br>      &quot;elasticloadbalancing:ModifyRule&quot;,<br>      &quot;s3:GetObject&quot;<br>    ]<br><br>    resources = [&quot;*&quot;]<br>  }<br>  statement {<br>    sid    = &quot;AllowPassRole&quot;<br>    effect = &quot;Allow&quot;<br><br>    actions = [&quot;iam:PassRole&quot;]<br><br>    resources = [<br>      aws_iam_role.app_task_role.arn<br>    ]<br>  }<br><br>  statement {<br>    sid    = &quot;DeployService&quot;<br>    effect = &quot;Allow&quot;<br><br>    actions = [&quot;ecs:DescribeServices&quot;,<br>      &quot;codedeploy:GetDeploymentGroup&quot;,<br>      &quot;codedeploy:CreateDeployment&quot;,<br>      &quot;codedeploy:GetDeployment&quot;,<br>      &quot;codedeploy:GetDeploymentConfig&quot;,<br>    &quot;codedeploy:RegisterApplicationRevision&quot;]<br><br>    resources = [<br>      aws_ecs_service.frontend.id,<br>      aws_codedeploy_deployment_group.frontend.arn,<br>      &quot;arn:aws:codedeploy:${var.region}:${var.aws_account_id}:deploymentconfig:*}&quot;,<br>      aws_codedeploy_app.frontend.arn<br>    ]<br>  }<br><br><br>}<br>resource &quot;aws_iam_role_policy&quot; &quot;codedeploy&quot; {<br>  role   = aws_iam_role.codedeploy.name<br>  policy = data.aws_iam_policy_document.codedeploy.json<br>}</pre><h4>CodeDeploy Deployment Process</h4><p>To deploy, the following steps are to be taken:</p><ul><li>Build the docker image</li><li>Push the docker image to AWS ECR</li><li>Get the task definition using AWS CLI</li></ul><pre>aws ecs describe-task-definition — task-definition “$ecs_task_def_name” — query taskDefinition &gt; task-definition.json</pre><ul><li>Update the code deploy appspec.yaml file</li></ul><p>sample appspec file:</p><pre>applicationName: &#39;code-deploy-app&#39;<br>deploymentGroupName: &#39;code-deploy-deployment-group&#39;<br>revision:<br>  revisionType: AppSpecContent<br>  appSpecContent:<br>    content: |<br>      version: 0.0<br>      Resources:<br>        - TargetService:<br>            Type: AWS::ECS::Service<br>            Properties:<br>              TaskDefinition: &quot;[YOUR_TASK_DEFINITION_ARN]&quot;<br>              LoadBalancerInfo:<br>                ContainerName: &quot;ecs-service-container&quot;<br>                ContainerPort: 80</pre><ul><li>Deploy code using code deploy</li></ul><pre>aws deploy create-deployment --cli-input-yaml file://appspec.yaml</pre><h4>Cons of Blue/Green Deployment</h4><p>One of the main cons of using Blue/Green Deployment is that it is expensive. Since you need a replica of the running environment, it means that you will require double the resources. For an expensive environment, this deployment strategy may not be the best.</p><h4>References</h4><ul><li><a href="https://techsparx.com/nodejs/docker/simple-node-service-discovery-ecs-terraform.html">Terraform deployment on AWS ECS a multi-tier Node.js and Nginx system using Service Discovery</a></li><li><a href="https://docs.aws.amazon.com/AmazonECS/latest/userguide/service-create-loadbalancer-bluegreen.html">Configuring a load balancer for the blue/green deployment type — Amazon ECS</a></li><li><a href="https://docs.aws.amazon.com/codedeploy/latest/userguide/tutorial-ecs-deployment.html">https://docs.aws.amazon.com/codedeploy/latest/userguide/tutorial-ecs-deployment.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dfd67502b5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Lambda + Terraform + Github Actions Deployment]]></title>
            <link>https://medium.com/@ywg/aws-lambda-terraform-github-actions-deployment-97e38fd14c2b?source=rss-5161d83115ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/97e38fd14c2b</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Wambui Gitau]]></dc:creator>
            <pubDate>Tue, 07 Mar 2023 05:02:44 GMT</pubDate>
            <atom:updated>2023-03-07T13:02:21.617Z</atom:updated>
            <content:encoded><![CDATA[<p>AWS Lambda is an AWS component that enables you to run code without worrying about the underlying infrastructure (Serverless Computing). It scales up and down depending on the needs. It is cost effective for tasks that take less than 15mins since there is no need for idle instances.</p><p>AWS Lambda can either be <strong>Event Source</strong> (trigger from an event. Can be change of resource/data e.g S3, DynamoDB, IoT) or <strong>Functions </strong>(Piece of code that is run when a event occurs. Currently supporting 4 languages — Node.js, Python, Java 8 and C#)</p><p>In data engineering, it is mostly used for extraction or simple transformation of data. For data extraction, one can consume APIs, IoT, Webhooks just to name a few. For simple transformations like create subsets of raw dataset, renaming of columns, changing of data types. AWS Lambda have memory limitation of 128MB to 1.5GB. Therefore for complex transformations, one can use other resources such as spark.</p><p>In the remainder of this post, we will look at AWS Lambda Functions. We will learn the following:</p><ul><li>Working with Localstack</li><li>Resources that work with AWS Lambda</li><li>Creating AWS Lambda using Terraform</li><li>Creating Lambda functions whose code will be stored on S3</li><li>Deploying the Lambda function code using githun actions workflow</li></ul><h4>Prerequisite</h4><ul><li>Terraform installed</li><li>Python 3.7+ installed</li><li>docker installed</li><li>Terraform Basics</li><li>AWS basics</li><li>AWS CLI</li></ul><h4>LocalStack</h4><p><a href="https://localstack.cloud/solutions/cloud-emulation/">Localstack</a> is a fully local cloud stack. This is used when you want to create your infrastructure without incurring server costs. For this post, we will use Localstack with AWS.</p><ul><li>Installing Localstack</li></ul><pre>brew install localstack<br>localstack --help</pre><h4>AWS + Terraform</h4><p>The primary resources that we will be using is S3 and Lambda functions. The secondary resource will be IAM roles. Code will be organised in a module form. The folder structure will look like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*HnnQC3CVGtGxUvsRSDdhjg.png" /><figcaption>folder structure</figcaption></figure><p>I found it easier to configure terraform through terraform provider instead of using tflocal. This is because I came across the error below when creating S3:</p><pre>dial tcp: lookup s3.localhost.localstack.cloud on 192.168.178.1:53: no such host</pre><p>The provider file will look as below:</p><pre>provider &quot;aws&quot; {<br>  access_key                  = &quot;test&quot;<br>  secret_key                  = &quot;test&quot;<br>  region                      = &quot;us-east-1&quot;<br><br>  # only required for non virtual hosted-style endpoint use case.<br>  # https://registry.terraform.io/providers/hashicorp/aws/latest/docs#s3_force_path_style<br>  s3_use_path_style           = true<br>  skip_credentials_validation = true<br>  skip_metadata_api_check     = true<br>  skip_requesting_account_id  = true<br><br>  endpoints {<br>    s3             = &quot;http://localhost:4566&quot;<br>    lambda         = &quot;http://localhost:4566&quot;<br>    iam            = &quot;http://localhost:4566&quot;<br>  }<br>}</pre><p>You will run aws configure and set up dummy values.</p><p>The main file will be used to initialise the module.</p><pre>module &quot;lambda&quot; {<br>  source = &quot;./lambda&quot;<br>}</pre><p>For S3, we will create a bucket and a bucket object. The object will be created inside the lambda file. The bucket will store the code. Below is the S3 file:</p><pre>resource &quot;aws_s3_bucket&quot; &quot;code_bucket&quot; {<br>    bucket = var.code_bucket_name<br>}<br><br>resource &quot;aws_s3_bucket_server_side_encryption_configuration&quot; &quot;code&quot; {<br>  bucket = aws_s3_bucket.code_bucket.bucket<br><br>  rule {<br>    apply_server_side_encryption_by_default {<br>      sse_algorithm = &quot;AES256&quot;<br>    }<br>  }<br>}</pre><p>Lambda file will consist of the lambda function, S3 bucket object and the dummy archive file which is necessary at the beginning. If you have layers, this is where they will be placed.</p><p>The S3 bucket object states where the zipped lambda function will be stored. The archive file will zip the lambda function folder.</p><pre>resource &quot;aws_s3_object&quot; &quot;lambda_function&quot; {<br>  bucket = aws_s3_bucket.code_bucket.id<br>  key    = &quot;localstack_test/lambda_function.zip&quot;<br>  source = data.archive_file.lambda_function.output_path<br>  etag   = filemd5(data.archive_file.lambda_function.output_path)<br><br>lifecycle {<br>    ignore_changes = all<br>  }<br>}<br><br><br>data &quot;archive_file&quot; &quot;lambda_function&quot; {<br>  type        = &quot;zip&quot;<br>  source_dir  = &quot;${path.module}/lambda_function&quot;<br>  output_path = &quot;${path.module}/lambda_function.zip&quot;<br>}<br><br>resource &quot;aws_lambda_function&quot; &quot;hello_world_function&quot; {<br>  function_name = &quot;HelloWorldLambda&quot;<br>  handler       = &quot;hello_world.main_handler&quot;<br>  runtime       = &quot;python3.7&quot;<br>  s3_bucket = aws_s3_bucket.code_bucket.bucket<br>  s3_key    = aws_s3_object.lambda_function.key<br>  environment {<br>    variables = {<br>      test_var = &quot;hello&quot;<br>    }<br>  }<br>}</pre><p>For the roles, we will have only one role the <em>assume role</em> and the <em>AWSLambdaBasicExecutionRole</em> policy. We will then tie the role to lambda function. This can be done by adding role variable to the function:</p><pre>role          = aws_iam_role.lambda_execution_role.arn</pre><p>Below is the code on iam.if:</p><pre>data &quot;aws_iam_policy&quot; &quot;AWSLambdaBasicExecutionRole&quot; {<br>  arn = &quot;arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole&quot;<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;AWSLambdaBasicExecutionRole&quot; {<br>  role       = aws_iam_role.lambda_execution_role.name<br>  policy_arn = data.aws_iam_policy.AWSLambdaBasicExecutionRole.arn<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;lambda_execution_role&quot; {<br>  name = &quot;helloworld-api-execution-role&quot;<br><br><br>  assume_role_policy = jsonencode(<br>    {<br>      Version = &quot;2012-10-17&quot;,<br>      Statement = [{<br>        Action = &quot;sts:AssumeRole&quot;,<br>        Principal = {<br>          Service = &quot;lambda.amazonaws.com&quot;<br>        },<br>        Effect = &quot;Allow&quot;<br>      }]<br>    }<br>  )<br>}</pre><p>Create a lambda function folder that will have the dummy lambda function file <em>hello_world.py. </em>The dummy code will be as below:</p><pre>import os<br><br>def main_handler(event, context):<br>    <br>    test_var = os.environ[&#39;test_var&#39;]<br>    return {&quot;message&quot;: test_var, &quot;Status&quot;: 200}</pre><p>When that is done, run the terraform commands to create the resources. Open a terminal and paste the command below:</p><pre>localstack start</pre><p>Open a new terminal to run terraform. Below are the commands:</p><pre>terraform init<br>terraform plan<br>terraform apply</pre><p>When the commands are completed, you can test whether the resources have been created by running:</p><pre>aws --endpoint-url=http://localhost:4566 s3 ls s3://test-bucket<br><br>aws --endpoint-url=http://localhost:4566 lambda list-functions</pre><h4>Deployment</h4><p>By default, terraform has been setup to deploy lambda functions. Ideally, IaC and Application code repos are always separated. Therefore, there is a need to not use terraform to deploy the lambda function. To do that, we will use Github Actions to deploy the code.</p><p>The following are the steps taken to deploy lambda function on AWS:</p><ul><li>Create a user who will be given multiple roles. Create user.tf and also create access key id and secret key. This will be needed for authentication.</li></ul><pre>resource &quot;aws_iam_user&quot; &quot;gh_actions&quot; {<br>  name = &quot;github_action_deploy_user&quot;<br>  path = &quot;/&quot;<br>  <br>}<br><br>resource &quot;aws_iam_access_key&quot; &quot;gh_actions&quot; {<br>  user = aws_iam_user.gh_actions.name<br>}<br><br>resource &quot;aws_secretsmanager_secret&quot; &quot;gh_actions&quot; {<br>  description             = &quot;GitHub actions Lambda Code user credentials&quot;<br>  name                    = &quot;github_action_deploy_user_credentials&quot;<br>  recovery_window_in_days = 0<br>}<br><br>resource &quot;aws_secretsmanager_secret_version&quot; &quot;gh_actions&quot; {<br>  secret_id     = aws_secretsmanager_secret.gh_actions.id<br>  secret_string = jsonencode({ &quot;aws_access_key_id&quot; = aws_iam_access_key.gh_actions.id, &quot;aws_secret_access_key&quot; = aws_iam_access_key.gh_actions.secret })<br>}</pre><ul><li>Grant the user permissions. The user will need permission to get and put objects in the S3 object. They will also need permission to update the function code. Add the below code to iam.tf</li></ul><pre>resource &quot;aws_s3_bucket_acl&quot; &quot;s3_bucket&quot; {<br>  bucket = aws_s3_bucket.code_bucket.id<br>  acl    = &quot;private&quot;<br>}<br><br>data &quot;aws_iam_policy_document&quot; &quot;code_bucket_gh_actions_policy_document&quot; {<br>  statement {<br>    sid    = &quot;GHUserPermissionS3&quot;<br>    effect = &quot;Allow&quot;<br><br>    actions = [<br>      &quot;s3:getObject&quot;,<br>      &quot;s3:putObject&quot;,<br>    ]<br><br>    resources = [<br>      &quot;${data.aws_s3_bucket.code_bucket.arn}&quot;,<br>      &quot;${data.aws_s3_bucket.code_bucket.arn}/*&quot;<br>    ]<br>  }<br><br>  statement {<br>    sid    = &quot;GHUserUpdateFunctionRole&quot;<br>    effect = &quot;Allow&quot;<br><br>    actions = [<br>      &quot;lambda:UpdateFunctionCode&quot;<br>    ]<br><br>    resources = [<br>      &quot;${aws_lambda_function.lambda_function.arn}&quot; ]<br>  }<br>}<br><br>resource &quot;aws_iam_user_policy&quot; &quot;code_bucket_gh_actions_policy&quot; {<br>  name   = &quot;${aws_iam_user.gh_actions.name}-code-bucket-policy&quot;<br>  user   = aws_iam_user.gh_actions.id<br>  policy = data.aws_iam_policy_document.code_bucket_gh_actions_policy_document.json<br><br><br>}</pre><ul><li>Add environment variables on github. Under repo -&gt; Settings → Secrets and Variables -&gt; Actions</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*NeU5zareS_DQy4W11IxE_A.png" /></figure><p>Create an environment. Then on the environment create AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY . The value can be found in the secret manager called gh_actions .</p><ul><li>Zip the code. The assumption here is that this is a new repo. For the purpose of illustration, i will create a new folder outside tf to place the code.</li></ul><pre>zip -jr lambda_test/lambda_function.zip lambda_test/hello_world_.py</pre><ul><li>Upload the zipped code to S3 bucket</li></ul><pre>aws s3 cp lambda_test/lambda_function.zip s3://test-bucket/localstack_test/</pre><ul><li>Update the function code. At the moment, AWS does to automatically monitor changes to S3 buckets that have lambda functions. Therefore one needs to update the code but with S3 key stated.</li></ul><pre>aws lambda update-function-code --function-name &quot;arn:aws:lambda:us-east-1:&lt;acccount_id&gt;:function:HelloWorldLambda&quot;  --s3-bucket &quot;test-bucket&quot; --s3-key &quot;localstack_test/lambda_function.zip&quot;<br></pre><ul><li>Wait for the update to be completed. Updating function takes a while. If there are other commands such as publishing the code, it will fail unless update is completed.</li></ul><pre>aws lambda wait function-updated --function-name &quot;arn:aws:lambda:us-east-1:&lt;account_id&gt;:function:HelloWorldLambda&quot;</pre><p>All the above can be put into a github action workflow which will update function when there is a change in file. Create a file under .github/workflows deploy_lambda.yml</p><pre>name: Deploy Lambda Function Through S3<br><br>on:<br>  push:<br>    branches:<br>      - main<br>    paths:<br>      - &quot;lambda_test/hello_world_.py&quot;<br><br>env:<br>  AWS_REGION: &quot;us-east-1&quot;<br>  S3_BUCKET_NAME: &quot;test-bucket&quot;<br><br>jobs:<br>  Deploy-Lambda-Functions:<br>    name: Deploy Function<br>    runs-on: ubuntu-latest<br><br>    environment: &quot;dev&quot;<br>    steps:<br>      - uses: actions/checkout@v3<br>      - name: Configure AWS credentials<br>        uses: aws-actions/configure-aws-credentials@v1<br>        with:<br>          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}<br>          aws-region: ${{ env.AWS_REGION}}<br><br>      - name: Zip file<br>        run: zip -jr lambda_test/lambda_function.zip lambda_test/hello_world_.py<br>      - name: Copy File to S3<br>        run: |<br>          aws s3 cp lambda_test/lambda_function.zip s3://test-bucket/localstack_test/<br>      - name: Upload Function to Lambda<br>        run: |<br>          aws lambda update-function-code --function-name &quot;arn:aws:lambda:us-east-1:&lt;account_id&gt;:function:HelloWorldLambda&quot;  --s3-bucket &quot;test-bucket&quot; --s3-key &quot;localstack_test/lambda_function.zip&quot;<br>      - name: Remove Zip File<br>        run: rm lambda_test/lambda_function.zip<br>      - name: Wait for update to finish<br>        run: aws lambda wait function-updated --function-name &quot;arn:aws:lambda:us-east-1:&lt;account_id&gt;:function:HelloWorldLambda&quot;</pre><p>This will deploy the code on push to main branch.</p><h4>Summary</h4><p>At the end of this post, you should be able to:</p><ul><li>Create Lambda function with code stored on S3</li><li>Give the Lambda functions the write permissions to be deployed using github</li><li>Create AWS resources using Terraform and Localstack</li><li>Deploy Lambda function using Github Actions</li></ul><p>The code can be found <a href="https://github.com/yvonnegitau/aws_terraform/tree/main/lambda">here</a>. In the next post, we will look at how to work with Lambda that is located in a VPC.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97e38fd14c2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fintech Data Engineering Stack with Azure]]></title>
            <link>https://medium.com/@ywg/fintech-data-engineering-stack-with-azure-1ab10b425a20?source=rss-5161d83115ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ab10b425a20</guid>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Wambui Gitau]]></dc:creator>
            <pubDate>Tue, 16 Aug 2022 09:48:04 GMT</pubDate>
            <atom:updated>2022-08-16T09:48:04.603Z</atom:updated>
            <content:encoded><![CDATA[<p>For the last two months, I have been developing a data stack for a fintech company. The main question being asked is who are our clients, how do we retain them and how do we add more clients.</p><p>The basic services offered by most fintech companies is transfer money from one account to another. The sender is usually an individual and the receiver is either an individual or a business.</p><h4>Project Approach</h4><p>The most critical part of the architecture is data protection; securing the data is important in determining the how the infrastructure is setup.</p><p>To answer the above question, I had to get the transactional data, senders information and customer acquisition data.</p><p>Since the data to be consumed does not affect real-time decisions, the data will be ingested in batches. I decided to ingest the data every dawn so that reports of the past day ready as the business team starts the day.</p><p>When designing the cloud infrastructure, first I created a private network within Azure. The data will not be accessible to anyone other than the organization. Connection to the transactional database will be through API in a site to site VPN connection as described in this <a href="https://blog.heptanalytics.com/connecting-a-linux-vps-to-an-aws-vpc-using-a-s2s-vpn-with-static-routing/">blog</a>.</p><h4>Data Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0EQTO18Aloeht0kviQejxg.png" /><figcaption>Data Stack Architecture</figcaption></figure><p>For this project, there are 3 data sources. The third party source for transactional data is being used to complete data about the senders. Some information like where the card is from and where the sender is transforming from are added.</p><p>Google Analytics data is used to understand the marketing output. The data was used to get the origin of the customers. How did the company acquire the customer. This information can be used by the sales and marketing team to create strategies around customer acquisition.</p><p>Since the data was being consumed via APIs, I used serverless functions. There was no need of creating a Virtual machine and hosting an application to consume the APIs. To make sure idempotent is maintained, I created a function for each API.</p><p>Data lake is used to store the raw data. This data can be used by data scientists when creating ML models for fraud detection and also recommendation models.</p><p>Data transformation was done by databricks notebooks. This could be substituted with normal python notebooks however I found working with pyspark easier.</p><p>The data warehouse used was the simplest since the data was to massive. For 1TB and above, one can choose serveless solutions such as Big query and Azure Synapse. I created data marts for the business team.</p><p>The output was a KPI dashboard that was to be used by the business team team to make decisions and business strategies. With the data, one can have multiple outputs such as data customer platform which will be consumed by the customers or reverse ETL where the data will be fed back to the application or CRMs.</p><h4>Azure Components</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y5Oec1kZX8e_g7I99NZ7qw.png" /><figcaption>Azure Data Stack</figcaption></figure><p>Implementation of the stack using Azure is as above. For serveless functions, I used azure functions. For the data lake, I used Azure blob storage to store the API responses in form of parquet files.</p><p>Transformation of the data is done using Azure databricks notebooks with pyspark and the transformed data is stored in the data warehouse, Azure SQL server. The dashboard is created using the transformed data in data warehouse with PowerBI.</p><p>Azure data factory was used to orchestrate the pipeline . The jobs run every dawn, the business team get the updated reports of the previous day ready.</p><p>The next step would be to feed the information back to the CRM so that the sales and marketing team would have personalized campaigns or creating a data customer platform for the customers. The potential is endless depending on the organization and their strategy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ab10b425a20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Engineering Zoomcamp - Week 7(Project)]]></title>
            <link>https://medium.com/@ywg/data-engineering-zoomcamp-week-7-project-b16e59d40211?source=rss-5161d83115ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/b16e59d40211</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Wambui Gitau]]></dc:creator>
            <pubDate>Mon, 04 Apr 2022 07:13:12 GMT</pubDate>
            <atom:updated>2022-04-04T07:13:12.629Z</atom:updated>
            <content:encoded><![CDATA[<p>I had to skip week 6 about Kafka since it needed a lot of time and because I was not going to use it in the project. For this project, I will be analyzing Iowa liquor sales which are updated every month. The source of the data is found <a href="https://data.iowa.gov/Sales-Distribution/Iowa-Liquor-Sales/m3tr-qhgy">here</a> and the data is consumed via API.</p><p>I created two branches on Github, one for dev and the other for production. The source for the project can be found <a href="https://github.com/yvonnegitau/iowadataset_pipeline">here</a>.</p><p>I used the steps below to complete the project:</p><ul><li>Create VM and BigQuery table and dataset in GCP using terraform</li><li>Create a docker image of airflow and dbt</li><li>Create extract and load dags</li><li>Create dags to execute dbt for data transformation</li><li>Deploy to VM</li><li>Create Reports using Data Studio</li></ul><h4>Create VM and BigQuery table and dataset in GCP using terraform</h4><ol><li>Create a project in GCP</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*8hS_rNScErtOMKTYGAEyLA.png" /><figcaption>create GCP project</figcaption></figure><p>2. Create service account</p><p>From <a href="https://console.cloud.google.com/iam-admin/serviceaccounts">here</a>, create the project service account. We will need the following permissions (for production case, limit the permissions to the minimum):</p><ul><li>compute admin</li><li>Bigquery admin</li></ul><p>3. Add key to the service account and download the json file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dfarIYb1VgEgcbIHPJ-_Nw.png" /><figcaption>add a new json key</figcaption></figure><p>4. Create a folder called terraform and inside create a file called main.tf. Then add the initial provider details. run terraform init</p><pre>provider &quot;google&quot; {<br>  project = var.project<br>  region = var.region<br>  credentials = var.gcp-creds<br>}</pre><p>5. Add the compute instance , firewall configuration and bigquery details</p><pre>resource &quot;google_compute_instance&quot; &quot;default&quot; {<br>  name = &quot;iowa-vm&quot;<br>  machine_type = &quot;custom-2-8192&quot; #ec2 machine with 2vcpu and 8gb ram<br>  zone = &quot;us-central1-a&quot;</pre><pre>boot_disk {<br>    initialize_params {<br>        image = &quot;ubuntu-os-cloud/ubuntu-1804-lts&quot;<br>        size = 100 // size of the disc<br>    }<br>  }<br>  network_interface {<br>    network = &quot;default&quot;</pre><pre>access_config {<br>      // VM will be give exteranl IP address<br>    }<br>  }<br>  metadata_startup_script = &quot;sudo apt-get update &amp;&amp; sudo apt-get install docker wget -y&quot; # making sure that docker is installed<br>  tags = [ &quot;http-server&quot;,&quot;https-server&quot; ]<br>}<br>resource &quot;google_compute_firewall&quot; &quot;http-server&quot; { # allowing port 8080 and 80 to be accessed<br>  name = &quot;allow-default-http&quot;<br>  network = &quot;default&quot;</pre><pre>allow {<br>    protocol = &quot;tcp&quot;<br>    ports = [ &quot;80&quot;,&quot;8080&quot;,&quot;8000&quot; ]<br>  }<br>  source_ranges = [&quot;0.0.0.0/0&quot;]<br>  target_tags = [ &quot;http-server&quot; ]<br>}<br>output &quot;ip&quot; {<br>  value = &quot;${google_compute_instance.default.network_interface.0.access_config.0.nat_ip}&quot;<br>}</pre><pre>resource &quot;google_bigquery_dataset&quot; &quot;dataset&quot; {<br>  dataset_id = var.BQ_DATASET<br>  project = var.project<br>  location = var.region<br>  <br>}</pre><p>6. Create a variables.tf file that will contain all the variables</p><pre>variable &quot;project&quot; {<br>  description = &quot;GDP PROJECT ID&quot;<br>}</pre><pre>variable &quot;region&quot; {<br>  description= &quot;Resource for GDP closest to location&quot;<br>  default = &quot;us-central1&quot;<br>  type = string<br>}</pre><pre>variable &quot;gcp-creds&quot; {<br>  description = &quot;GDP SERVICE ACCOUNT KEY&quot;<br>  sensitive   = true<br>}<br>variable &quot;BQ_DATASET&quot; {<br>  description = &quot;BigQuery Dataset that raw data (from GCS) will be  written to&quot;<br>  type = string<br>  default = &quot;iowa_data&quot;<br>}<br>variable &quot;BQ_TABLE&quot; {<br>  description=&quot;Raw data table&quot;<br>  default = &quot;sales_raw_data&quot;<br>}</pre><p>7. run terraform init -upgrade then terraform apply .For the key json file that you downloaded, remove all next line and have one long text. This is what you will use when asked about gcp-creds.</p><p>8. Go to GCP console and make sure the VM is created well</p><p>7. ssh to the vm using</p><pre>gcloud compute ssh --project=PROJECT_ID \<br> --zone=ZONE \<br> VM_NAME</pre><h4>Create a docker image of airflow</h4><ol><li>Create a folder called docker</li><li>Inside the docker folder, create docker-compose.yml and Dockerfile</li></ol><p>We will have two postgres instances: one for airflow and another for dbt.</p><pre>version: &#39;3&#39;</pre><pre>services:<br>  postgres-airflow:<br>    image: postgres<br>    environment:<br>      POSTGRES_PASSWORD: pssd<br>      POSTGRES_USER: airflowuser<br>      POSTGRES_DB: airflowdb</pre><pre>      AIRFLOW_SCHEMA: airflow<br>    expose:<br>      - 5432<br>    restart: always<br>    volumes:<br>      - ./script_postgress:/docker-entrypoint-initdb.d</pre><pre> postgres-dbt:<br>    image: postgres<br>    environment:<br>      POSTGRES_PASSWORD: pssd<br>      POSTGRES_USER: dbtuser<br>      POSTGRES_DB: dbtdb<br>      DBT_RAW_DATA_SCHEMA: dbt_raw_data</pre><pre>      DBT_SCHEMA: dbt<br>    expose:<br>      - 5432<br>    restart: always<br>    volumes:<br>      - ./data:/opt/iowa/data</pre><p>The add the airflow service which will be built using the dockerfile. The image will be python, airflow and dbt will be installed using pip.</p><pre>airflow:<br>    build: .<br>    restart: always<br>    environment: <br>      DBT_PROFILES_DIR: /opt/iowa/dbt<br>      AIRFLOW_HOME: /opt/iowa/airflow<br>      AIRFLOW__CORE__DAGS_FOLDER: /opt/iowa/airflow/dags<br>      AIRFLOW__CORE__EXECUTOR: LocalExecutor<br>      AIRFLOW__CORE__PARALLELISM: 4<br>      AIRFLOW__CORE__DAG_CONCURRENCY: 4<br>      AIRFLOW__CORE__MAX_ACTIVE_RUNS_PER_DAG: 4<br>      AIRFLOW__CORE__LOAD_EXAMPLES: &#39;false&#39;<br>      # AIRFLOW__ADMIN__HIDE_SENSITIVE_VARIABLE_FIELDS: False<br>      # Postgres details need to match with the values defined in the postgres-airflow service<br>      POSTGRES_USER: airflowuser<br>      POSTGRES_PASSWORD: pssd<br>      POSTGRES_HOST: postgres-airflow<br>      POSTGRES_PORT: 5432<br>      POSTGRES_DB: airflowdb<br>      # postgres-dbt connection details. Required for the inital loading of seed data<br>      # Credentials need to match with service postgres-dbt<br>      DBT_POSTGRES_PASSWORD: pssd<br>      DBT_POSTGRES_USER : dbtuser<br>      DBT_POSTGRES_DB : dbtdb<br>      DBT_DBT_SCHEMA: dbt<br>      DBT_DBT_RAW_DATA_SCHEMA: dbt_raw_data<br>      DBT_POSTGRES_HOST: postgres-dbt</pre><pre>      GOOGLE_APPLICATION_CREDENTIALS: /.google/credentials/google_credentials_iowa.json<br>      AIRFLOW_CONN_GOOGLE_CLOUD_DEFAULT: &#39;google-cloud-platform://?extra__google_cloud_platform__key_path=/.google/credentials/google_credentials_iowa.json&#39;<br>      GCP_PROJECT_ID: &#39;iowa-project-de&#39;<br>      GCP_GCS_BUCKET: &#39;iowa_data_lake&#39;<br>      GCP_BQ_DATASET: &#39;iowa_data&#39;<br>      DEPLOY_STATUS: &#39;dev&#39;</pre><pre>   depends_on:<br>      - postgres-airflow<br>      - postgres-dbt<br>    ports:<br>      - 8000:8080<br>    volumes:<br>      - ./dbt:/opt/iowa/dbt<br>      - ./data:/opt/iowa/data<br>      - ./airflow:/opt/iowa/airflow<br>      - ~/.google/credentials/:/.google/credentials:ro</pre><p>The dockerfile will have the code below. All the packages to be installed will be put in the requirements text file.</p><pre>FROM python:3.9</pre><pre>COPY requirements.txt .<br>RUN pip install -r requirements.txt</pre><pre>RUN pip uninstall markupsafe -y<br>RUN pip install markupsafe==2.0.1</pre><pre>RUN mkdir /project<br>COPY scripts/ /project/scripts/</pre><pre>COPY dbt/profiles.yml /root/.dbt/profiles.yml</pre><pre>RUN chmod +x /project/scripts/airflow_init.sh</pre><pre>ENTRYPOINT [ &quot;/project/scripts/airflow_init.sh&quot; ]</pre><p>Add airflow initialization script airflow_init.sh that is used to create the user.</p><pre>#!/usr/bin/env bash</pre><pre># Setup DB Connection String<br>AIRFLOW__CORE__SQL_ALCHEMY_CONN=&quot;postgresql+psycopg2://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}&quot;<br>export AIRFLOW__CORE__SQL_ALCHEMY_CONN</pre><pre>AIRFLOW__WEBSERVER__SECRET_KEY=&quot;openssl rand -hex 30&quot;<br>export AIRFLOW__WEBSERVER__SECRET_KEY</pre><pre>DBT_POSTGRESQL_CONN=&quot;postgresql+psycopg2://${DBT_POSTGRES_USER}:${DBT_POSTGRES_PASSWORD}@${DBT_POSTGRES_HOST}:${POSTGRES_PORT}/${DBT_POSTGRES_DB}&quot;</pre><pre>cd /opt/iowa/dbt/iowa &amp;&amp; dbt compile<br>rm -f /opt/iowa/airflow/airflow-webserver.pid</pre><pre>sleep 10<br>airflow db upgrade<br>sleep 10<br>airflow connections add &#39;dbt_postgres_instance_raw_data&#39;  --conn-uri &quot;${DBT_POSTGRESQL_CONN}&quot;<br>airflow users create \<br>          --username airflow \<br>          --firstname fname \<br>          --lastname lname \<br>          --password airflow \<br>          --role Admin \<br>          --email <a href="/service/mailto:email@email.com">email@email.com</a><br>airflow scheduler &amp; airflow webserver</pre><p>Have a file to initialize the postgres database: init-user-db.sh. This will be put in a folder called script-postgres.</p><pre>#!/bin/bash<br>set -e<br>psql -v ON_ERROR_STOP=1 — username &quot;$POSTGRES_USER&quot; — dbname &quot;$POSTGRES_DB&quot; &lt;&lt;-EOSQL<br> ALTER ROLE $POSTGRES_USER SET search_path TO $AIRFLOW_SCHEMA;<br> — CREATE SCHEMA IF NOT EXISTS $DBT_SCHEMA AUTHORIZATION $POSTGRES_USER;<br> — CREATE SCHEMA IF NOT EXISTS $DBT_SEED_SCHEMA AUTHORIZATION $POSTGRES_USER;<br> CREATE SCHEMA IF NOT EXISTS $AIRFLOW_SCHEMA AUTHORIZATION $POSTGRES_USER;<br>SET datestyle = &quot;ISO, DMY&quot;;<br>EOSQL</pre><p>You will need to initialize dbt on local machine so that it creates the folders. You will need to create the projects.yml file the run dbt init .</p><pre>iowa:<br>  outputs:<br>    dev:<br>      dataset: iowa_staging<br>      fixed_retries: 1<br>      keyfile: /.google/credentials/google_credentials_iowa.json<br>      location: us-central1<br>      method: service-account<br>      priority: interactive<br>      project: iowa-project-de<br>      threads: 4<br>      timeout_seconds: 300<br>      type: bigquery<br>    prod:<br>      dataset: iowa_prod<br>      fixed_retries: 1<br>      keyfile: /.google/credentials/google_credentials_iowa.json<br>      location: us-central1<br>      method: service-account<br>      priority: interactive<br>      project: iowa-project-de<br>      threads: 4<br>      timeout_seconds: 300<br>      type: bigquery<br>  target: dev</pre><p>With that done, docker is ready to be built.</p><ul><li>docker compose build</li><li>docker-compose up -d</li></ul><h4>Create extract and load dags</h4><p>For the extract and load dags, Make sure that when each task is run multiple times, the results will be the same: <em>idempotent.</em></p><p>With<em> </em>that in mind, create 3 tasks in EL_dag. One to get data from the API and convert the json data to parquet file, then to load the data to my bucket and finally to remove the local file system. Data is uploaded every 2nd day of the month. Therefore scheduled that the data is extracted every 3rd day at 1am. You have to add the catch up option so that the data start from 2012 to this month.</p><p>Add a dag that will create the external table — BQ_dag. This will done only once since you have put all the files under on major folder ad referenced it while creating the table: “sourceUris”:[f”gs://{BUCKET}/raw/iowa_sales/*”]. This means that all files under that folder will be used in creating the table. Do this to avoid calling the task every time a file is loaded.</p><h4>Create dags to execute dbt for data transformation</h4><p>Create a staging view : staging_sales.sql that will transform the date field to datetime and all fields that are related to money to numeric. Also turn all the names to lowercase. Partition the view by months since the reports generated will be by month.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*Nk2jwnJaaJxubUj-CuWu7A.png" /><figcaption>staging_sales.sql</figcaption></figure><p>From the staging view, Create a sales mart that will have incremental tables which will contain vendors, stores and general report. All the tables will be partitioned by sales_date. For vendors and stores, clustere based on vendors and sales respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*gXVutCnjT4nJyLm7g_8hhQ.png" /><figcaption>general_vendor_facts</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*n8XrAhXrWK_ziCNwkiKhSA.png" /><figcaption>general_store_facts</figcaption></figure><p>Then create monthly reports for each store and each vendor. These reports can be used in the planning of inventory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*QDwYsh-ZYXkdp2YByrvy3Q.png" /><figcaption>monthly_vendor_report</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*UwmGFklgLsx-dNjOpytN5A.png" /></figure><p>These models need to be run every month so as to add the new data into the tables. The models will be run individually.</p><p>This is where airflow comes in. The following steps will be followed:</p><ul><li>dbt compile will create a manifest.json that is stored in the target folder. This file contains all the models and there dependencies. This command will be run every time there is a new model created or any changes to the models regarding dependencies</li><li>Loop through the json file and get all the models. This will create the model run as tasks.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*UfNACMRaGCyWmu2Dp98N9g.png" /><figcaption>Get all the models</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*5YPBUz8VZbeIBHYhTzn_Bw.png" /><figcaption>create models as tasks</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*bWDbkLbt3n8jCJqqWrO1Ow.png" /><figcaption>connect the tasks</figcaption></figure><ul><li>Run the models. They will be run the same time as the extract and load dags but at 4am. This will give time for the data to be loaded to the bucket.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*agdQLwr8UfwhubPU11r2Pg.png" /><figcaption>dbt model tasks</figcaption></figure><h4>Deploy to VM</h4><p>Wanted to create a CI/CD pipeline using Google compose and Google build, however they do not support docker-compose. Normal deployment made sense here.</p><p>Save all the work done and push the code to GitHub. Make sure to ignore all the files under .terraform and also the credentials json file</p><p>On the created VM, I installed docker compose:</p><pre>sudo curl -L &quot;<a href="https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname">https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname</a> -s)-$(uname -m)&quot; -o /usr/local/bin/docker-compose</pre><pre>sudo chmod +x /usr/local/bin/docker-compose</pre><pre>docker-compose --version</pre><p>Clone the code from the git on the VM</p><p>Move inside docker folder and run</p><pre>sudo docker-compose up -d</pre><p>Go to http://&lt;publicip&gt;:8000</p><p>Airflow should be running there.</p><h4>Create Reports using Data Studio</h4><p>Add all the tables created for the sales mart and create charts. I created one page that had the summary of the sales done. This is just a simple visualization and there is much information than can be extracted from the data. The report can be found <a href="https://datastudio.google.com/reporting/425ff009-603c-491f-8323-4df51f233478">here</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ecD_1IMPiGXPRn486Sg4aA.png" /></figure><h3>References</h3><ul><li><a href="https://medium.com/@komal1491/installing-airflow-dbt-python-with-docker-52ea5196c7ca">https://medium.com/@komal1491/installing-airflow-dbt-python-with-docker-52ea5196c7ca</a></li><li><a href="https://www.astronomer.io/guides/airflow-dbt/">https://www.astronomer.io/guides/airflow-dbt/</a></li><li><a href="https://docs.getdbt.com/reference/resource-configs/bigquery-configs">https://docs.getdbt.com/reference/resource-configs/bigquery-configs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b16e59d40211" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>