<?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 Abaq Asif on Medium]]></title>
        <description><![CDATA[Stories by Abaq Asif on Medium]]></description>
        <link>https://medium.com/@abaqasif?source=rss-510d9e9122cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8F_2wErwE4dM8f6HVqKKDw.jpeg</url>
            <title>Stories by Abaq Asif on Medium</title>
            <link>https://medium.com/@abaqasif?source=rss-510d9e9122cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:00:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abaqasif/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[Real-time fraud signal pipeline: what I built and what surprised me]]></title>
            <link>https://medium.com/@abaqasif/real-time-fraud-signal-pipeline-what-i-built-and-what-surprised-me-85e09d447f87?source=rss-510d9e9122cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/85e09d447f87</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[great-expectations]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[fraud-detection]]></category>
            <category><![CDATA[aws-glue]]></category>
            <dc:creator><![CDATA[Abaq Asif]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 18:38:06 GMT</pubDate>
            <atom:updated>2026-10-21T18:38:06.542Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why I built it</h3><p>I wanted to see what breaks when a streaming project goes past the tutorial stage, so I built a fraud signal pipeline and owned every layer myself, from event generation to the SQL on top.</p><p>It takes card transaction events, decodes and validates them, lands them in a lakehouse on S3, and lets me query the result with Athena. Kafka, Spark, Postgres, the schema registry and Debezium all run in Docker on my laptop. Only storage, the Glue catalog and Athena live in AWS, which keeps the bill small.</p><p>This post covers what’s running today and the parts that surprised me: a schema registry that let a breaking change through, what that registry actually checks per record, and what change data capture looks like once you watch one event travel. The code is at <a href="https://github.com/abaqasif-aa/fraud-signal-pipeline">github.com/abaqasif-aa/fraud-signal-pipeline</a>.</p><h3>What is actually running</h3><p>Events come from a Python generator, get serialized to Avro, and land in Kafka. Spark reads them, decodes them with the schema from the registry, adds data quality flags, and writes Bronze and Silver Delta tables to S3. Great Expectations checks the Silver table, and a Glue catalog and crawler, provisioned with Terraform, let Athena query it. A Glue job builds a small Gold summary from Silver. On the side, Debezium streams changes from a Postgres table into their own Kafka topics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*ZCfKUw_a9Vn8eI6LrCVHXw.png" /></figure><p>The registry sits next to the stream rather than inside it: the producer registers a schema at startup and Spark fetches it by ID.</p><h3>The registry let a breaking change through</h3><p>I expected the schema registry to stop me from dropping fields, and it didn’t.</p><p>I created a registry called fraud-pipeline in AWS Glue, added a transaction-events schema in Avro with BACKWARD compatibility, and registered a 13-field version. Version 2 added an optional terminal_id field, which is the textbook safe change, and it went through. Then I registered version 3 with most of the fields removed, expecting a rejection. It was accepted.</p><p>Two things were going on. Glue checks a new version against the checkpoint version, not the latest one, and my checkpoint was still version 1. And in Avro terms, BACKWARD means the new schema can read data written with the old one. A reader with fewer fields just skips the extras, so removing fields passes. BACKWARD protects consumers that upgrade ahead of producers. It doesn’t stop a producer from dropping fields that other consumers still need.</p><p>To tighten it up I switched the schema to FULL compatibility, which checks both directions. The CLI won’t change the compatibility mode unless the checkpoint is on the latest version, and it won’t delete the checkpoint version, so I couldn’t simply remove version 3. I registered a clean 14-field version 4 instead and moved the checkpoint there. After that, a version that changed amount from double to string came back with status FAILURE, which is the behavior I wanted from the start.</p><p>On a real team I’d make moving the checkpoint part of the merge process for approved schema changes. Left as a manual step it’s easy to forget, and the registry looks like it’s protecting you when it isn’t.</p><h3>The registry never sees your records</h3><p>I had assumed the registry sat in the path of every message and checked each one. It doesn’t, and that changed how I think about where validation lives.</p><p>When the producer starts, it posts its schema to the registry and gets back an integer ID. Every message after that is Avro binary with a five-byte header: a zero byte, then the schema ID. Kafka just stores bytes. On the Spark side, a UDF reads the ID from the header, fetches the schema the first time it sees that ID, caches it, and decodes the payload with fastavro. After that first fetch there are no registry calls per message.</p><p>The per-record check happens in the serializer. If a producer tries to write a string into the amount field, fastavro raises an error before anything reaches Kafka. What it can’t catch is anything that is structurally valid but wrong for the business: a negative amount, a country code that doesn’t exist, a merchant category outside the contract. Those serialize fine, which is why the pipeline has its own data quality layer.</p><p>In Spark the Kafka value has to stay as raw bytes. Casting it to a string, which is what the JSON version of the job did, would corrupt the Avro payload.</p><p>With the Avro path in place, one run through Spark processed a batch of 77,960 records with a 100% inline data quality pass rate and a 2.0% fraud rate, which matches what the generator is set to produce.</p><h3>Data quality runs at two speeds</h3><p>Avro tells me a field is a double. It doesn’t tell me the double makes sense, so I check business rules in two places.</p><p>The first is inline. Every micro-batch in Spark adds flags to each record: category not in the contract, amount outside $0.01 to $50,000, or a required field missing. They roll up into one column, dq_passed, so downstream queries can filter with a single condition. Each batch also computes rates, such as the share of records missing required fields, and logs a critical message when a rate crosses its threshold. It works like a smoke detector: it tells me quickly that something is wrong, but not what.</p><p>The second is a Great Expectations suite with 15 expectations, run against the Silver table through SparkDFDataset so the checks execute as Spark aggregations instead of pulling data into memory. It catches slower problems that only show up across many records, like a drifting fraud rate or skewed categories. Results go to S3 as JSON and into a Postgres table I can query for trends. I run it by hand for now; scheduling it with Airflow is on my list.</p><p>My generator produces clean data, so the pass rate sits at 100%. That’s expected, and it means I haven’t tested these checks against genuinely messy input yet.</p><h3>CDC was easier to set up than to explain</h3><p>Change data capture means reading the database’s transaction log instead of querying its tables. Debezium tails the Postgres write-ahead log and turns each insert, update and delete into a Kafka event, so the application writing to the database never has to know Kafka exists.</p><p>Setup took three pieces. Postgres had to run with wal_level=logical, because the default level doesn’t carry enough row detail for an outside reader. I added a Debezium Connect container to Docker Compose. And I registered a connector through the Connect REST API, pointed at two tables, fraud_signals and dq_run_log, using the built-in pgoutput plugin. A one-shot container called debezium-init runs the registration script on startup and exits, so a single docker compose up does the whole thing.</p><p>To check it, I inserted a row by hand and read the topic. The event had a before of null, an after with the full row, an op of c for create, and the transaction ID and log position from the source. That log position is what you’d use to resume from a known point.</p><p>One thing tripped me up. The amount column came through as a short base64 string. Postgres NUMERIC values are sent as binary decimals by default, and setting decimal.handling.mode to double in the connector config fixed it.</p><p>What I haven’t done is consume those topics. Right now Debezium writes to Kafka and nothing downstream reads it, and the table I tested with isn’t populated by the pipeline yet. In production the same idea would run on MSK Connect against Aurora PostgreSQL, with logical replication switched on through the Aurora parameter group.</p><h3>What isn’t done yet</h3><p>Three things are next, in this order:</p><ul><li>Exactly-once into Silver. Kafka delivers at least once, so a crash and replay can write the same event twice. The plan is to keep the streaming job append-only into Bronze, where speed matters, and run a scheduled batch job that deduplicates on event_id and merges into Silver, where correctness matters. I’ve written that job but haven’t run it, so I won’t claim it works yet.</li><li>Reading the CDC topics in Spark, so changes in Postgres actually flow through the pipeline.</li><li>Stateful streaming for velocity checks, like several transactions from one user in a few minutes. That’s a pattern you can’t see in any single event.</li></ul><p>After those: lineage with OpenLineage, Airflow scheduling, and model scoring into a Gold layer.</p><p>The whole project is at <a href="https://github.com/abaqasif-aa/fraud-signal-pipeline">github.com/abaqasif-aa/fraud-signal-pipeline</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85e09d447f87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Semantic Search Alone Gets RAG Wrong — and What I Built Instead]]></title>
            <link>https://medium.com/@abaqasif/why-semantic-search-alone-gets-rag-wrong-and-what-i-built-instead-3cf3320890a5?source=rss-510d9e9122cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cf3320890a5</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Abaq Asif]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 21:39:08 GMT</pubDate>
            <atom:updated>2026-06-24T21:39:08.234Z</atom:updated>
            <content:encoded><![CDATA[<h4>Notes from building a hybrid RAG system on World Bank economic data</h4><p>Ask a RAG system built on pure semantic search a question like <em>“which countries had inflation above 10% in 2022?”</em> and it will confidently give you an answer. The answer will also, quite often, be wrong — not hallucinated, not made up, but wrong in a specific and easy-to-miss way: some of the countries it returns won’t actually meet the threshold, some that do meet it will be missing, and the years will drift.</p><p>I ran into this directly while building an open-source economic intelligence platform on World Bank data — 148 countries, 2000 to 2023, with a chat interface for asking natural language questions about GDP, inflation, unemployment, and trade. The first version used Qdrant for semantic search over embedded country-year records, feeding the top matches to a local LLM as context. It worked beautifully for open-ended questions. It quietly failed on precise ones.</p><p>Here’s why, and what fixed it.</p><h3>The failure mode, concretely</h3><p>Semantic search finds records whose <em>meaning</em> is close to your query’s meaning, measured as vector similarity. For a question like <em>“explain Lebanon’s economic situation,”</em> that’s exactly right — there’s no precise answer to retrieve, just relevant context to synthesize from.</p><p>But for <em>“which countries had inflation above 10% in 2022,”</em> the question isn’t really asking for similar records. It’s asking for an exact filter: inflation_rate &gt; 10 AND year = 2022. When I ran this through pure semantic search, the top-10 results included records like Belarus in 2000 and Congo in 2000 — both genuinely high-inflation, semantically very &quot;close&quot; to the query — sitting alongside the actually-correct 2022 records. The LLM, given that mixed context, sometimes reported the wrong years, sometimes missed the threshold, and had no way of knowing it was wrong, because nothing in the retrieval told it the constraint had been violated.</p><p>This isn’t a tuning problem. No amount of embedding model upgrades or prompt engineering closes this gap, because the underlying retrieval mechanism — nearest neighbor in vector space — has no concept of a hard filter. It optimizes for similarity, not correctness against constraints.</p><h3>The fix: classify before you retrieve</h3><p>The architecture I landed on routes every question before doing any retrieval at all:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*rHvKq6HsS5YdS7JHzAokag.png" /></figure><p><strong>SQL route.</strong> A separate LLM call extracts structured filters from the question — year, country, region, indicator, operator, threshold — as JSON, not raw SQL. The actual query is built in Python from those parameters using parameterized queries, with the columns and operators checked against an allowlist before they ever touch a query string. The model decides <em>what</em> to filter on; the code decides <em>how</em> to query, safely. <em>“Which countries had inflation above 10% in 2022?”</em> becomes {&quot;year&quot;: 2022, &quot;indicator&quot;: &quot;inflation_rate&quot;, &quot;operator&quot;: &quot;&gt;&quot;, &quot;threshold&quot;: 10}, which becomes one parameterized WHERE clause against PostgreSQL. No ambiguity, no drift.</p><p><strong>Semantic route.</strong> Open-ended questions go straight to Qdrant. <em>“Explain the economic situation in Lebanon”</em> retrieves the most semantically relevant country-year records and lets the LLM synthesize a narrative — there’s no filter to get wrong here, so similarity search is exactly the right tool.</p><p><strong>Hybrid route.</strong> Some questions are genuinely both — <em>“which countries had the highest inflation in 2022, and why?”</em> needs the precise SQL result for the “which” and semantic context for the “why.” Both queries run, and their results are combined into one context block before a single generation call.</p><p><strong>A fourth route, almost an afterthought, turned out to matter a lot:</strong> OUT_OF_RANGE. The dataset only covers 2000–2023. Early on, a question about 2025 inflation would get silently routed to semantic search, which would happily return <em>something</em> — the nearest available years — without ever telling the user the data didn’t exist. Now the classifier checks the requested year range against the dataset’s actual bounds before any retrieval happens, and returns an honest “no data” response instead of a plausible-sounding wrong one. The fix was three lines of prompt context. The bug it prevented — confidently answering a question with data that doesn’t exist — is exactly the kind of failure that erodes trust in a RAG system fastest.</p><h3>Conversation memory as a layer, not a rewrite</h3><p>Once the routing was solid, the obvious next question was: can you ask a follow-up? <em>“Explain Ghana’s economic situation”</em> then <em>“what about in 2006 specifically?”</em> — without repeating “Ghana.”</p><p>The naive approach would be threading conversation history through the classifier, the filter extractor, and the generation prompt — three places, three chances to get context handling subtly wrong in each one differently. Instead, I added a single step <em>before</em> classification: an LLM call that takes the conversation history and rewrites the latest question into a fully self-contained one.</p><pre>History: &quot;Explain the economic situation of Ghana&quot; → [answer]<br>Follow-up: &quot;What about in 2006 specifically?&quot;<br>              ↓ rewritten<br>&quot;What was the specific economic development that occurred in Ghana in 2006?&quot;</pre><p>That resolved question then flows through the exact same SQL/SEMANTIC/HYBRID/OUT_OF_RANGE pipeline as before, completely unaware that conversation memory exists. The routing logic didn’t change at all — it’s the same code whether the question came in fresh or got rewritten from a follow-up. History itself lives in Redis, keyed by session, storing the <em>resolved</em> questions rather than the raw ones — each turn becomes a clean, self-contained record, which makes resolving the <em>next</em> follow-up easier rather than compounding ambiguity across turns.</p><p>The whole feature is maybe 80 lines of code, and none of it touches the retrieval or generation logic that took much longer to get right.</p><h3>What this actually looks like</h3><p>Two real queries against the running system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzCK5XAlFUerLccnhH2fhg.png" /></figure><p>Notice the answer format itself adapts — a single result gets a plain sentence, twenty results get a numbered list. That’s a small prompt detail (the generation prompt checks the row count and switches instruction accordingly), but it’s the difference between an answer that reads naturally and one that reads like raw database output pasted into a chat window — which is, unglamorously, where a lot of the actual engineering effort in RAG systems goes once retrieval is solid.</p><h3>The honest limitation</h3><p>Routing isn’t free — the SQL and hybrid paths add an extra LLM call before retrieval even starts, which on local hardware (this runs entirely on a consumer GPU, LLaMA 3.1 8B via Ollama, zero API cost) adds a few seconds of latency per question. For a chat interface where users expect sub-second responses, that’s a real cost. It’s the right trade for correctness on a system where wrong answers are worse than slow ones — but it’s not free, and pretending otherwise would undersell what the architecture is actually trading off.</p><p>The deeper limitation: this only works because the question types are cleanly separable into “needs a filter” versus “needs synthesis.” Plenty of real-world RAG use cases don’t decompose that cleanly, and the classifier itself is a model making a judgment call that can be wrong. Worth treating as a strong default, not a universal solution.</p><h3>What’s next</h3><p>The data and retrieval layers are done — dbt medallion architecture with 36 passing data quality tests, Airflow orchestrating the full pipeline daily, Qdrant holding embeddings for 3,500+ country-year records.</p><p>Next: regression and clustering analytics tracked in MLflow, and dashboards in Superset, so the same data that powers the chat interface also powers a more traditional BI layer.</p><p>The project is open source — repo link below if you want to see the routing logic, the dbt models, or run it yourself.</p><p><a href="https://github.com/abaqasif-aa/worldbank-platform">https://github.com/abaqasif-aa/worldbank-platform</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cf3320890a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing for “Future Me”: Docker Compose and AWS]]></title>
            <link>https://medium.com/@abaqasif/designing-for-future-me-docker-compose-and-aws-9a74b111dd67?source=rss-510d9e9122cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a74b111dd67</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Abaq Asif]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 18:32:02 GMT</pubDate>
            <atom:updated>2026-06-13T18:32:02.610Z</atom:updated>
            <content:encoded><![CDATA[<h4>Reproducibility, Docker patterns, and where AWS fits</h4><p>Last time I wrote about the dbt transformation layer — bronze/silver/gold, 36 tests, lineage docs. That layer runs as one piece of a larger Docker Compose setup. This post is about that setup: why it’s built the way it is, and what each piece would look like on AWS.</p><p>This project doesn’t get built in long focused stretches. It’s an hour here, a couple of hours there, sometimes a few days between sessions. That constraint shaped the infrastructure more than almost any other decision — the question I kept coming back to wasn’t “what’s the most impressive setup” but “what does it take for me to sit down after four days away and be productive in five minutes instead of thirty.”</p><p>The answer turned out to be: a docker-compose file that does most of the thinking for you, a couple of small scripts, and a clear mental model of which pieces are <em>services</em> (always running) versus <em>tasks</em> (run once, do a thing, exit).</p><p>Here’s the stack as it stands:</p><pre>postgres   — structured data storage<br>redis      — fast key-value cache<br>qdrant     — vector storage (for RAG, coming later)<br>mlflow     — ML experiment tracking<br>airflow    — pipeline orchestration<br>superset   — dashboards<br>jupyter    — notebooks<br>api        — FastAPI service (ingestion trigger + RAG endpoint)<br>ingestion  — one-off: pull World Bank API, load to postgres<br>dbt        — one-off: transform, test, document</pre><p>Eight long-running services, two “run it and it exits” tasks. That distinction turned out to matter more than I expected.</p><h3>Services vs. tasks: not everything needs to be “up”</h3><p>Postgres, Redis, Airflow — these need to exist continuously. Other things in the stack don’t run on a schedule, run, do their job, and stop. Ingestion fetches from the World Bank API and writes to Postgres. dbt transforms and tests. Neither needs to be “running” between invocations.</p><p>Docker Compose has a clean primitive for this: <strong>profiles</strong>.</p><pre>ingestion:<br>  build: ./services/ingestion<br>  profiles: [&quot;tasks&quot;]<br>  depends_on:<br>    postgres:<br>      condition: service_healthy<br><br>dbt:<br>  build: ./services/dbt<br>  profiles: [&quot;tasks&quot;]<br>  depends_on:<br>    postgres:<br>      condition: service_healthy</pre><p>docker compose up -d starts everything <em>without</em> a profile — the eight always-on services. docker compose --profile tasks run --rm ingestion builds, runs, and removes the ingestion container, on demand. Nothing about ingestion or dbt sits idle consuming resources between runs, and nothing about the always-on services needs to know these tasks exist.</p><p>This is a small thing, but it’s the kind of small thing that, multiplied across a project, is the difference between “docker compose up and walk away” and “docker compose up, then remember which five containers you don’t actually need today and stop them manually.”</p><h3>“Started” isn’t “ready” — and that gap will get you</h3><p>The most common failure mode when wiring up multi-container setups: container A starts, container B starts a second later, B tries to connect to A, A hasn’t finished initializing yet, B crashes (or worse, silently retries forever).</p><p>Docker Compose’s depends_on with condition: service_healthy handles most of this — but it requires the upstream service to define a healthcheck in the first place, and not everything reports its own readiness usefully out of the box.</p><p>For Postgres specifically, I added an explicit wait loop in the startup script rather than relying purely on Compose’s healthcheck timing:</p><pre>echo &quot;Waiting for postgres to be healthy...&quot;<br>until docker compose exec postgres pg_isready -U de &gt; /dev/null 2&gt;&amp;1; do<br>    sleep 2<br>done<br>echo &quot;Postgres is ready.&quot;</pre><p>pg_isready is Postgres&#39;s own &quot;can I accept connections yet&quot; check. The loop is unglamorous — just polling every two seconds — but it means the startup script <em>guarantees</em> Postgres is actually ready before the next batch of services starts, rather than hoping Compose&#39;s dependency graph and healthcheck intervals line up.</p><p>The general principle: anywhere one component depends on another at startup, “the container is running” and “the thing inside the container is ready to do work” are different facts, and conflating them is one of the most common sources of flaky multi-service setups — in Docker, in Kubernetes, anywhere.</p><h3>ENTRYPOINT vs CMD: locking a container to one job, flexibly</h3><p>The dbt container is built once but used many different ways — dbt run, dbt test, dbt seed, dbt snapshot, dbt docs generate. I wanted a container that&#39;s <em>only</em> ever a dbt invocation — never accidentally used to run an arbitrary shell command — but flexible about <em>which</em> dbt command.</p><pre>ENTRYPOINT [&quot;dbt&quot;]<br>CMD [&quot;--help&quot;]</pre><p>ENTRYPOINT fixes the executable — every invocation of this container runs dbt, full stop. CMD is the default argument if none is supplied, and it&#39;s the part that&#39;s freely overridable:</p><pre>docker compose run --rm dbt run --select stg_indicators<br>docker compose run --rm dbt test<br>docker compose run --rm dbt docs generate</pre><p>Each of these becomes dbt run --select stg_indicators, dbt test, dbt docs generate inside the container. The container can never become &quot;run an arbitrary script&quot; — it&#39;s locked to being a dbt runner — but it&#39;s not locked to a single dbt command either. Small pattern, but it&#39;s the right level of constraint: restrictive about <em>what kind of thing</em> this container is for, flexible about the specific operation.</p><h3>Open source stack → AWS equivalents</h3><p>A natural question, especially since I’m also working through AWS material in parallel: if this were built on AWS instead of self-hosted open source, what would map to what? Mostly this is useful as a sanity check — if I can’t map a piece of my stack to <em>something</em> in a cloud platform, it usually means I’ve reinvented a wheel that a managed service would’ve handled, for worse, not better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3__7Kjld1SxVDO0W7Jv0jw.png" /></figure><p>A few things stand out from doing this mapping honestly rather than glossing over it:</p><p><strong>The “task vs service” distinction matters just as much on AWS, if not more</strong> — because on AWS, an always-on service you don’t need is a bill, not just idle RAM. The profile-based separation I did almost for tidiness in Docker Compose becomes a cost-driven architectural decision on AWS (Lambda/Fargate/Glue jobs for ingestion and dbt, not an always-on EC2 instance running a cron job).</p><p><strong>Qdrant doesn’t have a single AWS equivalent — but not for the reason I’d have guessed.</strong> AWS’s vector search options have actually converged a lot: OpenSearch has a vector engine, Aurora PostgreSQL supports pgvector, and Bedrock Knowledge Bases now picks from six different vector store backends depending on what you tell it to use. So it’s not that AWS is behind here.</p><p>The actual difference is in the <em>shape</em> of the offering. AWS’s pattern is consistently “add vector search to a database or search engine you already have” — pgvector bolted onto Postgres, a vector engine bolted onto OpenSearch. Qdrant is the opposite: a database built from the ground up <em>as</em> a vector store, with everything else (filtering, payloads, collections) designed around that. There’s no AWS service that’s “a dedicated vector database as a managed product” the way Qdrant is — the closest you get is Bedrock KB choosing one of the bolted-on options for you. Whether that’s a meaningful difference depends on whether you’re starting from “I need vector search added to my existing stack” or “vector search is the primary thing this component does” — and for a RAG-focused project, it’s the latter.</p><p><strong>Docker Compose’s closest AWS equivalent is closer than I initially gave it credit for.</strong> CloudFormation + SAM is genuinely the same idea — declarative, file-based, and sam local gives you the same &quot;run the whole stack on one machine&quot; workflow as docker compose up. Terraform is the tool more people actually reach for in practice, for similar reasons (declarative, file-based, multi-cloud). CDK is the odd one out here — it&#39;s code that <em>generates</em> CloudFormation, which is a different authoring experience even if the end result is the same kind of declarative stack.</p><h3>The actual point</h3><p>None of this is sophisticated. A healthcheck wait loop, two lines of Dockerfile, a profiles key in a YAML file. But the test I kept applying was: <em>if I disappear for a week, does </em><em>git pull &amp;&amp; ./start.sh get me back to exactly where I left off, with no &quot;oh right, I need to remember to also run X first&quot;?</em></p><p>So far, yes. Which means the next session starts with actual work instead of re-deriving the setup from memory — and that compounds a lot more than any individual piece of config does.</p><p>With the dbt layer and the infrastructure both in place, next up is Redis for fast country metadata lookups, an Airflow DAG to tie ingestion → dbt → (eventually) embeddings together end to end, and a RAG layer so the platform can answer natural-language questions like <em>“which countries had inflation above 10% and positive GDP growth in 2022?”</em> directly.</p><p>Repo’s open source and in progress — link below.<br><a href="https://github.com/abaqasif-aa/worldbank-platform">https://github.com/abaqasif-aa/worldbank-platform</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a74b111dd67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Picking Up dbt: What Transfers, What Doesn’t, and a Country That Broke My Test Bounds]]></title>
            <link>https://medium.com/@abaqasif/picking-up-dbt-what-transfers-what-doesnt-and-a-country-that-broke-my-test-bounds-bb7f18ba0534?source=rss-510d9e9122cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb7f18ba0534</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Abaq Asif]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 18:04:48 GMT</pubDate>
            <atom:updated>2026-06-12T18:04:48.391Z</atom:updated>
            <content:encoded><![CDATA[<h4>Notes from building an open-source economic data platform on World Bank data</h4><p>I’ve worked with data pipelines for a while — mostly hand-rolled ETL, some Spark, a fair amount of “write the SQL, schedule the SQL, hope the SQL still works next quarter.” dbt was the one tool in that world I’d read about constantly but never actually used — it just wasn’t part of the stack at any company I’d worked with.</p><p>So: side project. Open-source economic data platform on World Bank indicators — GDP, inflation, unemployment, trade, population, 200+ countries, 2000–2023. Docker-based, dbt for transformations, eventually a RAG layer on top. This week was the dbt build: raw API data into a medallion architecture (bronze/silver/gold), 36 automated tests, lineage docs, SCD2 snapshots.</p><p>A lot of this felt familiar — the medallion layering, the idea of staging vs. final tables, data quality checks. What was new was dbt’s specific opinions about how those familiar ideas should be wired together. Three things stood out, and two of them aren’t really about dbt at all — they’re things I already knew, that dbt just gave me a fresh reason to think about properly.</p><p>Here’s the lineage graph dbt generated for the finished pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*0g0Ou-zS_MPjooILOAgFNQ.png" /></figure><h3>1. dbt’s schema naming convention is its own opinion — and it’s a reasonable one, once you know it exists</h3><p>I set staging and marts as schema names in dbt_project.yml, ran dbt run, queried staging.stg_indicators — relation doesn&#39;t exist. The table was sitting in marts_staging.</p><p>This is dbt’s default: custom schemas get prefixed with your profile’s target schema (&lt;target&gt;_&lt;custom&gt;). The reasoning is sane for teams — every developer gets their own target schema (e.g. dbt_jsmith), and prefixing keeps everyone&#39;s staging/marts tables from colliding in a shared dev database.</p><p>For a solo project, it’s just confusing. The fix is the well-documented generate_schema_name override:</p><pre>{% macro generate_schema_name(custom_schema_name, node) -%}<br>    {%- set default_schema = target.schema -%}<br>    {%- if custom_schema_name is none -%}<br>        {{ default_schema }}<br>    {%- else -%}<br>        {{ custom_schema_name | trim }}<br>    {%- endif -%}<br>{%- endmacro %}</pre><p>This is the part that’s genuinely dbt-specific — in a hand-rolled pipeline, <em>you</em> decide what schemas things land in, full stop. dbt has opinions baked in that you only discover by hitting them. Not a complaint — once I understood the “why” (multi-developer collision avoidance), the default made sense, and overriding it for a single-developer setup is one line. But it’s a good example of the kind of thing that’s invisible in the docs’ quickstart and only shows up the first time you go looking for a table that isn’t where you put it.</p><h3>2. NULL vs. FALSE — old problem, dbt just put it back in front of me</h3><p>This one isn’t new. I’ve hit it in Python feature pipelines, in API responses, in reporting layers — anywhere a flag gets derived from columns that can be missing.</p><p>The setup: derived column crisis_flag — 1 if inflation &gt; 10% and unemployment &gt; 8% in the same country-year. World Bank data has real gaps, especially for lower-income countries in earlier years. First pass:</p><pre>case<br>    when inflation_rate &gt; 10 and unemployment_rate &gt; 8 then 1<br>    else 0<br>end as crisis_flag</pre><p>In SQL, NULL &gt; 10 is NULL, NULL AND x is NULL, and a NULL condition falls through to ELSE. So a country-year with <em>no data at all</em> gets crisis_flag = 0 — same value as a country-year we&#39;ve actually checked and confirmed wasn&#39;t in crisis. &quot;We checked, and no&quot; and &quot;we have no idea&quot; become indistinguishable. That&#39;s a problem if this column ever becomes a feature for a model — it&#39;d be learning from silently mislabeled rows.</p><pre>case<br>    when inflation_rate is null or unemployment_rate is null then null<br>    when inflation_rate &gt; 10 and unemployment_rate &gt; 8 then 1<br>    else 0<br>end as crisis_flag</pre><p>Three states instead of two. Nothing about this is dbt — it’s just that writing transformation logic in a new tool, on a new dataset, is exactly the situation where old habits get skipped because you’re focused on the new syntax. Worth treating “is this column ever null, and does that mean something different from false” as a checklist item regardless of what’s generating the SQL.</p><h3>3. A failing test is a hypothesis, not a verdict — also not new, also worth re-learning</h3><p>Test on gdp_growth_rate (YoY GDP change via LAG(), partitioned by country, ordered by year): bounded -75% to +150%, on the assumption that real economies don&#39;t move further than that in a year.</p><p>One failure: Sierra Leone, 2001, +164.4%.</p><p>I’ve been burned before by assuming a failing test means broken code — and burned the other way too, by assuming “the data’s just weird” and missing an actual bug. So: checked the window function, checked the join, checked for unit mismatches. The number held up:</p><ul><li>2000: GDP ≈ $636M</li><li>2001: GDP ≈ $1.68B</li></ul><p>Sierra Leone’s civil war was ending through 2001 (formally declared over January 2002). 2000 is a near-collapsed wartime economy; 2001 is the start of recovery — low base, real rebound. Following years moderate as expected (15.0%, 10.8%). Real event, correctly reflected in the data.</p><p>Widened the bound to 200%, documented why in the test:</p><pre>- name: gdp_growth_rate<br>  description: &gt;<br>    Upper bound of 200% accommodates legitimate post-conflict recovery<br>    spikes (e.g. Sierra Leone 2001 at 164% following the end of its<br>    civil war).</pre><p>The dbt-specific part here is just that dbt_expectations makes writing these range tests trivial — a couple of YAML lines and you get the check. The judgment call underneath — investigate before you decide whether to trust the test or the data, and write down your reasoning either way — is the same regardless of whether the check is a dbt test, a Great Expectations suite, or an assertion in a Python script.</p><h3>What’s next</h3><p>dbt layer done — bronze/silver/gold, 36 tests passing, lineage docs, SCD2 snapshots tracking how the analytical table changes as World Bank revises historical figures.</p><p>This all runs as one piece of a larger Docker Compose setup — more on that, and what’s next for the platform, in the next post.</p><p>Repo’s open source and in progress — link below.</p><p><a href="https://github.com/abaqasif-aa/worldbank-platform">https://github.com/abaqasif-aa/worldbank-platform</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb7f18ba0534" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark, dbt and Airflow — A Practical Walkthrough]]></title>
            <link>https://medium.com/@abaqasif/spark-dbt-and-airflow-a-practical-walkthrough-5ef932a352ee?source=rss-510d9e9122cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ef932a352ee</guid>
            <category><![CDATA[pipeline-orchestration]]></category>
            <category><![CDATA[data-architecture]]></category>
            <category><![CDATA[apache-airflow]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Abaq Asif]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 19:00:00 GMT</pubDate>
            <atom:updated>2026-06-07T19:01:11.015Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a medallion architecture pipeline from scratch</h4><h3>Part 4: Orchestration with Apache Airflow</h3><p>I have seen pipelines run on cron jobs with no alerting, no retries, and no visibility. You only find out something broke when an analyst emails you asking why the numbers look wrong. Airflow exists to make sure that never happens.</p><h3>What is Apache Airflow</h3><p>Apache Airflow is a workflow orchestration platform that lets you define, schedule, and monitor data pipelines as code. Rather than running scripts manually or relying on cron jobs, Airflow gives you a full picture of your pipeline — what ran, when it ran, whether it succeeded, and what to do when it fails.</p><p>The key difference between Airflow and a cron job is not scheduling — cron can schedule. The difference is dependency management, failure handling, observability, and retries. A cron job fires and forgets. Airflow tracks every run, every task, every failure, and gives you a UI to see exactly what happened.</p><h3>The DAG</h3><p>The entire pipeline is orchestrated by a single DAG that runs on a daily schedule and chains four tasks in sequence:</p><pre>spark_bronze → spark_silver → dbt_run → dbt_test</pre><p>Each task has a hard dependency on the one before it. If Bronze fails, Silver never runs. If dbt_run fails, dbt_test never runs. This is the most important thing Airflow gives you over a cron job — task dependency management with a clear failure point. You always know exactly where the pipeline broke and nothing downstream runs on bad data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LRJMP4bmXFVHnMWEok_PYA.png" /></figure><h3>Operator choices</h3><p>Both the Spark jobs and dbt are triggered using BashOperator, which runs a shell command on the same machine. This is the pragmatic choice for a local setup — simple, transparent, and easy to debug.</p><p>SparkSubmitOperator is the right tool when Spark is running as a proper cluster on YARN or Kubernetes. DbtCloudRunJobOperator only applies if you are using dbt Cloud as a managed service. Operator choice should follow the environment, not convention — using SparkSubmitOperator locally just to look sophisticated is over-engineering.</p><p>In production the operator choices would change:</p><ul><li><strong>Spark on Kubernetes</strong> → SparkKubernetesOperator</li><li><strong>Spark on YARN</strong> → SparkSubmitOperator</li><li><strong>dbt Core</strong> → BashOperator with dbt run</li><li><strong>dbt Cloud</strong> → DbtCloudRunJobOperator</li></ul><h3>Reliability configuration</h3><p><strong>Retries and retry delay</strong> The DAG is configured with retries=2 and a 5-minute retry delay. Transient failures — a database connection timing out, a file not yet available — are common in real pipelines and a flat failure on the first attempt is too aggressive. Two retries with a delay gives the system a chance to recover without piling up failed runs.</p><p><strong>catchup=False</strong> Often overlooked but important. Without it, Airflow will backfill every missed DAG run from the start date to today on first deployment — potentially triggering hundreds of runs at once. Turning it off means the DAG starts from the next scheduled interval and moves forward cleanly.</p><p><strong>Email alerting on failure</strong> A pipeline that fails silently is worse than one that does not run at all. Email alerting on failure closes the loop — the right person knows immediately, not when an analyst notices the numbers are wrong two days later.</p><h3>Production features worth knowing</h3><h3>Variables and Connections</h3><p>Hardcoding database URLs, file paths, and credentials in DAG files is a red flag in production. Airflow Variables store configuration outside the DAG code and Connections store credentials securely in the Airflow metadata database. Any value that could change between environments — dev, staging, production — belongs in a Variable or Connection, not in the DAG itself. This is one of the first things I look for when reviewing a DAG.</p><p>In this project the PostgreSQL connection and file paths are candidates for Variables — a small change that makes the DAG environment-agnostic and significantly easier to promote from local to production.</p><h3>XComs — passing data between tasks</h3><p>XComs (cross-communications) allow tasks to push and pull small pieces of data between each other. A common production pattern is pushing metadata from a task — row counts, file paths, status flags — and pulling it downstream for validation or logging.</p><p>In this pipeline a practical use would be pushing the row count from the Bronze task and validating it in the Silver task before proceeding. If Bronze writes zero rows, Silver should not run — a hard dependency alone does not catch that. XComs make the pipeline data-aware, not just sequence-aware.</p><pre># Push row count from Bronze task<br>context[&#39;ti&#39;].xcom_push(key=&#39;bronze_row_count&#39;, value=row_count)<br><br># Pull in Silver task before proceeding<br>bronze_count = context[&#39;ti&#39;].xcom_pull(task_ids=&#39;spark_bronze&#39;, key=&#39;bronze_row_count&#39;)<br>if bronze_count == 0:<br>    raise ValueError(&quot;Bronze layer wrote zero rows — aborting Silver&quot;)</pre><h3>Trigger rules</h3><p>By default every task uses trigger_rule=&#39;all_success&#39; — it only runs if all upstream tasks succeeded. This is the right choice for this pipeline. But in production you often need more nuance:</p><ul><li>all_done — run regardless of upstream success or failure. Useful for cleanup tasks that should always run.</li><li>one_failed — trigger an alerting or rollback task if any upstream task fails.</li><li>none_failed_or_skipped — useful in branching pipelines where some tasks are conditionally skipped.</li></ul><p>Understanding trigger rules is what took my DAGs from linear sequences to genuinely resilient pipelines.</p><h3>Sensors</h3><p>Sensors wait for a condition before proceeding rather than assuming data is ready at a fixed time. In this pipeline the Bronze task assumes the CSV files are in the raw data folder — a FileSensor would wait and confirm before triggering ingestion. I would never hardcode a time assumption about when data arrives in production.</p><pre>wait_for_raw_data = FileSensor(<br>    task_id=&#39;wait_for_raw_data&#39;,<br>    filepath=&#39;/path/to/raw_data/&#39;,<br>    poke_interval=300,  # check every 5 minutes<br>    timeout=3600,       # fail after 1 hour<br>    dag=dag<br>)</pre><p>Key parameters: poke_interval controls how often the sensor checks, timeout controls when it gives up and fails. Getting these wrong — too aggressive a poke interval, too short a timeout — is something I have seen cause problems in production more than once.</p><h3>Pools</h3><p>Pools limit concurrent task execution across DAGs. I have worked in environments where multiple DAGs hit the same database simultaneously — without pools they can overwhelm it. A pool defines a slot limit and tasks assigned to that pool compete for slots. This gives you resource-level concurrency control, not just DAG-level.</p><p>In this project a postgres_pool with a defined slot limit would prevent the Silver Spark job and dbt from hitting PostgreSQL simultaneously during periods of overlap.</p><h3>SLA misses and callbacks</h3><p>sla on a task defines the maximum acceptable runtime. If exceeded, Airflow fires an SLA miss callback — separate from failure alerting. In my experience this is what catches performance degradation before it becomes a failure. If the Bronze job normally takes 10 minutes and suddenly takes 45, you want to know before it cascades.</p><p>on_failure_callback and on_success_callback give fine-grained control over alerting — beyond email, you can trigger Slack notifications, PagerDuty alerts, or custom logging on any task state change.</p><h3>Backfilling</h3><p>airflow dags backfill lets you rerun a DAG for historical dates. Combined with catchup=True on specific DAGs, this is how you handle late-arriving data or reprocess after a bug fix. The distinction between backfill, rerun, and clearing tasks is subtle but important — clearing a task reruns it within an existing DAG run, backfill creates new DAG runs for historical intervals.</p><h3>Airflow vs cron — when does Airflow make sense?</h3><p>Cron is not wrong — it is the right tool for simple, single-task schedules with no dependencies. Airflow earns its complexity when:</p><ul><li>Tasks have dependencies on each other</li><li>You need retries and failure handling</li><li>You need visibility into what ran and when</li><li>You have multiple pipelines monitored in one place</li><li>You need to backfill historical data</li><li>You need resource-level concurrency control across DAGs</li></ul><p>For a pipeline with four dependent tasks, email alerting, and a daily schedule — Airflow is the right call.</p><h3>What I’d do differently</h3><ul><li><strong>Add sensors</strong> — replace the time-based trigger assumption with FileSensor to confirm raw data is present before Bronze runs.</li><li><strong>Implement XComs for row count validation</strong> — push row counts from Bronze and Silver, validate before proceeding. Makes the pipeline data-aware not just sequence-aware.</li><li><strong>Use Variables and Connections</strong> — move all hardcoded paths and credentials out of the DAG into Airflow Variables and Connections.</li><li><strong>Define pools</strong> — prevent concurrent database access from multiple tasks overwhelming PostgreSQL.</li><li><strong>Add SLA definitions</strong> — set expected runtimes per task and alert on degradation before it becomes a failure.</li><li><strong>Containerise Airflow</strong> — run Airflow, Spark, and PostgreSQL each in their own Docker container with docker-compose. Reproducible in minutes, no dependency conflicts.</li><li><strong>Separate DAGs per layer</strong> — split ingestion and transformation into independent DAGs. Easier to rerun, debug, and schedule independently as the pipeline grows.</li><li><strong>Add task groups</strong> — group Spark tasks and dbt tasks visually in the DAG UI. Keeps the graph readable as complexity grows.</li></ul><h3>Wrapping up the series</h3><p>This is the fourth and final part of the series. Across the four articles we covered:</p><ul><li><a href="https://medium.com/@abaqasif/medallion-architecture-from-scratch-a-practical-walkthrough-with-spark-dbt-and-airflow-part-1-ab40b3d47df6"><strong>Part 1</strong> — the dataset, the design decisions, and the medallion architecture</a></li><li><a href="https://medium.com/@abaqasif/spark-dbt-and-airflow-a-practical-walkthrough-c053d15b20e6"><strong>Part 2</strong> — Spark, how it executes, and the ingestion and transformation layers</a></li><li><a href="https://medium.com/@abaqasif/spark-dbt-and-airflow-a-practical-walkthrough-5413599cecf8"><strong>Part 3</strong> — dbt, how it models data, and the production thinking behind testing and lineage</a></li><li><a href="https://medium.com/@abaqasif/spark-dbt-and-airflow-a-practical-walkthrough-5ef932a352ee"><strong>Part 4</strong> — Airflow, how it orchestrates the pipeline, and what reliability looks like in practice</a></li></ul><p>The goal was never to build the most impressive pipeline — it was to build one that reflects how things are actually done at work, and to share the thinking behind every decision. I hope it was useful.</p><p>The full project is available on <a href="https://github.com/abaqasif-aa/olist_data_pipeline_end">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ef932a352ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark, dbt and Airflow — A Practical Walkthrough]]></title>
            <link>https://medium.com/@abaqasif/spark-dbt-and-airflow-a-practical-walkthrough-5413599cecf8?source=rss-510d9e9122cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/5413599cecf8</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-architecture]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Abaq Asif]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 14:36:41 GMT</pubDate>
            <atom:updated>2026-06-07T19:02:03.048Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a medallion architecture pipeline from scratch</h4><h3>Part 3: Data Transformation with dbt</h3><p>The first time I used dbt I kept thinking — I have seen this pattern before. It took me a while to place it. It was MVC. The same separation of concerns I used building PHP applications back in the day, reimagined for data pipelines.</p><h3>What is dbt</h3><p>dbt (data build tool) is a transformation framework that lets you write data models in SQL and handles the rest — materialisation, dependency management, testing, and documentation. If you have worked with raw SQL transformation scripts scattered across a codebase, dbt will feel like a long overdue solution.</p><p>It is important to be clear about what dbt is not. dbt is a transformation tool — it does not move data, handle ingestion, or replace orchestration. It picks up where Spark leaves off and hands off to Airflow when it is done. Knowing the boundaries of each tool is what keeps a pipeline maintainable as it grows.</p><h3>The MVC analogy</h3><p>Working with dbt reminded me of the MVC pattern from building applications in PHP. Staging is your Model — data cleaned and renamed. Intermediate is your Controller — the logic layer. Marts are your View — the final output the consumer sees. The pattern is not new, it has just been reimagined for data pipelines.</p><p>That separation matters more than it might seem. In most legacy pipelines I have worked on, business logic was buried in stored procedures, scattered across scripts, and undocumented. dbt puts all of it in one place, versioned, tested, and documented. The next person who touches the pipeline is not guessing — they are reading.</p><h3>Lineage and documentation</h3><p>One thing I genuinely appreciate about dbt is how it treats lineage and documentation as first class citizens. Every model is documented in one place and the lineage graph shows exactly how data flows from source to output. In legacy environments I have worked in, that visibility simply did not exist — you were reverse engineering pipelines from stored procedures and hoping someone left a comment.</p><p>In production, lineage is not a nice-to-have — it is what keeps a team functional when things go wrong. When a source table changes unexpectedly, lineage tells you instantly which downstream models are affected and which consumers will break. Without it you are making phone calls and checking Slack trying to piece together what depends on what — usually at 2am during an incident. With it you open the graph, see the blast radius, and act.</p><p>Documentation compounds this. When a column is renamed, deprecated, or its definition changes, the models that consume it need to know. dbt lets you document every model and column in one place and keeps that documentation version-controlled alongside the code. Relevant consumers — analysts, data scientists, downstream engineers — can see exactly what a field means, where it comes from, and when it last changed. That single source of truth is what prevents silent data quality issues from propagating downstream for weeks before someone notices.</p><p>Downtime is also reduced significantly. When you can trace a failing model back to its source in seconds rather than hours, mean time to resolution drops dramatically. Lineage does not prevent incidents — but it contains them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6715cVAUjZUr9ROKuK8XA.png" /><figcaption>Lineage graph generated by DBT</figcaption></figure><h3>Materialisation choices</h3><p>Each layer is materialised differently and the reasoning matters more than the choice itself:</p><ul><li><strong>Staging — views</strong> — no storage cost, always fresh, lightweight. Not meant to be queried directly — a clean interface over the raw source.</li><li><strong>Intermediate — incremental</strong> — the dataset grows over time and a full reload on every run would be wasteful. Only new or changed data gets processed.</li><li><strong>Marts — tables</strong> — queried frequently by BI tools and need fast, predictable read performance. The heavy lifting happens at build time, not at query time.</li></ul><h3>Incremental strategy</h3><p>The intermediate model is configured as follows:</p><pre>config(<br>    materialized=&#39;incremental&#39;,<br>    unique_key=&#39;order_id&#39;,<br>    incremental_strategy=&#39;delete+insert&#39;,<br>    partition_by=&#39;purchased_at&#39;<br>)</pre><p>The choice of delete+insert over upsert comes down to predictability. An upsert checks each incoming row and either updates or inserts. delete+insert deletes the affected window first, then reinserts the full refreshed set. No ambiguity about whether a row was updated or silently skipped. It is also more portable — merge behaves differently across PostgreSQL, Snowflake, and BigQuery. delete+insert is easier to reason about and easier to debug when something goes wrong.</p><p>Partitioning by purchased_at was deliberate. Partitioning only delivers a benefit when the filter logic aligns with the partition column. The 45-day lookback window filters on purchased_at — PostgreSQL targets only the relevant partitions rather than scanning the entire table. If the partition column and filter column don&#39;t match, you get the overhead with none of the gain — a common mistake worth calling out.</p><h3>Testing</h3><p>dbt supports two types of tests and using both is what separates a well-engineered pipeline from one that just runs.</p><p>Generic schema tests in schema.yml cover the basics — not_null, unique, accepted_values. These catch structural issues.</p><p>The more valuable tests are singular tests that encode actual business logic:</p><ul><li>assert_delivered_orders_have_payment — no delivered order should have zero payment value</li><li>assert_delivery_delay_in_range — delay must fall between -30 and 365 days</li><li>assert_customers_have_spend — every customer must have a positive total spend</li></ul><p>These are not catching schema drift — they are catching real data quality violations that a generic test would never find. Writing them forces you to think about what the data should look like, not just what it does look like.</p><h3>Dev/prod separation</h3><p>All development work writes to a personal schema (dev_abaq) and production runs write to public. No risk of dev work overwriting production data and no need to tear down tables when iterating on a model. A small configuration decision that reflects how serious teams manage dbt in production.</p><h3>A few things worth calling out</h3><p>One limitation worth being explicit about — dbt is SQL dependent and it is not SQL flavour agnostic. Every model you write is tied to the dialect of the database you are running against. Window functions, date formatting, string manipulation, array handling — these all behave differently across PostgreSQL, Snowflake, BigQuery, and Spark SQL. Some functions exist in one dialect and not another. Some share the same name but return different results.</p><p>This makes database migrations less seamless than they appear on paper. If you build a mature dbt project on PostgreSQL and then migrate to Snowflake, you are not just changing a connection string. You are auditing every model for dialect-specific functions, rewriting date logic, testing edge cases, and discovering that something that worked perfectly for two years now silently returns a different result. Macros help — you can abstract dialect-specific logic into a single macro and swap the implementation when you migrate. But they require the discipline to use them consistently from the start, not as a retrofit.</p><p>The lesson from experience is to treat SQL flavour portability as a design decision made early, not a problem solved during migration. In this project I used macros for date extraction — format_date, extract_year, extract_month — which meant any change to date logic needed to be made in exactly one place and would be straightforward to swap out if the database ever changes.</p><h3>What I’d do differently</h3><ul><li><strong>Implement more singular tests</strong> — the three I wrote barely scratch the surface. Every business rule that matters should have a test behind it.</li><li><strong>Add source freshness checks</strong> — dbt lets you define how stale a source table can be before the pipeline fails. I did not implement this but it is essential in production.</li><li><strong>Document every model</strong> — I documented the key models but not all of them. Full documentation is what makes the lineage graph genuinely useful rather than just visually appealing.</li><li><strong>Explore dbt snapshots</strong> — for slowly changing dimensions like customer data, dbt snapshots track historical changes automatically. Worth adding as the Gold layer matures.</li></ul><h3>What’s next</h3><p><a href="https://medium.com/@abaqasif/spark-dbt-and-airflow-a-practical-walkthrough-5ef932a352ee">Part 4</a> wraps up the series with Airflow — how I orchestrated the full pipeline, the operator choices behind each task, and what I would change about the setup in a production environment.</p><p>The full project is available on <a href="https://github.com/abaqasif-aa/olist_data_pipeline_end">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5413599cecf8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark, dbt and Airflow — A Practical Walkthrough]]></title>
            <link>https://medium.com/@abaqasif/spark-dbt-and-airflow-a-practical-walkthrough-c053d15b20e6?source=rss-510d9e9122cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/c053d15b20e6</guid>
            <category><![CDATA[data-architecture]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[medallion-architecture]]></category>
            <dc:creator><![CDATA[Abaq Asif]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 19:10:40 GMT</pubDate>
            <atom:updated>2026-06-05T14:41:53.904Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a medallion architecture pipeline from scratch</h4><h3>Part 2: Data Ingestion with Apache Spark</h3><h3>What is Apache Spark</h3><p>Apache Spark is a distributed data processing engine that splits work across multiple machines and processes it in parallel. Rather than processing data sequentially like a traditional script, Spark breaks a dataset into partitions and processes them simultaneously across a cluster of nodes — making it one of the most widely adopted tools for large-scale data engineering in the industry.</p><p>But the more important thing to understand about Spark is how it thinks about work. Spark is lazy — it does not execute anything until it absolutely has to.</p><p>It is also worth understanding where Spark sits relative to MPP databases like Snowflake, Redshift, and BigQuery, since the two are often confused. MPP databases are purpose-built for SQL analytics — they own the data, distribute it across nodes at storage level, and are optimized for fast query responses. Spark is different — it is not a database and has no storage of its own. It brings compute to wherever the data lives, reads it, processes it in memory across a cluster, and writes results somewhere else. In most modern data stacks the two coexist — Spark transforms and loads the data, MPP serves it to analysts downstream.</p><p>In this project Spark does the heavy lifting and PostgreSQL plays that downstream role for dbt to query against.</p><h3>Lazy evaluation — the foundation of how Spark works</h3><p>When you write a chain of Spark transformations — a filter, a join, a select — Spark does not run them immediately. It builds a DAG (Directed Acyclic Graph) of operations and waits. Only when you trigger an action — a write, a count, a show — does Spark look at the entire plan, optimize it, and execute it.</p><p>This is why Spark can seem slow to start. It is not running your code line by line — it is building an execution plan first. The benefit is that it can optimize the entire pipeline before touching a single row of data.</p><p>That optimization is handled by the Catalyst optimizer — Spark’s built-in query planner. Catalyst rewrites your operations into the most efficient execution order regardless of how you wrote them. Filter pushdown, predicate reordering, constant folding — it handles all of this automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x73GMKKIhyKVfay79W6I6w.png" /></figure><h3>Transformations vs actions</h3><p>Everything in Spark falls into one of two categories:</p><p><strong>Transformations</strong> — lazy operations that build the execution plan: filter, select, withColumn, join, groupBy</p><p><strong>Actions</strong> — operations that trigger execution: write, count, show, collect</p><p>This is one of the most fundamental things to understand about Spark. A chain of twenty transformations costs you nothing until an action fires — at which point Spark executes the entire optimised plan in one go.</p><h3>Wide vs narrow transformations</h3><p>Not all transformations are equal. Spark distinguishes between two types:</p><p><strong>Narrow transformations</strong> — each partition is processed independently with no data movement. filter, select, withColumn are all narrow. Fast, cheap, no network overhead.</p><p><strong>Wide transformations</strong> — data must be shuffled across partitions, often across nodes in a cluster. join, groupBy, distinct are all wide. Expensive — and the primary source of performance bottlenecks in Spark pipelines.</p><p>This is where the concept of stages becomes important. Spark groups transformations into stages — a stage is a sequence of narrow transformations that can run together without any data movement. Every time Spark hits a wide transformation that requires a shuffle, it draws a stage boundary. The data is written to disk at that boundary, shuffled across partitions, and then the next stage begins.</p><p>This matters directly in my Silver layer, which performs 6 joins across 7 tables. Every one of those joins is a wide transformation, each one potentially triggering a shuffle and a new stage boundary. Each stage runs independently and only proceeds once the previous stage has completed and the shuffle has finished. Every unnecessary wide transformation adds a stage boundary, a shuffle, and a write to disk — in a large pipeline those costs compound quickly.</p><h3>How Spark executes — driver, cluster manager, and workers</h3><p>When an action fires, here is what actually happens under the hood:</p><ol><li>Your application triggers an action (df.write(), df.show(), df.count())</li><li>The driver builds the DAG and splits it into stages and tasks</li><li>The cluster manager negotiates resources and launches executors on worker nodes</li><li>Worker nodes run tasks in parallel — wide transformations trigger a shuffle between nodes</li><li>Results are either written to storage (Parquet, PostgreSQL, S3) or returned to the client (df.show(), df.collect())</li></ol><p>In client mode the driver runs on your machine — logs appear in your terminal and the connection must stay open. In cluster mode the driver runs inside the cluster, making it safe to disconnect. This is the production pattern.</p><p>In this project I used local[*] — driver, cluster manager and executors all run as threads on one machine with no network overhead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*APbbXttF9ul5BixwYZqaAg.png" /></figure><h3>Broadcast joins — optimising small table joins</h3><p>One of the most effective optimisations for join-heavy pipelines is the broadcast join. When joining a large table with a small one, rather than shuffling the large table across the network, Spark can broadcast the small table to every executor — each node gets a full copy and the join happens locally with no shuffle at all.</p><p>In my Silver layer, the product_category_name_translation table is tiny — a simple lookup table mapping Portuguese category names to English. This is a perfect broadcast join candidate. In production I would explicitly hint this to Spark:</p><pre>from pyspark.sql.functions import broadcast<br><br>silver_df = orders_df.join(broadcast(product_category_df), &quot;product_category_name&quot;, &quot;left&quot;)</pre><p>A small change, a significant performance improvement at scale — and the kind of detail that signals real Spark experience.</p><h3>My implementation</h3><p>I used PySpark for both the Bronze ingestion and Silver transformation layers. In a real production environment this data would not be sitting in a folder as CSVs — it would be arriving from an event stream, an API, or an S3 bucket at scale. Using Spark here kept the project realistic even if the data volume did not strictly require it.</p><p><strong>Bronze layer</strong> reads each of the 9 CSV files with explicit schemas rather than relying on inference. Schema inference triggers an extra scan of the data before processing — explicit schemas skip that scan and fail fast on type mismatches. Two benefits: performance and data quality.</p><p>This also surfaces a broader production concern: schema evolution. Columns get added, renamed, or dropped over time. The clean solution is Delta Lake or Apache Iceberg, both of which handle schema evolution natively without requiring a full reload. That is a natural next step for this project.</p><p><strong>Silver layer</strong> is where Spark earns its keep. The DataFrame API joins 7 tables, casts timestamps, derives delivery_delay_days, is_late, and total_item_value, then prunes down to only the 20 columns needed downstream. The output lands in two places — Parquet as a durable local copy and PostgreSQL via JDBC for dbt to pick up.</p><p>Column pruning at the Silver stage was deliberate. Rather than carrying all columns from all 7 tables through to Gold, I select only what is needed downstream. In a production environment dragging unnecessary columns through the pipeline wastes storage, increases shuffle size, and slows down every downstream query.</p><h3>Fault tolerance — why Spark is resilient</h3><p>Spark tracks the full lineage of every transformation in the DAG. If a partition fails mid-job, Spark does not restart the entire pipeline. It recomputes only the failed partition by replaying the transformations from the last stable point. This is the foundation of Spark’s fault tolerance model and one of the reasons it is trusted for mission-critical production workloads.</p><h3>What I’d do differently</h3><p>Spark is powerful but heavy for a single-machine local setup. The value here was practicing the patterns, not the performance. Given the chance to rebuild this:</p><ul><li><strong>Containerize Spark</strong> — run each service in its own Docker container. Eliminates dependency conflicts and makes the environment reproducible in minutes.</li><li><strong>Replace Parquet with Delta Lake</strong> — schema evolution support and ACID transactions out of the box. No more manual schema updates on source changes.</li><li><strong>Add the broadcast join hint explicitly</strong> — the product_category_name_translation join is a perfect candidate. Small change, meaningful performance gain at scale.</li><li><strong>Tune </strong><strong>spark.sql.shuffle.partitions</strong> — the default of 200 is far too high for this dataset size. Unnecessary partitions add scheduling overhead with no benefit.</li><li><strong>Enable AQE</strong> — Adaptive Query Execution (on by default in Spark 3.2+) adjusts the plan at runtime. Automatically coalesces small partitions, converts sort-merge joins to broadcast joins, and handles skew. For a pipeline with 6 joins it makes a real difference.</li><li><strong>Use </strong><strong>coalesce before writing</strong> — after joining 7 tables and pruning to 20 columns, you end up with many small partitions holding very little data. coalesce merges them without a shuffle by combining partitions on the same node. repartition does the same but forces a full network shuffle — unnecessary overhead when all you want is fewer, fuller output files.</li></ul><h3>What’s next</h3><p><a href="https://medium.com/@abaqasif/spark-dbt-and-airflow-a-practical-walkthrough-5413599cecf8">Part 3</a> dives into dbt — how I modelled the Silver output into business-ready Gold tables, the incremental strategy behind the pipeline, and why dbt reminded me of a pattern I first used building PHP applications fifteen years ago.</p><p>The full project is available on <a href="https://github.com/abaqasif-aa/olist_data_pipeline_end">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c053d15b20e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark, dbt and Airflow — A Practical Walkthrough]]></title>
            <link>https://medium.com/@abaqasif/medallion-architecture-from-scratch-a-practical-walkthrough-with-spark-dbt-and-airflow-part-1-ab40b3d47df6?source=rss-510d9e9122cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab40b3d47df6</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[data-architecture]]></category>
            <category><![CDATA[apache-airflow]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Abaq Asif]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 04:24:26 GMT</pubDate>
            <atom:updated>2026-06-07T19:03:09.416Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a medallion architecture pipeline from scratch</h4><h3>Part 1: Overview &amp; Architecture</h3><p>Most portfolio projects stop at “it works”. This one goes further — because when you have spent 7+ years dealing with schema drift, late-arriving data, dependency conflicts and silent pipeline failures, you cannot help but build things differently. This is my walkthrough of medallion architecture with Spark, dbt and Airflow — new tools, old lessons.</p><h3>Introduction</h3><p>I wanted to get hands-on with three technologies I keep seeing across the industry: Apache Spark, dbt and Airflow. I also wanted to apply the medallion architecture end to end — not just understand it conceptually but actually build it.</p><p>I used the Olist Brazilian e-commerce dataset as the foundation for this project. The entire setup runs on my local machine using Python virtual environments which honestly comes with its fair share of headaches — dependency conflicts being the main one. The cleaner approach would have been to run each service in its own Docker container or use managed cloud services altogether, but I deliberately kept it local to focus on understanding the tools themselves rather than the infrastructure around them. I’ll go deeper on this in the challenges section.</p><p>One thing that makes this writeup a bit different — I’ll be sharing my own opinions on the tools and their features based on what I’ve seen and worked with over the years, not just a walkthrough of what I built.</p><h3>The Dataset — Olist Brazilian E-commerce</h3><p>The dataset is publicly available on <a href="https://www.kaggle.com/datasets/olistbr/brazilian-ecommerce">Kaggle</a> and was provided by Olist, the largest department store in Brazilian marketplaces. It covers around 100k orders placed between 2016 and 2018 across multiple marketplaces in Brazil. It’s real commercial data that has been anonymized, which makes it a good proxy for working with production-like data.</p><p>It’s structured as a relational database with 9 interconnected tables covering orders, customers, sellers, products, payments, reviews and geolocation. That relational structure is what made it a good fit for this project — it gave me something realistic to model rather than a flat file with nothing to join.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*947py3ERSzCMLlT-z5kB4Q.png" /></figure><p>The Gold layer was built around three analytical areas: order fulfilment performance (delivery times vs estimates), customer satisfaction trends by product category, and seller performance metrics. These are the kind of datasets you’d typically expose to a BI tool or hand off to an analyst team.</p><h3>Architecture Overview</h3><p>The pipeline follows the medallion architecture — a layered approach where each stage has a clear and specific responsibility. Raw data lands in Bronze untouched, gets cleaned and enriched in Silver, and is modelled into business-ready tables in Gold using dbt. The entire flow is orchestrated by a single Airflow DAG that runs daily and chains each stage in sequence.</p><p>From the start I wanted to build this the right way, not just get it working. That meant a few deliberate decisions: incremental loads so the pipeline only processes new or changed data rather than reloading everything from scratch each run, column pruning at the ingestion stage to carry only what’s needed through the layers rather than dragging unnecessary fields all the way to Gold, and dbt tests at each layer to catch issues early before bad data propagates downstream. Small dataset or not, these are the same principles you’d apply in production and I wanted the project to reflect that.</p><p>I ingested all 9 tables into the Bronze layer and selectively promoted to Silver and Gold based on what was needed for the analytical models. Not everything needs to make it all the way through, and deciding what does is part of the design process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1-JJn69OFe9OPdMAFigLBA.png" /></figure><h3>What’s Next</h3><p>This article is the first in a four-part series walking through the full pipeline end to end. The next three parts go deeper into each layer of the stack:</p><ul><li><a href="https://medium.com/@abaqasif/spark-dbt-and-airflow-a-practical-walkthrough-c053d15b20e6"><strong>Part 2</strong> — Data ingestion with Apache Spark: explicit schemas, schema evolution, and the Bronze and Silver layers</a></li><li><a href="https://medium.com/@abaqasif/spark-dbt-and-airflow-a-practical-walkthrough-5413599cecf8"><strong>Part 3</strong> — Data transformation with dbt: medallion modelling, incremental strategy, testing, and business layer isolation</a></li><li><a href="https://medium.com/@abaqasif/spark-dbt-and-airflow-a-practical-walkthrough-5ef932a352ee"><strong>Part 4</strong> — Orchestration with Apache Airflow: DAG design, operator choices, and reliability configuration</a></li></ul><p>The full project is available on<a href="https://github.com/abaqasif-aa/olist_data_pipeline_end"> GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab40b3d47df6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>