<?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 Morad Abbou Azaz on Medium]]></title>
        <description><![CDATA[Stories by Morad Abbou Azaz on Medium]]></description>
        <link>https://medium.com/@moradabaz?source=rss-126bf1b0d2de------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*V9hODG5E0__PQaewVCDOdA.jpeg</url>
            <title>Stories by Morad Abbou Azaz on Medium</title>
            <link>https://medium.com/@moradabaz?source=rss-126bf1b0d2de------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:10:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@moradabaz/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[Semantic Layer Routing: Giving the Model Only What the Question Needs]]></title>
            <link>https://medium.com/@moradabaz/semantic-layer-routing-giving-the-model-only-what-the-question-needs-d2b16ccc8d3a?source=rss-126bf1b0d2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2b16ccc8d3a</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[semantic-layer]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[analytics-engineering]]></category>
            <dc:creator><![CDATA[Morad Abbou Azaz]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 16:31:01 GMT</pubDate>
            <atom:updated>2026-09-27T16:31:01.536Z</atom:updated>
            <content:encoded><![CDATA[<p><em>To build reliable Text-to-SQL agents, your semantic layer needs a </em><strong><em>Schema Routing Engine</em></strong><em>. Here is how it works, what we learned testing it in real benchmarks, and the best practices for implementing it.</em></p><h3>What is Schema Routing and Why It Matters</h3><p>Schema Routing is a deterministic gateway sitting between the user’s question and the LLM’s context window.</p><p>Instead of exposing all models, the routing engine inspects the query, matches its intent to a specific question_type in a YAML configuration file, and sends <strong>only 1 or 2 relevant tables, live column types, join keys, and specific business notes</strong> to the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lwkV-p-q07PpHk9s0nAhjg.png" /></figure><h3>Why it is critical:</h3><ul><li><strong>Eliminates Schema Hallucinations:</strong> The LLM cannot join or reference tables that are completely absent from its context window.</li><li><strong>Reduces Latency and Costs:</strong> Strips out thousands of unnecessary schema tokens per request.</li><li><strong>Enforces Business Logic:</strong> Injects critical domain caveats (e.g., distinguishing between the <em>current</em> property manager and the <em>manager at booking time</em>).</li></ul><h3>What routing is in DBT, in practice</h3><p>Routing is a YAML file, not a framework. A question_type entry maps a set of keywords to the table (or tables) that answer that shape of question, the join keys between them if more than one table is needed, and a notes field for the one caveat nothing else in the config can express.</p><p>This is a real entry, unedited, from agent_routing.yml:</p><pre>- type: revenue_per_property_manager<br>  keywords: [&quot;property manager&quot;, &quot;manager&#39;s portfolio&quot;, &quot;each of their accommodations&quot;]<br>  primary_mart: mart_kpi<br>  columns: [revpan, adr]<br>  secondary_tables: [dim_accommodation]<br>  join_keys:<br>    - &quot;mart_kpi.accommodation_id = dim_accommodation.accommodation_id&quot;<br>  notes: &gt;<br>    dim_accommodation.property_manager_id is the CURRENT manager.<br>    fct_reservation deliberately excludes property_manager_id (it&#39;s a<br>    frozen snapshot at booking time) -- a historical variant of this<br>    question should hit the fallback, not reach into a different table.</pre><p>That notes field is where the real decision lives. This project has two columns that could both plausibly answer &quot;who manages this,&quot; and only a person deciding the routing config knows which one a given question actually means. No matching algorithm is going to infer that on its own.</p><p>A YAML file doesn’t match anything by itself. A function does, and it’s worth seeing exactly what it does, because its limitations are the whole story of this post:</p><pre>def match_question_type(question, routing_config):<br>    question_lower = question.lower()<br>    best_type = None<br>    best_keyword_len = -1<br><br>    for question_type in routing_config[&quot;question_types&quot;]:<br>        for keyword in question_type[&quot;keywords&quot;]:<br>            if keyword.lower() in question_lower and len(keyword) &gt; best_keyword_len:<br>                best_type = question_type<br>                best_keyword_len = len(keyword)<br><br>    return best_type</pre><h3>Benchmark Experiment &amp; Results</h3><p>We evaluated our live agent against a benchmark of 6 real-world analytical questions using scoped context. You can find the experiment in these resources:</p><ul><li><a href="https://moradabaz.github.io/blog/semantic-layer-pill-3-routing/">https://moradabaz.github.io/blog/semantic-layer-pill-3-routing/</a></li><li><a href="https://github.com/moradabaz/semantic-layer-pills/tree/main/posts/04-routing-without-scope">https://github.com/moradabaz/semantic-layer-pills/tree/main/posts/04-routing-without-scope</a></li></ul><p><strong>The setup</strong>: same 6 business questions this series has run since <a href="https://medium.com/@moradabaz/building-a-semantic-layer-from-zero-part-1-when-you-give-an-llm-a-database-and-zero-context-69c38020655c">post 1</a>, now with the model seeing only the table its matched question type points to, instead of the whole schema.</p><p>A typo in the generated SQL (SUM(k.revpand), one extra letter) got rejected by Postgres immediately. Wrong, loud, easy to fix. That&#39;s the good kind of failure.</p><p>One question matched no routing entry at all, and the fallback kicked in exactly as designed: “I don’t have a defined routing rule for this question. Can you rephrase it?” No guess, no invented table.</p><p>Another question asked to compare ADR against a normalized daily cost. The matched routing type only exposed KPI columns, no cost data. The model didn’t invent a cost column to answer with. It said the table it had access to didn’t contain what the question needed.</p><blockquote><strong>Key lesson:</strong> An honest refusal is the safe failure mode. A model that says “I don’t have enough context” is doing its job. The dangerous failure mode is the one below.</blockquote><p><strong>The Good (Honest Refusals and Safe Failures):</strong></p><ul><li><strong>Q2 (Fallback Working):</strong> A question about cancelled reservations matched no existing rule. The agent safely triggered its fallback template instead of guessing.</li><li><strong>Q4 (Honest Refusal):</strong> The query requested cost data, but the routed context only contained KPI metrics. The agent correctly replied: <em>“I don’t have access to cost data in this context to answer your question.”</em></li><li><strong>The Gaps (String Fragility and Grain Issues):</strong></li><li><strong>Q4 (Keyword Miss):</strong> The query asked for “normalized <strong>daily</strong> cost”, but the keyword rule looked for the exact substring &quot;normalized cost&quot;. The word insertion caused the router to miss the correct context.</li><li><strong>Q5 (Grain Bug Persisted):</strong> Routing delivered the right table (mart_aggregates), but because the table is grained at (accommodation_id, month), the model failed to aggregate across accommodations, returning 15 duplicate rows.</li></ul><blockquote><strong>Key lesson:</strong> routing’s job is reducing noise, not fixing what a table actually contains. If the right table is ambiguous about its own grain, trimming the context down to “just that table” hands the model a smaller, still-ambiguous thing to be confidently wrong about.</blockquote><h3>Practical Tips for Analytics Engineers</h3><ul><li><strong>Replace Keyword Matching with Embeddings / Semantic Search:</strong> Exact substring matching is excessively fragile when facing natural language variations (as seen with <em>“normalized daily cost”</em>). Implementing <strong>Embeddings</strong> or vector semantic search maps the user’s true intent directly to the correct question_type, avoiding routing failures caused by minor phrasing changes.</li><li><strong>Routing vs Scope (Two Separate Layers):</strong> Keep query planning (Routing: <em>which tables and joins to use?</em>) in agent_routing.yml separate from access control and safety (Scope: <em>row limits, schema restrictions, and PII blocking</em>) in agent_scope.yml. Every request must pass through both layers.</li><li><strong>Apply Defense-in-Depth:</strong> Declare explicit safety rules (such as forbidden PII columns like guest_name or email) even if your current models do not expose them. This guarantees the system fails loudly the day someone adds a new table that accidentally leaks sensitive data.</li><li><strong>Routing Eliminates Noise, Not Grain Bugs:</strong> Scoping context keeps the prompt clean, but your dbt models must still consolidate and aggregate data (dim_ / fct_) to avoid fan-out errors when executing joins at runtime.</li><li><strong>Distinguish Live Data from Historical Snapshots:</strong> Document in your routing notes when two similar columns carry different temporal meanings (e.g., accommodation.property_manager_id as the <strong>current</strong> manager vs reservation.property_manager_id as a <strong>snapshot</strong> at booking time).</li><li><strong>Audit Coverage Against Your dbt Schema:</strong> Do not review routing files merely for YAML syntax validity. Cross-reference your rules against dbt dimensions and tests (accepted_values). If a column is vital to the business (e.g., channel or season), it deserves its own dedicated routing entry.</li></ul><p>Full transcript and routing config: <a href="https://github.com/moradabaz/semantic-layer-pills/tree/main/posts/04-routing-without-scope">github.com/moradabaz/semantic-layer-pills</a></p><p>If you’re routing context to an LLM today, how many of your routing rules have actually been tested against a real, slightly-off phrasing, versus just read back to confirm they look right?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2b16ccc8d3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LSM-Trees vs. B+ Trees: The Computer Science Behind DB Performance]]></title>
            <link>https://medium.com/@moradabaz/lsm-trees-vs-b-trees-the-computer-science-behind-db-performance-03b1ed22e82e?source=rss-126bf1b0d2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/03b1ed22e82e</guid>
            <category><![CDATA[streaming-databases]]></category>
            <category><![CDATA[rocksdb]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Morad Abbou Azaz]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 20:29:10 GMT</pubDate>
            <atom:updated>2026-09-23T20:29:10.872Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A deep dive into the disk architectures of RocksDB/Flink and PostgreSQL, how memory access patterns shape I/O trade-offs, and when to use each.</em></p><p>As software engineers or Data Engineers, we often treat databases as black boxes. We write SELECT queries, configure object-relational mappers (ORMs), or tune connection pools. At that point, system performance comes down to a fundamental hardware reality: <strong>How does your storage engine manage reads and writes between RAM and Disk?</strong></p><p>In this article, we will dissect the two dominant storage engine designs in modern software architecture:</p><ol><li><strong>B+ Trees (In-Place Updates):</strong> The backbone of relational databases like <strong>PostgreSQL</strong> and <strong>MySQL</strong>.</li><li><strong>LSM-Trees (Log-Structured Merge-trees):</strong> The engine driving high-throughput streaming systems and NoSQL stores like <strong>Apache Flink (RocksDB)</strong>, <strong>Cassandra</strong>, and <strong>RocksDB</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjTVr1-y9ZTluyIlpAbOPw.png" /></figure><h3>1. The B+ Tree Architecture: Optimized for Deterministic Reads</h3><p>Traditional Relational Database Management Systems (RDBMS) like PostgreSQL store table rows in an unordered heap of <strong>fixed-size disk pages</strong> (typically 8 KB). To avoid scanning gigabytes of disk pages sequentially (Seq Scan), PostgreSQL uses <strong>B+ Trees</strong> for its indexes.</p><p>Unlike a binary search tree (like an AVL tree) that has a high node depth, a B+ Tree is extremely “wide” and shallow. A single <strong>8 KB</strong> page node can hold hundreds of keys, keeping the tree height to just 3 or 4 levels — even for millions of records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j_bd7CDRXuH5OWs1eoQFBg.png" /></figure><h4>The Read Path: Microsecond Precision</h4><p>When you query WHERE id = 42:</p><ol><li>The engine traverses the B+ Tree from the root page down to the leaf page (3–4 disk jumps).</li><li>The leaf page returns a <strong>Tuple ID (TID)</strong> containing the exact physical location: Page 45, Line 12.</li><li>The engine jumps directly to Page 45 in the table heap and returns the row.</li></ol><h4>The Write Path: The “In-Place” Cost</h4><p>To update a record or insert a new row in a table with 5 indexes:</p><ol><li>The engine writes to the <strong>Write-Ahead Log (WAL)</strong> sequentially for crash recovery.</li><li>It modifies the 8 KB page in memory.</li><li>The <strong>Checkpointer</strong> process overwrites the page <strong>in-place</strong> back onto the physical disk location.</li><li><strong>Crucially:</strong> It must navigate and overwrite pages in <strong>all 5 B+ Tree index files on disk</strong>.</li></ol><blockquote><strong><em>The Trade-off:</em></strong><em> Writes cause </em><strong><em>Random I/O, </em></strong><em>modifying records scattered across a large table forces the storage engine to perform expensive disk page writes at disparate disk locations.</em></blockquote><h3>2. The LSM-Tree Architecture: Optimized for Extreme Write Throughput</h3><p>When streaming engines like <strong>Apache Flink</strong> process hundreds of thousands of events per second, in-place disk page updates become an immediate bottleneck.</p><p><strong>LSM-Trees (Log-Structured Merge-trees)</strong> solve this by turning write operations into <strong>purely sequential memory and append-only disk operations</strong>. An LSM-Tree never overwrites an existing file in place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5L9q_3KBurgWDuvh84R-HA.png" /></figure><h3>The Write Path: Memory-Speed Ingestion</h3><ol><li><strong>MemTable (Table allocated in RAM):</strong> Incoming records are inserted into an in-memory sorted structure (a MemTable). The write returns in microseconds.</li><li><strong>Sequential Flush:</strong> When the MemTable fills up (e.g., reaches 64 MB), it is flushed to disk as an <strong>SSTable (Sorted String Table)</strong>. This is a single, continuous, <strong>immutable block write</strong>.</li><li><strong>Compaction:</strong> In the background, a worker process merges multiple SSTable chunks using a merge-sort algorithm, purging deleted or overwritten historical records.</li></ol><h3>The Read Path: The Search Cost</h3><p>Because records are written into multiple immutable SSTable files over time, a single key might exist in multiple places:</p><ul><li>To read a key, the engine checks the MemTable in RAM first.</li><li>If missing, it must search across various SSTable files on disk.</li><li><strong>The Optimization:</strong> To avoid reading every disk chunk, RocksDB uses in-memory <strong><em>Bloom Filters</em></strong>. A Bloom Filter mathematically tells the engine with 100% certainty if a key <em>does NOT</em> exist in a specific SSTable chunk, preventing unnecessary disk reads.</li></ul><h3>3. Deep-Dive Trade-off Matrix</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oViUGzw7C75UdrUQ6Ft-8g.png" /></figure><h3>Choose an LSM-Tree (RocksDB / Cassandra / Flink) when:</h3><ol><li><strong>You are building real-time streaming applications:</strong> You need to maintain large state stores (e.g., windowed aggregations, session states) driven by high-throughput ingestion from Kafka or Kinesis.</li><li><strong>Your write-to-read ratio is high:</strong> You ingest millions of metrics, logs, or user tracking events per minute.</li><li><strong>You need effortless incremental backups:</strong> Since SSTables are immutable, uploading state snapshots to cloud storage (like S3) involves copying only the newly generated SST files without locking the system.</li></ol><h3>Choose a B+ Tree (PostgreSQL / MySQL) when:</h3><ol><li><strong>You require complex relational queries:</strong> Your application relies heavily on multi-table JOINs, secondary indexes, and structured transactions (ACID compliance).</li><li><strong>Predictable read performance is critical:</strong> Your system is an OLTP application (e.g., an e-commerce checkout or banking system) where point-lookup latency on primary and secondary keys must remain strictly consistent.</li><li><strong>Your state fits within well-indexed tables:</strong> You need precise ad-hoc querying capability without managing custom compaction or Bloom filter memory allocations.</li></ol><p>Neither storage engine is inherently superior; they were engineered for opposing physical constraints.</p><p><strong>B+ Trees pay a performance tax on writes to grant you microsecond, deterministic reads.</strong> <strong>LSM-Trees trade away read simplicity to turn disk writes into near-instantaneous memory operations.</strong></p><p>Understanding these low-level disk trade-offs allows you to stop fighting your storage layer and start architecting systems that work <em>with</em> the hardware, rather than against it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03b1ed22e82e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Semantic Layer from Zero: Giving the Model the right Governance]]></title>
            <link>https://medium.com/@moradabaz/semantic-layer-routing-giving-the-model-only-what-the-question-needs-with-dbt-53b8a8c80f2d?source=rss-126bf1b0d2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/53b8a8c80f2d</guid>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[analytics-engineering]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Morad Abbou Azaz]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 14:08:38 GMT</pubDate>
            <atom:updated>2026-09-23T15:01:25.620Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Read a real routing config, run it against a live agent, then deliberately revert one function to its old, buggy version and watch a real misrouting bug come back on your own machine.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CofEsOPi96wjJVW14Taqlw.png" /></figure><p>My previous posts about this topic dumped the entire semantic layer into every prompt. That doesn’t scale past a handful of tables, which is the actual reason routing exists: match the question to a small, relevant slice of the schema, and hand over only that.</p><p>When building a semantic layer to power a Text-to-SQL agent (like an LLM or AI agent), you quickly run into a common roadblock: <strong>one-line column descriptions in your </strong><strong>.yml files just aren&#39;t enough.</strong></p><p>Real world business logic, such as revenue management, feature usage or critical operation, rarely fits into a single sentence. Cramming three detailed paragraphs into a _marts.yml file turns a clean catalog into an unreadable wall of text for both humans and models.</p><p>To test how deep business logic affects AI agents, we ran an experiment evaluating whether feeding full <em>doc-block-resolved</em> context to the LLM outperforms short one-sentence descriptions. While short descriptions work for simple formulas, complex rules require a proper home.</p><p>To ensure the semantic layer consumed by our AI agent remains <strong>reliable, well-documented, and stable</strong>, dbt provides three core governance mechanisms: <strong>Doc Blocks</strong>, <strong>Exposures</strong>, and <strong>Contracts</strong></p><h3>1. dbt Doc Blocks: Where Does the Deep Context Live?</h3><p><strong>Doc blocks</strong> decouple the metadata declaration of a model from its detailed explanation. They allow you to write reusable Markdown (.md) documentation blocks and reference them cleanly across your YAML files using Jinja.</p><pre># agent_stack/dbt/models/marts/_marts.yml<br>- name: avg_booking_window_days<br>  description: &quot;{{ doc(&#39;avg_booking_window_days&#39;) }}&quot;</pre><pre># agent_stack/dbt/models/marts/_marts.md<br>{% docs avg_booking_window_days %}<br>Average number of days between when a guest booked a reservation and<br>their check-in date (`start_date - booked_at`)...<br><br>**Do not compute this from `reservation.created_at`.** `created_at` is a<br>technical row-insert timestamp, not the date the guest actually made the<br>booking -- for this project&#39;s seed data, most reservations were<br>bulk-inserted long after their real booking date, and<br>`start_date - created_at` comes out negative for the majority of<br>historical rows...<br>{% enddocs %}</pre><ul><li><strong>What problem do they solve? </strong>They allow you to maintain rich, deep technical context (business logic, edge cases, misuse warnings) in a single centralized place without cluttering your .yml schema files.</li><li><strong>Impact on the AI Agent: </strong>In our experiment, resolving these blocks allowed us to pass full, untruncated context to the model prompt (e.g., <em>“Do not compute this from </em><em>reservation.created_at because it is a technical row-insert timestamp; use </em><em>booked_at instead&quot;</em>). This supplies the LLM with the <strong>deep semantic context</strong> required to avoid logical errors that one-liners simply cannot prevent.</li></ul><h3>2. dbt Exposures: Does Anyone Know an Agent Depends on This?</h3><p><strong>Exposures</strong> are dbt metadata declarations that explicitly define downstream consumers of your data models, such as dashboards, applications, or AI agents.</p><pre>exposures:<br>  - name: text_to_sql_agent<br>    type: application<br>    maturity: low<br>    description: &gt;<br>      Answers business questions about occupancy, revenue, and<br>      cancellations by querying the semantic layer directly.<br>    depends_on:<br>      - ref(&#39;mart_kpi&#39;)<br>      - ref(&#39;mart_aggregates&#39;)</pre><ul><li><strong>What problem do they solve? </strong>They make downstream dependencies visible to the dbt project itself. By declaring that a specific consumer (e.g., text_to_sql_agent) relies on mart_kpi or mart_aggregates, dbt understands that this consumer is a critical part of the data lineage.</li><li><strong>Impact on the AI Agent: </strong>They protect the agent from <strong>silent breaking changes</strong>. If a data engineer renames or drops a column thinking it is unused, dbt will flag the breaking change during CI against that specific exposure. This prevents silent failures in production where the agent suddenly throws raw database errors to end users.</li></ul><h3>3. dbt Contracts: Preventing Silent Schema Drift</h3><p><strong>Contracts</strong> in dbt enforce strict structural alignment (enforced: true) between the defined YAML schema and the underlying physical database model.</p><pre>models:<br>  - name: mart_aggregates<br>    config:<br>      contract:<br>        enforced: true<br>    columns:<br>      - name: available_nights<br>        data_type: integer<br>      - name: revenue<br>        data_type: numeric(10,2)<br>      # every column needs an explicit data_type once a contract is enforced</pre><ul><li><strong>What problem do they solve? </strong>They guarantee that column names and explicit data types (data_type) in your models strictly match what gets built. If a SQL transformation accidentally changes an INTEGER column to TEXT, dbt build will fail immediately before executing the CREATE TABLE query.</li><li><strong>Impact on the AI Agent: </strong>They guarantee <strong>structural integrity for the LLM prompt</strong>. If your documentation tells the model that a column is numeric so it can run SUM(), but the actual database column silently drifted to TEXT, the model&#39;s query will fail. Contracts prevent the documentation fed into the prompt from falling out of sync with physical reality.</li></ul><h3>We tried the experiment</h3><p>Same setup as post 2 — same 4 tables, same 6 questions, no routing, no per-question filtering, same <a href="https://github.com/moradabaz/pms-semantic-layer/blob/main/agent_stack/chapters/13-live-agent/agent/docs_dump.py">docs_dump.py</a> mechanism from that post. You can try it yourself following the guides of this page <a href="https://moradabaz.github.io/blog/semantic-layer-pill-3-routing/">semantic-layer-pill-3-routing</a>.</p><p>The only change: CONTEXT_MODE=docs_full instead of docs_short, which flips _resolve_description&#39;s short flag to False — every column&#39;s full, doc-block-resolved text goes into the prompt instead of just its first sentence. <a href="https://github.com/moradabaz/semantic-layer-pills/blob/main/posts/03-business-logic-notes/transcript.md">Full transcript here.</a></p><h4>The result: 5/6 correct, 1 confidently wrong</h4><p>Five questions landed exactly right. The sixth, “which month had the most cancelled reservations, and what’s the lost revenue for that month”, came back with February 2026, 2 cancellations, $62,284.22 lost.</p><p>The real number, verified directly against the database: January 2026, 45 cancellations, $61,605.58.</p><p>$62,284 for 2 cancelled reservations is already implausible on its face — this dataset’s nightly rates run $40–$350, not $30,000 a booking. That’s worth flagging as a habit on its own: a number that’s an order of magnitude off from what the rest of your data looks like deserves a second look before it goes in a slide deck.</p><h3>What We Learned from Our Verification Experiment</h3><p>In our benchmark testing (CONTEXT_MODE=docs_full vs docs_short), passing the full resolved doc blocks to the model successfully solved complex business logic caveats that short descriptions missed.</p><p>However, we also uncovered a key insight: <strong>richness is not the same as completeness.</strong></p><p>While doc blocks successfully prevented calculation errors by explaining <em>what columns mean</em>, they didn’t automatically prevent grain-mismatch mistakes (e.g., forgetting to SUM() across accommodations when a table is grained at accommodation_id, month). This highlighted that a complete semantic layer for LLMs requires both <strong>deep doc blocks</strong> for business logic and <strong>strict grain definitions</strong> (or dedicated marts) to guide query structure.</p><p><strong>Bottom Line:</strong> <em>Doc Blocks provide the </em><strong><em>semantic richness</em></strong><em> so the agent understands the “why” and “how” behind the data, while Exposures and Contracts provide the </em><strong><em>operational safety</em></strong><em> required to ensure that semantic layer never breaks silently in production.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53b8a8c80f2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Another Spark Issue: 204 Gigabytes of Spilled Memory and Zero Skewed Tasks]]></title>
            <link>https://medium.com/@moradabaz/another-spark-issue-204-gigabytes-of-spilled-memory-and-zero-skewed-tasks-04a3824f4d7c?source=rss-126bf1b0d2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/04a3824f4d7c</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[apache-iceberg]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Morad Abbou Azaz]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 06:49:07 GMT</pubDate>
            <atom:updated>2026-09-15T06:49:07.242Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A weekly merge job kept getting slower, week after week. Every signal pointed at the usual suspect. It wasn’t. Here’s how we told the difference, and what was actually eating the extra time.</em></p><p>A few weeks ago, after auditing our most expensive jobs, I noticed something small and annoying in one of our pipelines. Every week it ran a bit slower than the last: 555 seconds, then 572, then 601, then 669, then 714. The cluster was composed by:</p><ul><li>8 nodes</li><li>32 Gb of RAM each</li><li>128 Gb of Disk each</li></ul><p>When I opened the Spark UI to see what was going on, two stages jumped out immediately. Both were spilling to disk, a lot of it. One stage alone had spilled 183 gigabytes to disk and 822 gigabytes to memory before that. The other added another 21 gigabytes on disk. Altogether, close to 205 gigabytes of disk spill in a single run, for a job that only reads about 60 gigabytes of shuffle data to do its work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*iwiVbaeEGNO1YGtiWI5mzw.png" /></figure><p>My first thought, and I suspect most people’s first thought, was <strong>data skew</strong>. It’s the classic story, and the fix is always the same such as salt the key, repartition, let adaptive query execution handle the skewed join. We already had skew join handling turned on.</p><h3>Checking SparkUI instead of guessing</h3><p>I decided to actually check instead of assuming, and this is the part worth writing down, because the way you check for skew is almost embarrassingly simple once you know to look for it. Spark’s own UI computes it for you. Every stage detail page shows a summary row across all its tasks: minimum, 25th percentile, median, 75th percentile, maximum. If a job is skewed, that row screams it at you. A minimum of fifty megabytes and a maximum of eight gigabytes is a red flag with no analysis required</p><p>Ours didn’t look like that at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*GIh_SEh-ZyaJTD2yb1uj2A.png" /></figure><p>Every single one of the 56 tasks in the worst stage had read exactly 1.10 gigabytes of shuffle data. Minimum, median and maximum were all identical. Every task also spilled exactly <strong>3.28 gigabytes to disk and 14.69 gigabytes to memory</strong>. Not close to each other. Identical.</p><blockquote>That’s the opposite of skew. Skew means some tasks suffer while others coast. Every task here suffered exactly the same amount.</blockquote><p>Skew just gives one task more of the same kind of work. This was every task doing something that expanded far beyond its own input, uniformly. But another interesting point is that each task reads 1.10 Gb and spilled 14.69 Gb. That’s a 13x data output amplification.</p><h3>The number that shouldn’t be possible</h3><p>Before going further, one thing is worth clearing up, because it tripped me up the first time I saw it: “ <em>How can a single stage report </em><strong><em>822 gigabytes</em></strong><em> of memory spilled when the whole cluster only has 256 gigabytes of RAM across all eight workers combined?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*iwiVbaeEGNO1YGtiWI5mzw.png" /></figure><p>The answer is that the number is a running total. Spark reserves a small buffer for sorting and merging data during a heavy shuffle operation. When that buffer fills up, Spark writes it to disk, empties it, and keeps going. Do that enough times over a task that runs for minutes, and the sum of everything ever written can dwarf the memory actually available at any single moment. The number tells you how many times the bucket got emptied, not how big the bucket was.</p><h3>Reading the code instead of the dashboard</h3><p>The table definition told the rest of the story.</p><pre>CREATE TABLE events (<br>  event_id  STRING,<br>  ...<br>)<br>PARTITIONED BY (bucket(32, event_id))<br>-- no write.merge.mode set → defaults to copy-on-write<br><br>MERGE INTO events AS t<br>USING incoming AS s<br>ON t.event_id = s.event_id<br>WHEN MATCHED THEN UPDATE SET *<br>WHEN NOT MATCHED THEN INSERT *</pre><p>The table hashes each row’s id into one of 32 buckets, so a merge on that same id can prune straight to the one bucket that matches instead of scanning everything. Smart, and still correct today.</p><p><strong>Why we set the bucketting system at first?</strong> What wasn’t set is the write mode. Left at its default, every MERGE INTO rewrites a touched bucket&#39;s files whole, not just the changed row. That&#39;s why this worked fine for a long time: when the table was small, a whole bucket was small too, so rewriting it cost almost nothing.</p><p><strong>Why It stopped being cheap?</strong> There are two main reasons:</p><ul><li>A hash has no relationship to time, so this week’s batch lands scattered across nearly all 32 buckets, not concentrated in a couple like it would with a date partition.</li><li>And buckets never close: a bucket holds everything ever hashed into it since day one. As the table grew, every bucket grew with it, and the same weekly rewrite got more expensive every week, with the incoming volume never changing. That’s the creeping runtime we started with.</li></ul><h3>The fix, and the thing that broke first</h3><p>Once the mechanism was clear, the fix was to stop rewriting whole partitions on every merge. Modern table formats support a read-optimized write mode where a merge only records small delete markers for the rows that changed, plus the new rows themselves, leaving the rest of a partition’s files untouched. We switched the table’s merge, update and delete behavior to that mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*BXVKvAM-SMLzdGgCaytKsw.png" /></figure><p><strong>The improvement wasn’t total</strong>, and that’s worth being honest about. The new write mode still has to read an entire matching partition to figure out which rows need a delete marker, so that lookup cost stays proportional to the size of the partition, not the size of the weekly delta. What it stops doing is rewriting the whole thing afterward. It fixes the write side of the problem, not the read side, which is exactly what we expected going in.</p><p><strong>The lesson that stuck with me isn’t really about any particular table format or engine</strong>. Spill and slow tasks are a symptom shared by two very different diseases, and the standard toolkit for one does nothing for the other. Data skew means some tasks are drowning while others coast, and you fix it by rebalancing the work. What we had here was every task doing exactly its fair share of exactly the same amount of work, and still drowning, because the operation itself was quietly amplifying a small amount of input into a much larger amount of actual work underneath. No amount of repartitioning or salting touches that.</p><p>The only way to catch the difference is to actually look at the percentile spread across tasks before reaching for the usual skew playbook. If it’s flat, the bottleneck isn’t in how the data is split. It’s in what the operation does to it once it gets there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04a3824f4d7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Semantic Layer from Zero (Part 2): Can Column Descriptions Alone Stop an LLM From…]]></title>
            <link>https://medium.com/@moradabaz/building-a-semantic-layer-from-zero-part-2-can-column-descriptions-alone-stop-an-llm-from-8fc39464e1cb?source=rss-126bf1b0d2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fc39464e1cb</guid>
            <category><![CDATA[semantic-layer]]></category>
            <category><![CDATA[analytics-engineering]]></category>
            <category><![CDATA[dbt]]></category>
            <dc:creator><![CDATA[Morad Abbou Azaz]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 10:00:29 GMT</pubDate>
            <atom:updated>2026-08-26T10:01:35.007Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Semantic Layer from Zero (Part 2): Can Column Descriptions Alone Stop an LLM From Hallucinating SQL?</h3><p><em>Same 6 questions, same database — but this time the model gets the schema. 6/6 correct. And one formula in a one-line description that prevents a bug you won’t see again until post 5.</em></p><p>This is part 2 of a 6-post series: <a href="https://medium.com/@moradabaz/building-a-semantic-layer-from-zero-part-1-when-you-give-an-llm-a-database-and-zero-context-69c38020655c"><strong>“How much context does a model actually need to answer SQL questions correctly?”</strong></a></p><p>In <a href="https://medium.com/@moradabaz/building-a-semantic-layer-from-zero-part-1-when-you-give-an-llm-a-database-and-zero-context-69c38020655c">post 1</a>, an LLM was given a real Postgres database and zero context. 6 business questions, 6 wrong answers — 5 hallucinated table names, 1 fabricated number with no query behind it. The fix seems obvious: give it the schema.</p><p>This post tests exactly that, and only that. No routing, no per-question filtering, no business-logic notes. Just the entire semantic layer schema dumped into the prompt every single time.</p><h3>The problem from post 1 — and why “just give it the schema” sounds like the answer</h3><p>Post 1’s visible failures were all the same: the model guessed table names (reservations, bookings, unit) instead of the real ones (reservation, accommodation, property_manager). It was pattern-matching against thousands of booking schemas from its training data, not querying the database it was connected to.</p><p>The natural assumption: hand the model the table and column names, and those hallucinations disappear. No ambiguity left to guess at.</p><p>That assumption is half right. This post measures which half.</p><h3>Introducing dbt: Where “the schema” actually comes from</h3><p>Nothing in post 1 had any documentation at all — the model queried the raw application database directly. From this post onward, everything runs against a <strong>dbt project</strong> built specifically to sit between the raw PostgreSQL tables and anything that reads from them — a BI tool, an analyst, or an LLM.</p><p>The dbt project has two layers:</p><p><strong>Staging</strong> is a boring, 1:1 mirror of the raw tables — renamed columns, enforced types, no joins, no business rules. It’s implementation detail. No external consumer should ever query it directly.</p><p><strong>Marts</strong> is where the actual business logic lives: KPI formulas, revenue proration across month boundaries, PII removal. And critically, where _marts.yml puts a description: on every single column.</p><p>This is the real, unedited YAML for the adr column:</p><pre># _marts.yml<br>- name: adr<br>  description: &quot;{{ doc(&#39;adr&#39;) }}&quot;</pre><p>{{ doc(&#39;adr&#39;) }} is a reference into a separate Markdown file (_marts.md) where the actual text lives:</p><pre>{% docs adr %}<br>Average Daily Rate: revenue / occupied_nights. Both inputs are prorated<br>across month boundaries. NULL (not 0) when occupied_nights is 0, meaning<br>there&#39;s nothing to average, not a $0 rate.<br>{% enddocs %}</pre><p>This is standard dbt — dbt docs generate reads exactly this and builds a browsable documentation site. None of it was written for an LLM. That&#39;s the next problem: getting text that lives in a .yml/.md pair into the string that actually becomes a model&#39;s prompt.</p><h3>How a YAML description becomes a prompt</h3><p>Two small functions bridge the gap, and it’s worth seeing both — this is the part a “give it the schema” one-liner always skips.</p><p><strong>Step 1 — turn the dbt files into a plain-text block.</strong> A function called build_full_schema_context reads _marts.yml, resolves each {{ doc(...) }} reference against _marts.md, and builds a string — not an HTML page, a literal text block. It also queries information_schema.columns live, so the prompt reflects the real schema right now, not whatever someone last edited in the YAML.</p><p>For this experiment, each doc block is trimmed to its first sentence only (short=True). For adr, that means the model sees <em>&quot;Average Daily Rate: revenue / occupied_nights&quot;</em> — and nothing more.</p><p><strong>Step 2 — that string becomes the system prompt.</strong> The system message now says:</p><pre>You are a helpful PostgreSQL assistant for a property management system<br>database. Only query the tables described below — they are the only ones<br>you have access to. Write a single read-only SQL query (SELECT or WITH)<br>that answers the question.</pre><pre>Table: public_marts.mart_kpi<br>  - accommodation_id (bigint) -- The accommodation this row rolls up.<br>  - month (date) -- First day of the calendar month this row covers.<br>  - occupancy_rate_pct (numeric) -- 100 * occupied_nights / available_nights.<br>  - adr (numeric) -- Average Daily Rate: revenue / occupied_nights.<br>  - revpan (numeric) -- Revenue Per Available Night: revenue / available_nights.<br>  ...<br>Table: public_marts.mart_aggregates<br>  ...<br>Table: public_marts.fct_reservation<br>  ...<br>Table: public_marts.dim_accommodation<br>  ...</pre><p>Every column across 4 marts gets a one-line description like this. That messages list — the system message with the schema string, plus the user&#39;s business question — is the literal thing sent over the wire. There&#39;s no other channel. If a column&#39;s description isn&#39;t in that string, the model has never seen it.</p><h3>The result: 6/6 correct, verified</h3><p>Same 6 business questions as post 1. Every one came back right — cross-checked against the database directly, not taken on faith.</p><p>The model that hallucinated reservations and bookings in post 1 now writes public_marts.fct_reservation and public_marts.mart_kpi. The model that fabricated &quot;70% occupancy&quot; now writes a real query with a JOIN to dim_accommodation, a WHERE on property_manager_id = 9, and a NULLIF to avoid division by zero. Every query ran, every result matched.</p><p>You can check the transcript and results here:</p><p><a href="https://github.com/moradabaz/semantic-layer-pills/blob/main/posts/02-schema-and-docs/transcript.md">https://github.com/moradabaz/semantic-layer-pills/blob/main/posts/02-schema-and-docs/transcript.md</a></p><h3>Why one formula in a one-line description matters more than you think</h3><p>Look at the ADR question: <em>“</em><strong><em>Which accommodations have an ADR lower than their normalized daily cost over the last 3 months?</em></strong><em>”</em></p><p>The model’s query used AVG(mk.adr) directly from mart_kpi — because the description said <em>&quot;revenue / occupied_nights&quot;</em>, and the column already contained the computed value. Instead of inventing a ratio or guessing a formula, It just used what was there, because the description told it what &quot;there&quot; meant.</p><p>This matters because in post 5, the same question comes back under a different setup and We’ll see that the model gets it wrong. The one-line formula that prevented the bug here is exactly the kind of thing that disappears when you rely on column names alone instead of explicit definitions, as it has happened in Post 1.</p><blockquote><em>A </em><em>description that says &quot;Average Daily Rate&quot; tells a reader what the column is called. That </em><em>description says &quot;revenue / occupied_nights&quot; and tells the model how to compute it correctly.</em></blockquote><h3>What this does not solve</h3><p>6/6 is easy to over-read. Three things this result does not prove:</p><p><strong>It worked because the schema is tiny.</strong> Four tables, 37 columns total. Dumping an entire schema into a prompt does not scale to a production warehouse with hundreds of tables.</p><p><strong>One-line descriptions drop critical warnings.</strong> The full doc block for avg_booking_window_days includes a warning: <em>&quot;Do not compute this from reservation.created_at. created_at is a technical row-insert timestamp, not the date the guest actually made the booking.&quot;</em> The short=True trim cuts that warning entirely. Post 3 tests what happens when those warnings are back in the prompt, and finds a failure this post&#39;s approach didn&#39;t catch.</p><p><strong>Nothing here validates against a data contract.</strong> The model saw column types as strings in a prompt. Nothing checked that adr is still numeric by the time the query runs. A not_null test on a column that silently became TEXT still passes — a non-null string is still non-null. That&#39;s a different kind of guarantee, and it doesn&#39;t come from a good prompt. It comes from contract: { enforced: true } in dbt, which refuses to build a table if the declared type doesn&#39;t match what the compiled query produces.</p><p><strong>Read-only enforcement is still doing real work underneath.</strong> Every query ran through the same is_read_only check from post 1, against a dedicated Postgres role that cannot write anywhere. Good context reduces <em>wrong</em> answers. It does nothing about a malicious or careless one.</p><h3>Engineering notes</h3><p><strong>{% docs %} blocks exist for single-sourcing, not for length.</strong> When the same explanation applies to more than one column (revenue proration feeds both adr and revpan), inline strings force duplication. Duplication drifts. One copy gets updated, the other doesn&#39;t. A {% docs %} block is one paragraph, referenced twice, that can&#39;t drift because there&#39;s only one copy.</p><p><strong>Schema separation is an access-control decision, not a tidiness decision.</strong> Staging is an uncurated, 1:1 mirror of raw sources, there’s no business rules, no proration, no NULL handling. If a BI tool or an agent can query staging directly, every fix made in the mart layer can be silently bypassed. Separate schemas exist so GRANT SELECT can target public_marts alone.</p><p><strong>The </strong><strong>generate_schema_name override is not a hack.</strong> dbt&#39;s default macro concatenates the target schema with your custom one — dev_staging, not staging. A deliberate default so developers don&#39;t collide. Override it to use the exact name in production. This is a dbt Labs-documented pattern.</p><p><strong>Verify </strong><strong>docs_dump against the live schema, not the YAML.</strong> The function queries information_schema.columns every time, not the cached YAML. If someone renamed a column in the database but forgot to update _marts.yml, the prompt reflects reality, not the last edit.</p><h3>Takeaways</h3><p><strong>A one-line description that states the formula closes off an entire category of hallucination.</strong> “Average Daily Rate” is a label. “revenue / occupied_nights” is a defense. The model doesn’t need to guess what the column means — and a human reading the docs 6 months later doesn’t either.</p><p><strong>Documentation in a dbt project is not “more context for the prompt.”</strong> Every doc block in this project exists because a wrong number already happened. Revenue not prorated across months. A booking window computed from created_at instead of booked_at. A cancellation count at the wrong grain. Documentation is a record of previously wrong assumptions, written so they can&#39;t be silently repeated — by a human or a model.</p><p><strong>Dumping the full schema works at 4 tables. It does not work at 400.</strong> Per-question routing, which consists of giving the model only the 1–2 tables relevant to the question it was asked, is a scalability fix, not an optimization. Post 4 tests it.</p><p><strong>Test every AI-generated result against the real data, not against your expectation of the right answer.</strong> “The query ran without errors” is not evidence it’s correct. Every result in this series was independently verified against the database directly.</p><h3>What’s next</h3><p>Post 3 keeps the same full, unfiltered schema dump and the same mechanism — but flips short=False, swapping the one-line descriptions for the deeper &quot;why&quot; documentation this project accumulated over several chapters. A grain mismatch (per-accommodation-month vs. portfolio-wide) produces a confident, wrong answer that richer documentation doesn&#39;t catch — and the question becomes: when is more context not enough context?</p><p>The full repository — database, dbt project, agent code, routing config, every transcript — is at <a href="https://github.com/moradabaz/pms-semantic-layer">github.com/moradabaz/pms-semantic-layer</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fc39464e1cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Semantic Layer from Zero (Part 1): When You Give an LLM a Database and Zero Context]]></title>
            <link>https://medium.com/@moradabaz/building-a-semantic-layer-from-zero-part-1-when-you-give-an-llm-a-database-and-zero-context-69c38020655c?source=rss-126bf1b0d2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/69c38020655c</guid>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[dbt-semantic-layer]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Morad Abbou Azaz]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 09:10:36 GMT</pubDate>
            <atom:updated>2026-08-24T09:29:58.143Z</atom:updated>
            <content:encoded><![CDATA[<p><em>6 questions, 12 attempts, 1 silent fabrication that would have gone straight into a report</em></p><p>This is part 1 of a 6-post series that answers one question: <strong><em>How much context does a model actually need to answer SQL questions correctly?</em></strong></p><p>The idea is simple. I take a real Postgres database — a <strong>property management system</strong> with 613 accommodations, ~6,850 reservations, costs, cancellations — and ask an LLM the same 6 business questions at each level of context. Zero context, then schema descriptions, then business-logic doc blocks, then per-question routing, then real access control. Each post adds one layer, runs the same 6 questions, and measures what changes.</p><p>By post 5, the agent goes from 0/6 to 6/6. Then 6 new questions immediately find 4 more bugs — including a model that silently answers a different question than the one it was asked.</p><p>Everything — database, dbt project, agent code, routing config, every transcript — is open-source. You can reproduce every result in under 5 minutes.</p><h3>Set up the database in 4 commands</h3><p>The repository contains a full property management system: 613 accommodations, ~6,850 reservations, costs, cancellations, occupancy rules — a real schema with real constraints, not a toy dataset.</p><pre>git clone https://github.com/moradabaz/pms-semantic-layer.git<br>cd pms-semantic-layer<br>cp .env.example .env<br>docker compose up -d postgres</pre><p>Then restore the included snapshot instead of waiting for the simulator to generate data:</p><pre>docker cp db_snapshot/pms_snapshot.dump \<br>  $(docker compose ps -q postgres):/tmp/pms_snapshot.dump</pre><pre>docker compose exec postgres pg_restore \<br>  -U pms -d pms --clean --if-exists \<br>  --no-owner --no-privileges /tmp/pms_snapshot.dump</pre><p>Verify it worked:</p><pre>docker compose exec postgres psql -U pms -d pms \<br>  -c &quot;SELECT count(*) FROM accommodation;&quot; -c &quot;\dn&quot;</pre><p>You should see 613 accommodations and three schemas: public, public_staging, public_marts.</p><h3>Run the zero-context experiment</h3><p>Add your OpenAI API key to .env, then:</p><pre>docker compose run --rm agent-demo</pre><p>That runs the exact pipeline described below against the same 6 business questions — your own transcript, your own results. The model is non-deterministic, so your numbers will differ from mine. That’s the point.</p><h3>The Schema</h3><p>Seven tables, real constraints. The ones relevant to this experiment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*tq7yz1Zga2T2swuome9ABQ.png" /></figure><p>reservation.property_manager_id is intentionally denormalized (copied from accommodation.property_manager_id at booking time, not kept in sync by a trigger) — a query-convenience decision made back when this schema was designed, not something the model could infer either way. There&#39;s also a season_calendar reference table (city + accommodation type → high-season months) that feeds one of the harder questions below; it&#39;s matched by value, not a foreign key, so it&#39;s left out of the diagram above.</p><h3>The pipeline</h3><p>Every question goes through the same 4-step pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*sUd2LaCoI-xTkOsKY5x0KA.png" /></figure><p>ask_model sends the question with the one-line system prompt. extract_sql pulls SQL out of the response with two regexes — first a fenced code block, then anything from the first SELECT onward. is_read_only is the safety gate: strip comments, check it starts with SELECT or WITH, verify it&#39;s exactly one statement. Only then does it touch the database, limited to 6 rows via fetchmany(6).</p><p>That safety check had its own bug. The first version rejected several genuinely safe queries — ones where the model had added a comment before the SELECT, or used a WITH CTE. Four of six &quot;failures&quot; in an earlier run were the validator misfiring, not the model. Fixed by stripping SQL comments before validating and accepting WITH as a valid start. A safety check that&#39;s too strict is just as dangerous to experiment integrity as one that&#39;s too loose — it lets you misattribute your own bug to the thing you&#39;re testing.</p><h3>What actually happened</h3><p>In the canonical run, all six questions produced SQL referencing tables that don’t exist in the schema: accommodations, reservations, unit, bookings. The actual tables are accommodation, reservation, property_manager. Postgres rejected every one:</p><pre>Postgres error: relation &quot;reservations&quot; does not exist</pre><p>The model isn’t guessing randomly. It’s pattern-matching against thousands of booking and property-management schemas it saw during training, producing the most statistically plausible table name for the domain — not the one that’s actually true for this database.</p><h4>Two failure modes — only one of them is safe</h4><p>Across both runs (12 questions total), all twelve are hallucinations. The model invented unit the same way it invented 70%. The only difference is whether something downstream caught it.</p><p><strong>Visible hallucination (11 of 12):</strong> wrong table name, Postgres throws an error, someone notices immediately. The system works as a safety net — the failure is loud.</p><p><strong>Silent hallucination (1 of 12):</strong> no query at all. The model was asked “What is the occupancy rate for property manager 9 in August 2026?” and answered:</p><blockquote><em>“The occupancy rate for manager ID 9 in August 2026 is </em><strong><em>70%</em></strong><em>.”</em></blockquote><p>No SQL. No data. No hedge. Seventy percent is a completely believable occupancy rate for a vacation rental in August. Nobody on a finance or ops team would blink at that number, double-check it, or ask where it came from. It would go straight into a report.</p><p>Put two wrong answers side by side: “revenue is 47 billion euros” and “revenue is 18,230 euros.” The first one nobody believes. The second one walks straight into a spreadsheet. The danger was never that the agent gets things wrong — it’s that it can get things wrong in a way that’s indistinguishable from getting them right.</p><h3>What’s next</h3><p>This transcript is the “before.” In post 2, the same 6 questions run against the same database — but this time the model gets the full schema with column descriptions. Every visible hallucination disappears instantly. The silent one takes longer.</p><p>The full repository — database, dbt semantic layer, agent code, routing config, every transcript, every bug with root cause and fix — is at <a href="https://github.com/moradabaz/pms-semantic-layer">github.com/moradabaz/pms-semantic-layer</a>.</p><h3>Takeaways</h3><ul><li><strong>Don’t trust a “reasonable” AI-generated number more than an absurd one.</strong> The absurd one gets caught. The reasonable one is the one that needs checking.</li><li><strong>Never let a model execute anything beyond a single read-only SELECT.</strong> Validate by allowlist (starts with SELECT/WITH, exactly one statement) — not by denylist (doesn&#39;t contain DROP). Denylists are trivial to route around.</li><li><strong>Test your own validator as hard as you test the model.</strong> A safety check that’s too strict silently rejects legitimate queries and makes you misattribute your own bug to the model.</li><li><strong>A refusal is a feature, not a bug.</strong> A model that says “I don’t have enough context” is safer than one that always produces an answer. If your agent never says “I don’t know,” that’s a warning sign.</li><li><strong>Schema context fixes wrong table names. It does not fix a model that skips querying entirely.</strong> Those are two separate problems with two separate fixes — and the second one is what this series is about.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69c38020655c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a CDC-to-Flink Pipeline and Documented Every Decision That Had to Change]]></title>
            <link>https://medium.com/@moradabaz/i-built-a-cdc-to-flink-pipeline-and-documented-every-decision-that-had-to-change-1b60a8e0d1d7?source=rss-126bf1b0d2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b60a8e0d1d7</guid>
            <category><![CDATA[apache-flink]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[streaming-processing]]></category>
            <dc:creator><![CDATA[Morad Abbou Azaz]]></dc:creator>
            <pubDate>Fri, 07 Aug 2026 12:53:05 GMT</pubDate>
            <atom:updated>2026-08-07T12:53:05.103Z</atom:updated>
            <content:encoded><![CDATA[<p><em>8 architecture decisions, 5 Debezium incidents, 3 corrections — and what a streaming pricing engine looks like after all of them</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Kw3ccsC5-k4cPw2TAwJww.png" /></figure><p>The entire project was built with <strong>spec-driven development</strong> — every phase has a written spec before any code, every architecture decision has an ADR, and every incident has a root-cause document. The repository contains 8 ADRs, phase specs, event schema contracts, and an error-handling directory with 5 documented incidents. Three of those ADRs correct earlier ones. The Flink connector the architecture assumed existed turned out not to exist in Flink 2.0. A schema designed for clean JSON turned out to be impossible for Debezium to produce.</p><p>The running pipeline is the proof it works. The spec and ADR trail is the proof someone actually built it.</p><h3>The pipeline</h3><p>A property management company runs ~100 vacation rentals and needs dynamic pricing that accounts for real operational costs — not just market rates. The engine ingests two streams: operational costs via CDC (PostgreSQL → Debezium → Kafka) and market reference prices via Kinesis. Flink joins both, applies a formula that guarantees a minimum margin above cost, and writes pricing decisions to DynamoDB. Iceberg gets the audit trail downstream — not from Flink directly.</p><p>That’s the clean version. Here’s what it took to get there.</p><h3>Five Debezium defaults that will break your pipeline silently</h3><p>Every one of these incidents shared the same trait: the connector reported RUNNING while doing the wrong thing.</p><ul><li><strong>Default key serialization.</strong> Debezium wraps the primary key in a JSON struct by default. Kafka partition assignment and Flink’s keyed state both require <strong>byte-identical keys </strong>for the same logical entity. A struct-wrapped apartment_id and a bare apartment_id produce different bytes. Partition affinity broke — events for the same apartment landed on different partitions, processing out of order. This ran undetected for weeks until an acceptance criterion verified it structurally (group-by-key and count per partition), not by spot-checking individual messages.</li><li><strong>Default topic naming.</strong> Debezium names topics &lt;server&gt;.&lt;schema&gt;.&lt;table&gt;. The Flink consumer expected a different topic name. Both services ran. Both reported healthy. Zero data flowed between them. Diagnosing this required checking the data plane (count messages on the actual topic), not the control plane (connector status endpoint).</li><li><strong>Heartbeat interval disabled by default.</strong> Without heartbeat.interval.ms, a connector watching a quiet table stops advancing its LSN in the WAL. PostgreSQL interprets this as an active consumer and retains WAL segments indefinitely. Disk grows without bound. The connector reports healthy — it&#39;s technically doing nothing wrong, because nothing is happening. But &quot;nothing happening&quot; and &quot;quiet source table&quot; are indistinguishable to a connector without heartbeats.</li><li><strong>Adding a table to a running connector.</strong> After modifying table.include.list to capture a new reference table, the connector started streaming changes from the current LSN. No snapshot of existing rows. The initial snapshot.mode: initial had already completed on startup — adding a table afterward doesn&#39;t re-trigger it. New changes appeared correctly; all history was silently missing.</li><li><strong>Date and decimal wire encoding.</strong> Debezium defaults to base64-encoded byte arrays for decimals and days-since-epoch integers for dates. Both are valid CDC output. Both fail schema validation immediately against any contract expecting JSON numbers and ISO 8601 strings.</li></ul><p>None of these appear in Debezium’s quickstart. The real lesson wasn’t about reading documentation more carefully — it’s that every CDC default is an implicit decision interacting with your schema, your consumer, and your monitoring. Each one needs an acceptance criterion verified on the data plane.</p><h3>Design your CDC schema for what Debezium actually produces</h3><p>The original payment_line.v1 schema had nested objects: supplier: {name, tax_id} and billing_period: {start, end}. Debezium&#39;s ExtractNewRecordState produces flat rows from a relational table. Nested JSON from flat columns requires a custom reshaping stage — a new component purely to preserve a JSON shape.</p><p>The schema also declared additionalProperties: false while the connector was injecting CDC metadata (op, db, table, lsn). Every real message would have failed validation.</p><p>Both problems were resolved in one ADR: <strong>flatten the schema to match what CDC actually produces, strip all metadata from the payload</strong>. The contract test suite includes regression fixtures for the nested shape and the leaked-metadata shape — so a future config change that re-introduces either breaks CI before it reaches a running pipeline.</p><h3>Write your architecture decisions down — especially the wrong ones</h3><p>ADR-0001 established: <em>Kafka for cost events via CDC, Kinesis for market prices. The rationale was sound. The document also stated: “Both are supported by PyFlink 2.x.”</em></p><p><strong>False</strong>. FlinkKinesisConsumer depends on SourceFunction, which Flink 2.0 removed. No Kinesis connector exists on the new Source API. This surfaced at runtime, after three project phases had been built on the assumption.</p><p>A bridge service now reads Kinesis via boto3 and republishes to Kafka. A new ADR documents the correction. The value isn’t the bridge — it’s trivial. The value is that a written, falsifiable claim made the contradiction identifiable by reference instead of by debugging session.</p><p>The same pattern caught the partition key problem. ADR-0001 said both streams would use apartment_id. The market price schema has no apartment_id field — it&#39;s scoped by market segment. Caught at spec review, before any code was written, because the ADR existed as something checkable.</p><h3>Build Flink state by hand before you trust an abstraction</h3><p>This is the core of the project. The pricing engine needs a price per apartment per night. Costs are per apartment (no date). Market prices are per segment per night (no apartment). No shared key. No time alignment. Standard Flink joins — interval, temporal — don’t fit.</p><p>The solution is a KeyedProcessFunction keyed by market segment with two MapState leaves.</p><ul><li>Leaf 1: apartment_id → cost aggregate.</li><li>Leaf 2: target_date → market snapshot.</li></ul><p>A cost event updates Leaf 1 and fans out against every date in Leaf 2. A market event updates Leaf 2 and fans out against every apartment in Leaf 1.</p><p>This cross-product within a segment is the correct business semantics: a new invoice changes the calculation for all future nights of that apartment, and a market move for one night affects every apartment in its segment.</p><p>Built with KeyedProcessFunction instead of Table API — not because Table API can&#39;t express it, but because doing it by hand forces explicit reasoning about what Flink stores, when it emits, and what happens on replay. Table API generates retraction streams that the idempotent DynamoDB sink doesn&#39;t need.</p><p>Three risks were identified in writing before implementation and became actual tested code: stale-event overwrite protection (timestamp comparison before every MapState.put), eviction caps on both leaves (bounded state), and max_parallelism set explicitly to avoid freezing it at an arbitrary value on the first checkpoint — a default that silently limits all future rescaling.</p><h3>Verify with chaos, not just design</h3><p>A docker kill on the Flink TaskManager during active processing confirmed checkpoint restoration: cost_lines_count for a specific apartment continued growing after recovery without resetting or duplicating. The same test on the Iceberg CDC consumer — killed mid-stream, one record written while down, restarted — resumed from its checkpoint with exactly the expected rows. No duplicates. No gaps.</p><h3>Single-writer is not optional</h3><p>The schema says pricing decisions go to DynamoDB and Iceberg. Writing to both from the same Flink job is the dual-write problem from Kleppmann (DDIA, chapter 11): no atomicity between two independent sinks, no way to detect divergence after a partial failure.</p><p>Flink writes to DynamoDB only. Iceberg is populated via DynamoDB Streams CDC. Same pattern as upstream: the application writes to PostgreSQL, Debezium derives Kafka from the WAL. One writer per system, one derived copy. The pattern repeats because the problem repeats.</p><h3>Say what’s missing — it’s a stronger signal than pretending everything works</h3><p><strong>Event-time and watermarks were never used</strong>. Processing-time was correct for this job (no windows to close), but it means zero practice with out-of-order handling or windowed aggregation. Of Flink’s three core primitives — State, Time, Windows — only State and Timers were covered.</p><p>No observability beyond logs and manual checks. Every incident was diagnosed with curl, kcat, and describe-table. The biggest gap against anything resembling production.</p><p>Never tested under real load. 100 apartments, 18 segments, synthetic volume. The hot-shard risk is documented and accepted, not observed.</p><p>A known bug remains unfixed: the cost-side fan-out doesn’t filter past nights. It doesn’t bite in practice, but it’s a latent race condition, deferred on purpose.</p><p>These are gaps, not secrets. A pipeline with 8 ADRs, 5 documented incidents, chaos-verified checkpoints, and an honest list of what’s still missing is a stronger signal than one that claims everything works perfectly.</p><p>Here’s the repository if you want to have a look and the steps and decisions made: <a href="https://github.com/moradabaz/pms-price-engine">https://github.com/moradabaz/pms-price-engine</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b60a8e0d1d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Computer Science Behind Spark Joins]]></title>
            <link>https://medium.com/@moradabaz/the-computer-science-behind-spark-joins-fffe82fd1fd3?source=rss-126bf1b0d2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/fffe82fd1fd3</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[hash-table]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Morad Abbou Azaz]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 10:27:06 GMT</pubDate>
            <atom:updated>2026-08-24T10:22:35.982Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Hash tables, sorting algorithms, and Big-O explain joins and shuffle issues better than any tuning guide</em></p><p><strong>Apache Spark didn’t invent any new data structure or algorithm</strong>, it just the reused the classic ones for the MapReduce. We tend to think of Spark as a high-level engine where we apply transformations to DataFrames. But underneath that abstraction, Spark is a distributed execution engine governed by classical data structures and algorithms.</p><p>Understanding why a join takes seconds or hangs for 45 minutes is not about cloud intuition. It is about algorithmic fundamentals — what happens in memory, network, and CPU when you execute a JOIN.</p><p><strong>Hash tables: the foundation</strong></p><p>Before talking about joins, one concept is essential. A hash table is a data structure that stores key-value pairs and retrieves any value by its key in constant time — <strong>O(1)</strong>. You pass a key through a hash function, it returns an index, and you access the value directly. No scanning, no searching.</p><p>Insert 1 million rows: 1 million operations. Look up any single row: 1 operation, regardless of table size.</p><p>This property is what makes Spark’s first join strategy possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-bfL-L5bUI-eVTOlMPGrQ.png" /></figure><h3><strong>Broadcast Hash Join: linear time, zero shuffle</strong></h3><p>When you join a large fact table (N rows) with a small dimension table (M rows), Spark can use a Broadcast Hash Join:</p><pre>from pyspark.sql.functions import broadcast<br>df_result = df_large.join(broadcast(df_small), &quot;customer_id&quot;)The algorithm has two phases.</pre><p><strong>Build phase — O(M).</strong> The driver reads the small table and sends it over the network to every executor. Each executor builds a HashMap&lt;Key, Row&gt; in its local JVM heap memory. Inserting M elements costs O(M) operations.</p><p><strong>Probe phase — O(N).</strong> Each executor iterates sequentially through its local partition of the large table. For each row, it evaluates the join key against the HashMap. Each lookup is O(1). Doing this N times costs O(N).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*K5wKN63Sx8asOXCpvSc3gg.png" /></figure><p>Total complexity: <strong>O(N + M)</strong>. Linear. No sorting. And critically, no shuffle of the large table — the most expensive operation in distributed computing is eliminated entirely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lU0cYbX3kA1_P0-Pm_dbKg.png" /></figure><p><strong>Why it fails: OOM.</strong> The HashMap must fit entirely in the JVM heap. But a HashMap has overhead — object headers, pointers, hash buckets. A 200 MB CSV can become a 600 MB HashMap in memory. If the executor’s available heap cannot hold the structure, the JVM throws OutOfMemoryError immediately. There is no graceful fallback. The data structure either fits in memory or it does not.</p><h3><strong>Sort-Merge Join: when nothing fits in memory</strong></h3><p>Sort-Merge Join is Spark’s default for a reason:<strong> it cannot run out of memory.</strong> Unlike Broadcast Hash Join, which requires the entire small table to fit in the executor’s heap as a HashMap, Sort-Merge never holds both datasets in memory at once. If a partition exceeds RAM during the sort phase, Spark spills to disk — slower, but it completes. It has three phases, each with distinct algorithmic costs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vieKSo1PSVR3gheqC0fnog.png" /></figure><p><strong>Phase 1: Shuffle — deterministic hash partitioning</strong></p><p>For the join to work, all rows sharing the same key must end up on the same physical machine. Spark applies a deterministic hash function to each join key:</p><pre>Target Partition = hash(key) % num_partitions</pre><p>Every executor reads its local data, computes the target partition for each row, and sends it across the network. This is the Shuffle Write / Shuffle Read phase. Every row moves.</p><p><strong>Phase 2: Sort — O(N log N + M log M)</strong></p><p>Once each executor receives its shuffled partition, it sorts both sides by the join key. The JVM uses TimSort, a comparison-based algorithm with a mathematical lower bound of O(K log K) for K elements. Sorting the left side costs O(N log N). Sorting the right side costs O(M log M).</p><p><strong>Phase 3: Merge — O(N + M)</strong></p><p>With both sides sorted, the executor walks through them using two pointers — the classic merge step:</p><pre>List A (sorted): [ 10,  10,  12,  15 ]<br>                    ↑ (pointer A)<br>List B (sorted): [ 10,  11,  12,  14 ]<br>                    ↑ (pointer B)</pre><p>If key A is less than key B, advance pointer A. If equal, record the match and advance both. This is a single linear pass — O(N + M) — and it only needs to hold the two current elements in memory.</p><p>The complexity calculation is simple:</p><p><strong>Time Complexity </strong>= O(N + M) + <strong>O(N log N + M log M) +</strong> O(N + M)</p><p><strong>Time Complexity = O(N log N + M log M)</strong></p><p><strong>Time Complexity = O(N log N)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*MOnOyFIiXpBiXCNa80HVCQ.png" /></figure><p>For perspective: a naive nested-loop join would cost O(N × M). For two tables of 1 million rows, that is ¹⁰¹² operations. Sort-Merge requires roughly 20 × ¹⁰⁶. That is 50,000 times fewer operations.</p><h4><strong><em>From deterministic hashing to disk spill and timeouts</em></strong></h4><p><strong><em>The algorithm is efficient, So why does your Spark job still hang?</em></strong> Because Big-O measures CPU operations in idealized memory. Production runs on real hardware, and three things break the model.</p><p><strong>Network cost.</strong> The shuffle phase moves terabytes across network interfaces. Big-O says it is O(N) — linear. What it does not capture is that each operation involves serialization, network transfer, deserialization, and disk writes on the receiving end. The constant hidden inside that O(N) can dwarf the sort itself.</p><p><strong>Disk spill.</strong> To sort data in O(N log N), the executor needs the data in memory. When a partition exceeds available RAM, Spark activates External Merge Sort: it writes chunks to local disk, sorts each chunk in memory, then merges the sorted chunks back from disk. Disk I/O is roughly 100x slower than RAM access. The operation count stays O(N log N), but each operation now takes orders of magnitude longer.</p><p><strong>Data Skew — the real killer.</strong> This is where the deterministic nature of the hash function becomes a liability.</p><p>Suppose 70% of your data has a single key value — country = &#39;ES&#39;, or a null join key. Because the hash function is strictly deterministic, it always produces the same result for that value:</p><pre>hash(&#39;ES&#39;) % 30 = 6</pre><p>70% of your entire dataset lands on Partition 6. One executor. One thread.</p><pre>[ SHUFFLE READ ]<br>       │<br>       ├──► Partition 6  (70% data) ──► Executor 1 ──► SATURATED<br>       ├──► Partition 14 (15% data) ──► Executor 2 ──► Done in 10s<br>       └──► Partition 22 (15% data) ──► Executor 3 ──► Done in 10s</pre><p>What follows is a hardware chain reaction:</p><p><strong>Single-thread bottleneck.</strong> Even if Executor 1 has 8 CPU cores, a single partition is processed by a single task on a single thread. 70% of the computation is trapped in one core. The rest of the cluster sits idle.</p><p><strong>RAM exhaustion and disk spill.</strong> The task needs to sort a partition that is 7x larger than expected. The data exceeds the JVM heap. Spark starts spilling to disk — writing intermediate sort results to local storage and reading them back. Performance degrades dramatically.</p><p><strong>GC storms and timeout.</strong> The JVM enters aggressive garbage collection cycles, trying to free heap space. During full GC pauses (Stop-The-World), the Java process halts completely. It stops processing instructions. It stops sending heartbeats to the driver. The driver waits, receives no response, assumes the executor is dead, and kills the task with a spark.network.timeout error.</p><p>Two executors finished in 10 seconds. One executor crashed after 40 minutes. The job fails.</p><h3><strong>What to do before increasing memory</strong></h3><p>Open the Spark UI. Look at the task duration distribution — if one task took 40 minutes and the rest took 30 seconds, you have Data Skew. Look at Shuffle Read/Write — if the volume is disproportionate for one partition, confirm the skewed key. Look at GC time — if an executor spent more time in garbage collection than computation, it ran out of heap.</p><p>The fixes map directly to the algorithms. If one table is small enough, use a Broadcast Hash Join to eliminate the shuffle entirely. If the key distribution is skewed, salt the key — append a random suffix to spread the hot value across multiple partitions. If null keys dominate, filter them before the join or handle them separately.</p><p>The algorithm tells you where to look. The Spark UI tells you what happened. The fix is almost never “more memory.” It is almost always a different approach to the same join.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fffe82fd1fd3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Most Flink Decisions Have Nothing to Do With Flink]]></title>
            <link>https://medium.com/@moradabaz/most-flink-decisions-have-nothing-to-do-with-flink-b524b12326ad?source=rss-126bf1b0d2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/b524b12326ad</guid>
            <category><![CDATA[apache-flink]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Morad Abbou Azaz]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 08:56:49 GMT</pubDate>
            <atom:updated>2026-07-30T10:49:04.163Z</atom:updated>
            <content:encoded><![CDATA[<p>I was building a streaming pricing engine for vacation rental apartments. The system ingests operational costs via CDC from PostgreSQL through Debezium into Kafka, market reference prices through Kinesis, joins both streams in PyFlink, and outputs a recommended price per apartment to DynamoDB (hot path) and Iceberg (audit trail).</p><p>The architecture looks complex. But the hardest decisions in this project had nothing to do with Flink’s API. They happened before I wrote a single line of PyFlink — in the space where the business problem meets the infrastructure constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITJ4TRGXG37RyvxFnQsuKA.png" /></figure><p>Here are the ones that mattered most.</p><h3>The technology was the easy part</h3><p>The PyFlink code for this project is not complex. AI can set it for you. A KeyedCoProcessFunction with two MapState stores, a processing-time timer, and a deterministic pricing formula. The API documentation covers all of it.</p><p>What the documentation doesn’t cover is why MapState instead of windows, why segment instead of apartment_id as the partition key, why processing-time instead of event-time, or why a timer-based dead man&#39;s switch instead of a batch monitoring job.</p><p>Those decisions came from reasoning about the business problem: how costs arrive, how market prices relate to apartments, what “freshness” means in this domain, and what failure modes matter. The technology choice followed naturally once the problem was well understood.</p><p>Every streaming project I’ve seen that struggled wasn’t struggling with Flink or Kafka Streams. It was struggling with a problem that wasn’t well defined before someone started writing KeyedProcessFunction.</p><p>Define the problem first. The framework is the easy part.</p><h3>“I need a window” is the wrong default</h3><p>When you start learning Flink, you reach for window() first. Tumbling, sliding, session — the documentation is full of them.</p><p>My engine aggregates cost lines per apartment (electricity, water, OTA fees) and joins them with market prices. The intuitive design is a tumbling window: “every hour, aggregate costs and recalculate.”</p><p>The problem: cost lines don’t arrive on a schedule. A property manager enters an electricity bill on Tuesday, a water bill on Thursday, an OTA adjustment next Monday. A tumbling window would fire hourly even when nothing changed, or split related entries across two windows for no reason.</p><p>The right abstraction is a MapState keyed by apartment ID that upserts each cost category on arrival and emits an updated aggregate. No window trigger, no time boundary, no edge effects.</p><p>Before reaching for TumblingWindow, ask: does my problem actually have a time boundary? If what you want is &quot;update state when new data arrives,&quot; a window adds complexity without solving anything.</p><h3><strong>The partition key matters more than the process function</strong></h3><p>The cost-market join looked simple: each apartment has costs, each apartment has a market price, join by apartment_id.</p><p>Except market prices come per segment — a neighborhood, property type, star rating. One segment covers dozens of apartments. Key by apartment_id and you need to fan out market prices to every apartment in the segment. Key by segment and the join becomes a 1:1 lookup.</p><p>The Flink code for both approaches is nearly identical. The difference is which key you choose, and that comes from understanding the data’s cardinality, not Flink’s API.</p><p>80% of the join was solved by choosing the right key. 20% was writing the function.</p><h3><strong>Event-time is not always the right choice</strong></h3><p>The streaming orthodoxy: always use event-time. Processing-time is unreliable.</p><p>I chose processing-time. Not out of laziness — because the design has no windows to close.</p><p>Watermarks answer one question: “Have I seen all events up to time T?” This matters when a window needs to know when to fire. My engine uses continuous state updates — when an event arrives, it updates the map and emits a new price. No window to close means no question of completeness.</p><p>Event-time and watermarks solve a real problem, but that problem is “when can I safely close a time-bounded aggregation?” If your design has no time-bounded aggregations, watermarks add configuration overhead — allowed lateness, watermark strategies, idle source handling — without solving anything.</p><p>Ask: do I have windows that need to know when they are complete? If not, processing-time is simpler and sufficient.</p><h3><strong>Watch for silence, not just anomalies</strong></h3><p>If an apartment hasn’t received a cost update in 30 days, something is wrong. Maybe the CDC pipeline broke, maybe the property manager stopped entering data.</p><p>This is a <em>dead man’s switch</em>: the alarm is triggered by something <strong>not</strong> happening. In Flink, it is a processing-time timer on each KeyedProcessFunction. Every cost event resets the timer to &quot;now + 30 days.&quot; If the timer fires, no event arrived — emit a staleness alert.</p><p>Most alerting watches for anomalous events. This watches for the absence of expected events. In a CDC pipeline where the source system sends no heartbeats, it is the only way to distinguish “everything is fine” from “the pipeline is silently broken.”</p><h3><strong>Checkpointing ≠ delivery semantics</strong></h3><p>Kafka’s delivery guarantees (at-least-once, exactly-once) are transport-layer: did the message arrive?</p><p>Flink’s checkpointing is state-management: can I recover my in-progress computation after a crash?</p><p>You can have exactly-once Kafka delivery and still lose state if checkpointing is misconfigured — the events arrived but intermediate computation was lost. Conversely, reliable checkpoints with a non-transactional sink means duplicate writes.</p><p>“We have exactly-once” is a statement about one layer, not the whole pipeline. End-to-end exactly-once requires alignment across source (offsets), processing (checkpoints), and sink (transactional writes).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b524b12326ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Serverless Fails at Stream Processing]]></title>
            <link>https://medium.com/@moradabaz/why-serverless-fails-at-stream-processing-and-what-to-use-instead-cf6935a945c4?source=rss-126bf1b0d2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf6935a945c4</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[apache-flink]]></category>
            <category><![CDATA[spark-streaming]]></category>
            <category><![CDATA[streaming]]></category>
            <dc:creator><![CDATA[Morad Abbou Azaz]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 07:54:05 GMT</pubDate>
            <atom:updated>2026-09-06T14:29:28.202Z</atom:updated>
            <content:encoded><![CDATA[<p>There’s a pattern that works really well for building data lakes on AWS: Kinesis captures events, Lambda processes them, S3 stores them, Glue transforms them, Athena queries them. It’s cheap, it scales, and it barely needs any infrastructure management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Z6K4sftqQhtFNjZzOeNdA.png" /><figcaption>Serverless data architecture in AWS</figcaption></figure><p>The problem shows up the moment someone asks for a real-time metric. “<em>Average order value per hour</em>.” “<em>Fraud detection under 50 milliseconds</em>.” “<em>Alert me when CPU stays above 90% for 10 minutes</em>.” <strong>This architecture can’t produce those numbers, no matter how you configure it.</strong></p><p>The reason is <strong>state</strong>. Understanding why matters, because it’s the difference between building a data lake and building a streaming platform.</p><h3>The state problem in <em>serverless</em></h3><p>Computing anything over time, a moving average, a session duration, a windowed aggregate, requires memory. The system needs to remember what happened in the last 5 minutes, the last hour, the last session.</p><p><strong>Lambda functions or any serverless functions (Azure Functions, Openfaas) are stateless</strong> and short-lived. They spin up, process a batch of events from Kinesis, and terminate. Nothing is shared between invocations. So a Lambda that needs to calculate a 10-minute window only has two options: write every raw event to an external database and query it on every invocation, or read the full historical state from that database, append the new events, recalculate, and write it back.</p><p>At 10,000 events per second, both options melt the database. You’re trading network latency, CPU cycles, and database locks just to “remember” what happened five minutes ago. <strong>The serverless model is optimized for stateless request-response, not for maintaining continuous state over time.</strong></p><h3>How stateful streaming engines solve this</h3><p>Dedicated streaming engines like Apache Flink or Kafka Streams invert the model. Instead of moving data to the query, they keep the query in place and let the data flow through it. Instead of calling out to an external database for state, they embed a fast key-value store, usually RocksDB, directly inside each processing node.</p><p>The architecture looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6qPG2072D0-afD4ZhDX0bQ.png" /></figure><p>During a 1-hour tumbling window, Flink increments a local counter in RocksDB for every incoming event. There are zero network calls to external databases while the window is open. Only when the window closes does it write a single, consolidated result to the reporting layer.</p><p>The database is protected because the heavy lifting happens in local state, not in remote queries.</p><h3>Windows are not in the data — they are design decisions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1dRrjMTp-UOgiU2Ch_n2w.png" /></figure><p>One of the most important insights in Streaming Processing is that windows do not exist in the data stream. Events are a continuous, unbounded flow. A window is an abstraction that the engineer chooses, and that choice determines memory footprint, accuracy, and latency.</p><p><strong>Tumbling windows</strong> are fixed, non-overlapping intervals, every hour from 10:00 to 11:00, for example. They’re predictable and work well for business metrics like hourly sales reports. The downside is the edge effect: a user who acts at 10:59:59 and again at 11:00:01 gets split across two windows, which dilutes the correlation between those two actions.</p><p><strong>Sliding windows</strong> move continuously, “the last 5 minutes, updated every 10 seconds.” They fit monitoring and alerting well, for example triggering an alarm if CPU stays above 90% over the last 10 minutes. The cost is memory: because windows overlap, a single event belongs to multiple active windows at once, so the state gets duplicated.</p><p><strong>Session windows</strong> are defined by user activity rather than fixed time. They open on the first event and close after a configurable gap of inactivity. They fit user behavior analysis well, cart abandonment, session duration, engagement tracking. The cost is complexity: a session can only be closed retrospectively, once the timeout has passed, so the system has to keep state open for every active user in the meantime.</p><p>Each window type is a different answer to the same question: “<em>How much memory am I willing to spend, and how much edge-case accuracy am I willing to sacrifice?</em>”</p><h3>Late events: drop or update</h3><p>Life isn’t perfect, so networks tend to fail, mobile devices lose signal and purchase made at 15:00 in the subway might not reach the server until 15:30. Every streaming system needs a policy for this kind of straggler event.</p><p><strong>Dropping (Discarding)</strong> the event means excluding it from window calculations, while still logging it to a dead letter queue (DLQ) for monitoring and offline reconciliation. This works for non-critical analytical metrics, web click aggregations, page view counts, where a small margin of error is acceptable and reopening a closed window isn’t worth the cost.</p><p><strong>Updating</strong> the event means reopening the closed window, recalculating the aggregate with the late event included, and emitting a correction downstream. This is necessary for financial systems where accuracy isn’t optional, payment processing, driver payouts, billing reconciliation. It costs more: the system has to keep the ability to reopen any window within the allowed lateness threshold, which increases state size and adds complexity downstream.</p><p>This decision isn’t really technical, it’s a business requirement. The engineer’s job is to make the cost of each option visible so the business can choose with that cost in mind.</p><h3>Joins in streaming are memory management problems</h3><p>In batch processing, a join is a SQL statement. In streaming, a join is a commitment to hold data in memory for a defined period. Streams are infinite, so you can’t join “everything.” You have to define how events relate in time, and how much memory you’re willing to allocate to hold them.</p><p><strong>Stream-to-stream joins</strong> correlate two infinite flows of events. The engine keeps events from both streams in a windowed buffer, say 30 minutes, and matches them within that window. Once the window expires, unmatched events get discarded. A practical example is matching ad impressions with subsequent ad clicks to calculate conversion rates. Memory cost scales with window size and the event throughput of both streams.</p><p><strong>Stream-to-table joins</strong> enrich an infinite stream with relatively stable reference data. Rather than querying an external database on every event, which would create the same bottleneck as the Lambda pattern, the engine subscribes to the table’s change log through CDC and keeps a local replica in RocksDB. Every lookup happens locally, at microsecond latency. A practical example is enriching a live credit card transaction stream with user risk profiles. Memory cost equals the full size of the reference table, but latency cost is close to zero.</p><p><strong>Table-to-table joins</strong> maintain a materialized view of two changing datasets. Both tables are stored fully in state. A change on either side triggers an immediate recalculation of the joined result. A practical example is maintaining a user’s social feed by joining a posts table with a followers table. Memory cost is the combined size of both tables, which makes this the most expensive join type of the three.</p><p>Across all three, the pattern is the same: every join trades memory allocation against query latency. The engineer’s job is to pick the join type that fits the business requirement while keeping state size within what the infrastructure can handle.</p><h3>Three questions before you design a streaming system</h3><p>When evaluating whether a use case requires stateful streaming or can be served by a simpler architecture, these are the questions that matter:</p><p><strong>Is this pipeline stateful?</strong> If the use case needs aggregates over time, moving averages, session durations, windowed counts, a stateless architecture like Lambda or micro-batch will end up leaning on an external database for state, and that dependency won’t hold up under load. A dedicated streaming engine with local state is the right tool here.</p><p><strong>What’s the tolerance for late data?</strong> This determines whether you need simple drop-and-log handling or the more complex retract-and-correct logic. The answer comes from the business, not from engineering preference. Make the cost of each option visible before choosing.</p><p><strong>How reliable are the source clocks?</strong> Client device clocks drift, and mobile timestamps are often unreliable. Before trusting event-time windows, it’s worth calculating the offset between the server’s receive time and the device’s send time to calibrate timestamps:</p><pre>Calibrated Event Time = Device Event Time + (Server Receive Time - Device Send Time)</pre><p>If the offset exceeds your window tolerance, your event-time windows will produce incorrect aggregates regardless of how well the rest of the system is designed.</p><h3>The architectural boundary</h3><p>Serverless is excellent at what it was designed for: stateless, event-driven, request-response workloads. Data lake ingestion. API backends. File processing triggers.</p><p>Stateful streaming is a fundamentally different paradigm because It requires persistent local state, continuous processing, and explicit management of time, windows, and late arrivals. Trying to force one paradigm into the other produces a broken one.</p><p>The skill is not knowing how to build either architecture. It’s knowing where the boundary between them falls for a specific use case, and being able to articulate why.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf6935a945c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>