<?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 Micha Gersting on Medium]]></title>
        <description><![CDATA[Stories by Micha Gersting on Medium]]></description>
        <link>https://medium.com/@gerstingmicha?source=rss-494e63d656b5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*P9L-pESOhD7lzJlaThiNDQ.jpeg</url>
            <title>Stories by Micha Gersting on Medium</title>
            <link>https://medium.com/@gerstingmicha?source=rss-494e63d656b5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:27:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gerstingmicha/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[Tuning PostgreSQL in Seven Stages on 41 Million Rows: What Worked and What Did Not]]></title>
            <link>https://medium.com/@gerstingmicha/tuning-postgresql-in-seven-stages-on-41-million-rows-what-worked-and-what-did-not-1960e7cee8fe?source=rss-494e63d656b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1960e7cee8fe</guid>
            <category><![CDATA[database-indexing]]></category>
            <category><![CDATA[clickhouse]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[duckdb]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Micha Gersting]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 10:01:02 GMT</pubDate>
            <atom:updated>2026-11-23T10:01:02.714Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Six queries, three engines, an 8 GB MacBook, and the execution plan behind every number.</em></p><p>Everyone says columnar engines are faster than PostgreSQL for analytics. I wanted to see by how much, and how far careful tuning can close the gap. So I took one year of NYC yellow taxi trips, 41.2 million rows [1], wrote six queries, and ran them on PostgreSQL 17, DuckDB 2.0 and ClickHouse 26.10 on a MacBook with an M1 and 8 GB of RAM. Then I tuned PostgreSQL in seven stages, measured after each one, and saved the plan every time.</p><p>Here is the end result. Times are medians of warm runs, on a log scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQ8Jhxfs8dpyWIYDNXRSGg.png" /></figure><p><em>PostgreSQL baseline, PostgreSQL after tuning, DuckDB and ClickHouse. The full table is in the repository.</em></p><p>Short version: tuning took PostgreSQL from seconds to milliseconds on some queries and did almost nothing for others. DuckDB stayed faster on every query that scans a lot of rows, unless I precomputed the answer. Some of my stages brought nothing measurable, and I left them in the write up on purpose.</p><p>All code, plans and raw measurements are on GitHub: <a href="https://github.com/MGersting111/one-query-three-engines">one-query-three-engines</a>.</p><h3>The six queries</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UiGDSSOqXSGKVCzVpUVmrA.png" /></figure><p>The PostgreSQL baseline has default settings, no indexes and no primary key. Every query is a sequential scan over a 6.7 GB table. Warm runtimes are 6.0 s (Q1), 7.7 s (Q2), 13.5 s (Q3), 9.1 s (Q4), 9.0 s (Q5) and 68 s (Q6).</p><p>Every number in this article comes from five cold and five warm runs per query. “Cold” means the database was restarted, so its own cache is empty. The file cache of the Docker VM survives that, which is why cold and warm are often close.</p><h3>How to read a plan</h3><p>Everything below rests on EXPLAIN (ANALYZE, BUFFERS), so a quick primer. This is a trimmed excerpt from the Q3 baseline:</p><pre>Partial HashAggregate  (cost=2344978.54..2528939.09 rows=822291 width=40)<br>                       (actual time=14446.036..14451.612 rows=168 loops=3)<br>  -&gt; Parallel Seq Scan on trips<br>       (actual time=164.245..11267.836 rows=13723100 loops=3)<br>       Buffers: shared hit=417 read=859711</pre><p>The first parenthesis is what the planner expected, the second is what happened. actual time is first row and last row in milliseconds. When loops is greater than 1, rows and time are averages per loop, so 13.7 million rows times 3 workers is the whole table [2]. Buffers counts 8 kB pages: 859,711 pages read is the entire 6.7 GB.</p><p>Notice rows=822291 against rows=168. The planner expected 822,291 groups and got 168. Keep that in mind for stage 3.</p><h3>The seven stages</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p8weiIVM0QoAKHj_z8loUQ.png" /></figure><p><em>Green means a large gain, yellow a small or unproven one, grey nothing measurable.</em></p><h3>Stage 2: configuration (little)</h3><p>I raised shared_buffers from 128 MB to 1.5 GB, work_mem from 4 MB to 64 MB and the parallel workers per query from 2 to 4. The defaults are documented in [5].</p><p>work_mem fixed a visible problem. In Q5 the hash aggregate spilled: 65 batches and 52 MB written to temporary files. After the change it ran in one batch in memory. The runtime stayed at 10.3 seconds. The spill was about 3 percent of the I/O, and the plan still had to read 6.7 GB.</p><p>shared_buffers did nothing, and the reason is in the source. A large sequential scan does not fill the buffer cache. It uses a ring of 256 kB [3], and PostgreSQL picks that strategy when the table is larger than a quarter of the buffer pool [4]. On the second run I still saw shared hit=348 against roughly 860,000 pages.</p><p>Going from 2 to 4 workers gave a factor of 1.1 to 1.2, not the 2 I had hoped for. My guess is that read throughput limits the scan, not the CPU, but I did not verify that. Two queries even got 14 to 15 percent slower and I do not know why. My machine fluctuates by 15 to 30 percent between runs, which is as large as most effects in this stage. On a server with more memory and cores this stage would matter more. I did not measure that.</p><h3>Stage 3: statistics (better plans, no proven speedup)</h3><p>Back to rows=822291 against rows=168. For GROUP BY on an expression such as extract(hour FROM pickup_at), PostgreSQL has no statistics and falls back to the raw column. For Q5 it estimated 4.1 million groups, the truth is 84,926.</p><p>CREATE STATISTICS accepts expressions, which gives similar benefits to an expression index without the maintenance cost [6]. I created statistics for the three expressions my queries group by. The estimate for Q3 became exact (168), and Q5 improved from a factor of 48 to a factor of 3.</p><p>There is a trap. My first step was only to raise the statistics target for pickup_at, which makes the sample ten times larger. The estimate of distinct timestamps rose from 822,000 to 7.0 million (the truth is 20.0 million). The planner carried that over to the expressions, expected 7 million groups for Q3, and picked a serial plan. In a single EXPLAIN run Q3 went from about 8 seconds to 20.6. Only the expression statistics repaired it.</p><p>Did it make queries faster? I cannot prove it. Q1 was unchanged in this stage and still got 22 percent faster, so I can only call that drift. The benefit here is in the plan. On a table with joins, a wrong estimate decides the join order, and that is where this stage would pay off.</p><h3>Stage 4: indexes (the first big win)</h3><p>Two indexes did most of the work. A B-tree on trip_id (882 MB) turned Q1 from 6 seconds into 0.2 milliseconds, with 8 pages read instead of 860,000.</p><p>The second one is a wide covering index: (pickup_at) INCLUDE (pu_location_id, total_amount). INCLUDE stores extra columns in the index so a query can be answered without visiting the table. This is an index-only scan, and it depends on the visibility map being current, which VACUUM maintains. It only wins if many heap pages are marked all visible [7].</p><p>For Q2 I compared index types in single runs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*A2jD3UCwrIm9tEzU5d4kHQ.png" /></figure><p>BRIN stores a summary per block range of adjacent pages and works when values correlate with the physical row order [8]. My data was loaded sorted by pickup_at, so it fits. It is about 3,000 times smaller than the B-tree and only three times slower than the covering index. For a log or event table that is a good trade.</p><p>I also tried both column orders for a composite index on time and zone. They were equally fast, because fetching 163,000 rows from the table dominated. The order showed up in index pages read, not in seconds.</p><p>For Q3 and Q5 the wide index only gave a factor of 2. The index is 1.6 GB instead of 6.7 GB, but PostgreSQL still processes 41 million rows one at a time. The planner also ignored the index until I lowered random_page_cost from its default of 4.0 [9] to 1.1. That value is my choice for fast storage, not a documented recommendation.</p><p>Cost: 2.5 GB of indexes, 37 percent of the table. I did not measure the cost for writes, since this data is read only.</p><p>One more thing about measuring. While building these indexes the Mac started swapping, and every query became two to three times slower, including ones whose plans had not changed. The numbers in this article come from the run after a reboot.</p><h3>Stage 5: rewriting the query (the cheapest fix)</h3><p>Q6 is written badly on purpose:</p><pre>SELECT d::date AS day,<br>       (SELECT sum(t.total_amount) FROM trips t<br>        WHERE date_trunc(&#39;day&#39;, t.pickup_at) = d) AS revenue<br>FROM generate_series(&#39;2024-03-01&#39;::timestamp, &#39;2024-03-07&#39;::timestamp, interval &#39;1 day&#39;) AS d;</pre><p>date_trunc(...) wraps the column in a function, so no index can narrow the scan. The planner read the whole wide index seven times, 36 seconds. The fix is a range filter:</p><pre>WHERE t.pickup_at &gt;= d AND t.pickup_at &lt; d + interval &#39;1 day&#39;</pre><p>Same result, 0.068 seconds. That is a factor of 530 with no change to the database.</p><p>I also tried replacing the subquery with a LEFT JOIN, because that is the usual advice. It was twice as slow as the fixed subquery: the join first produced 798,861 rows and grouped afterwards, while the subquery aggregates inside each iteration. A correlated subquery is not the problem as long as each iteration can use an index.</p><p>The same original query takes 50 ms in DuckDB. It does not run the subquery per row at all, because DuckDB decorrelates every subquery before execution [12].</p><h3>Stage 6: partitioning (it depends on the index)</h3><p>I split the table into 12 monthly partitions. The size stayed the same, 9.2 GB. Without an index, pruning is dramatic: Q2 read 74,192 pages instead of 859,760 and dropped from 3.7 seconds to 0.33 to 0.57 seconds. Pruning works from the partition key alone, indexes are not needed [10].</p><p>With the indexes from stage 4, Q2 was already at 0.28 seconds, and partitioning changed nothing. It even cost something.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SfyuyshQET17OrncnvR9uQ.png" /></figure><p><em>Q1 filters on </em><em>trip_id, not on the partition key, so all 12 partition indexes are probed.</em></p><p>Q1 got 2.5 times slower (0.2 ms to 0.5 ms). The sargable Q6 got 1.9 times slower, because the planner can only prune at run time there: eleven partitions show up as never executed in the plan. Q3 to Q5 got 8 to 40 percent faster, and the plans show a parallel append across partitions. That may be the reason, but I did not isolate it.</p><p>I did not measure the real benefits of partitioning: dropping an old month instantly and vacuuming per partition. In terms of speed, with good indexes in place, it is not a win.</p><h3>Stage 7: materialized views (fastest, with a catch)</h3><p>For Q3 and Q5 I stored the result of the expensive aggregation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*IqLmlDeqFcC9fonYQfTIbw.png" /></figure><p>The view for Q3 stores the final 168 rows. The view for Q5 stores revenue per day and zone (85,000 rows) and the query still computes the ranking, so it is 60 times slower than the Q3 view but can answer other questions.</p><p>The price is freshness. REFRESH MATERIALIZED VIEW rebuilds everything; it took 2.9 to 4.8 seconds here. CONCURRENTLY keeps the view readable during the refresh but requires a unique index [11]. And the view goes stale: I inserted one test trip in a transaction, and the query saw an average of 30.10 while the view still showed 25.75. Then I rolled back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EEBYfeZGfRrQSvY_S8ndVQ.png" /></figure><p><em>Warm medians per stage on a log scale. Orange is the rewritten query or the materialized view.</em></p><h3>Why DuckDB and ClickHouse still win the scans</h3><p>After all of that, PostgreSQL is 25 to 85 times slower than DuckDB on Q3, Q4 and Q5, unless I precompute. The reason is the storage layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uWoovc0MKcU42Ajx7Sf0CA.png" /></figure><p><em>Simplified. PostgreSQL’s index-only scan is the nearest thing to a column read.</em></p><p>PostgreSQL stores whole rows in pages, so a query that needs two columns still moves all of them through memory. A column store keeps each column separately and reads only the blocks it needs [15]. DuckDB combines this with a vectorized execution engine [13]. My wide covering index was essentially a poor man’s column store, and it bought exactly the factor of 2 I measured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*D0vG3j2-uGRXuoLjIBOshw.png" /></figure><p>The point lookup is the one place where PostgreSQL holds its own: with a B-tree it is about equal to DuckDB. ClickHouse needs 6 ms because I chose (pickup_at, pu_location_id) as its sort key, and its sparse index (one entry per granule of 8,192 rows by default) follows that key [14]. A lookup on trip_id cannot use it. I assume that is the cause, but I did not test another sort key.</p><p>Q4 is the honest loser. A join with aggregation over 41 million rows has no index or view in my setup that helps, and it stayed around 6 seconds.</p><h3>What I would take away</h3><ul><li>Read the plan before you touch a setting. The two biggest wins, an index and an indexable filter, were both visible in the plan within minutes.</li><li>A query that wraps a column in a function throws away the index. Fix the query first.</li><li>Better statistics can make a plan worse if you only fix half of the picture. Check the estimate, not just the runtime.</li><li>Not every stage pays. Configuration, statistics (in seconds) and partitioning (with indexes) brought little here. I would still do the first two on a large server and measure there.</li><li>Precomputation beats everything, and it is the only stage where PostgreSQL won against DuckDB. You trade it for stale data.</li><li>Measure your environment. My laptop fluctuated by 15 to 30 percent, and one bad index build sent it into swap. Without a control query that does not change, I would have believed some numbers I should not have.</li></ul><h3>Limits</h3><p>I used only 2024. The data goes to 2026, but 123 million rows do not fit on this machine. The noise between runs is large, and single EXPLAIN runs are not benchmarks. I did not measure write costs of indexes, partition maintenance, other ClickHouse sort keys or DuckDB tuning, and a bigger machine would change the picture, especially for stage 2.</p><h3>Reproduce it</h3><pre>git clone https://github.com/MGersting111/one-query-three-engines<br>cd one-query-three-engines<br># follow the README: download, prepare, load, then bench/run_stage.sh per stage</pre><p>A one month quick test (3.6 million rows) runs all six queries and all seven stages; I used it to check the repository from a fresh checkout. Every stage folder contains the change as SQL, the reasoning, the numbers and the saved plans.</p><h3>References</h3><ol><li>NYC Taxi and Limousine Commission, TLC Trip Record Data. <a href="https://www.nyc.gov/site/tlc/about/tlc-trip-record-data.page">https://www.nyc.gov/site/tlc/about/tlc-trip-record-data.page</a></li><li>PostgreSQL 17 Documentation, Using EXPLAIN. <a href="https://www.postgresql.org/docs/17/using-explain.html">https://www.postgresql.org/docs/17/using-explain.html</a></li><li>PostgreSQL source, buffer manager README (ring buffer for sequential scans). <a href="https://github.com/postgres/postgres/blob/master/src/backend/storage/buffer/README">https://github.com/postgres/postgres/blob/master/src/backend/storage/buffer/README</a></li><li>PostgreSQL source, heapam.c (bulk read strategy when a table exceeds a quarter of the buffer pool). <a href="https://github.com/postgres/postgres/blob/master/src/backend/access/heap/heapam.c">https://github.com/postgres/postgres/blob/master/src/backend/access/heap/heapam.c</a></li><li>PostgreSQL 17 Documentation, Resource Consumption (shared_buffers, work_mem, hash_mem_multiplier). <a href="https://www.postgresql.org/docs/17/runtime-config-resource.html">https://www.postgresql.org/docs/17/runtime-config-resource.html</a></li><li>PostgreSQL 17 Documentation, CREATE STATISTICS. <a href="https://www.postgresql.org/docs/17/sql-createstatistics.html">https://www.postgresql.org/docs/17/sql-createstatistics.html</a></li><li>PostgreSQL 17 Documentation, Index-Only Scans and Covering Indexes. <a href="https://www.postgresql.org/docs/17/indexes-index-only-scans.html">https://www.postgresql.org/docs/17/indexes-index-only-scans.html</a></li><li>PostgreSQL 17 Documentation, BRIN Indexes. <a href="https://www.postgresql.org/docs/17/brin.html">https://www.postgresql.org/docs/17/brin.html</a></li><li>PostgreSQL 17 Documentation, Planner Cost Constants (random_page_cost). <a href="https://www.postgresql.org/docs/17/runtime-config-query.html">https://www.postgresql.org/docs/17/runtime-config-query.html</a></li><li>PostgreSQL 17 Documentation, Table Partitioning. <a href="https://www.postgresql.org/docs/17/ddl-partitioning.html">https://www.postgresql.org/docs/17/ddl-partitioning.html</a></li><li>PostgreSQL 17 Documentation, REFRESH MATERIALIZED VIEW. <a href="https://www.postgresql.org/docs/17/sql-refreshmaterializedview.html">https://www.postgresql.org/docs/17/sql-refreshmaterializedview.html</a></li><li>DuckDB, Correlated Subqueries in SQL. <a href="https://duckdb.org/2023/05/26/correlated-subqueries-in-sql">https://duckdb.org/2023/05/26/correlated-subqueries-in-sql</a></li><li>DuckDB, Why DuckDB. <a href="https://duckdb.org/why_duckdb">https://duckdb.org/why_duckdb</a></li><li>ClickHouse Documentation, A practical introduction to primary indexes in ClickHouse. <a href="https://clickhouse.com/docs/guides/clickhouse/data-modelling/sparse-primary-indexes">https://clickhouse.com/docs/guides/clickhouse/data-modelling/sparse-primary-indexes</a></li><li>ClickHouse, How columnar storage works. <a href="https://clickhouse.com/resources/engineering/what-is-columnar-storage">https://clickhouse.com/resources/engineering/what-is-columnar-storage</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1960e7cee8fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding LangChain: From Your First Prompt to a Local AI Agent]]></title>
            <link>https://medium.com/@gerstingmicha/understanding-langchain-from-your-first-prompt-to-a-local-ai-agent-caa03d12145c?source=rss-494e63d656b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/caa03d12145c</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Micha Gersting]]></dc:creator>
            <pubDate>Sun, 22 Nov 2026 11:22:50 GMT</pubDate>
            <atom:updated>2026-11-22T11:22:50.262Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What LangChain actually is, why it looks different since version 1.0, and how to build an agent entirely on your laptop in 15 minutes. No API key, no cloud.</em></p><h3>The Problem LangChain Solves</h3><p>A single call to a language model is easy to write. The interesting part comes after: you want reusable prompt templates, the ability to swap models without rewriting half your code, structured outputs, and a way to let the model call your own functions, such as a database query.</p><p>That is where LangChain comes in. It is an open source orchestration framework for building applications on top of large language models (LLMs) [8]. Typical use cases include chatbots, intelligent search, question answering, summarization, and AI agents [8].</p><p>The core idea is <strong>unified interfaces</strong>. A chat model from OpenAI, Anthropic, or a local model via Ollama looks the same in your code. The project now counts more than 700 integrations, which have been split out into their own packages [5].</p><h3>LangChain 1.0: What Changed</h3><p>If you tried LangChain a couple of years ago, you may remember countless chain classes and confusing import paths. That is history.</p><p>In October 2025, LangChain 1.0 and LangGraph 1.0 shipped as the first stable major versions [1][10]. With it, the team committed to no breaking changes until 2.0 [3]. The three core improvements are [2]:</p><ul><li><strong>create_agent</strong> as the standard way to build agents. It replaces the former create_react_agent from LangGraph [9].</li><li><strong>Standard content blocks</strong>, giving unified access to response content regardless of the provider behind it.</li><li><strong>A streamlined namespace</strong> focused on the building blocks for agents.</li></ul><p>Legacy pieces such as old chains, the hub module, and the indexing API moved to the separate langchain-classic package [2]. Existing code keeps working if you install it.</p><h3>How LangChain, LangGraph, and Deep Agents Fit Together</h3><p>The names sound like competing products, but they are layers stacked on top of each other. Each layer uses the one below it [4][5]:</p><p><strong>The LangChain ecosystem as a stack of layers:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNaqMGb4TqtxmxwRWFjj6g.png" /></figure><p>Read the diagram from the bottom up:</p><ul><li><strong>LangGraph</strong> is the engine. It runs the agent loop (ask the model, call a tool, ask again), keeps track of the conversation state, and can pause and resume a run. You rarely touch it directly at first.</li><li><strong>LangChain</strong> sits on top and is what you write code against. create_agent, ChatOllama, and @tool all live here. When you call create_agent, LangChain builds a LangGraph graph for you behind the scenes [9].</li><li><strong>Deep Agents</strong> is an optional layer above that. It adds ready-made behavior like planning a task, spawning subagents, and a virtual filesystem, useful for long jobs like research or coding [4].</li><li><strong>LangSmith</strong> is not a layer but an observer. It records what happens in every layer so you can see each model call and tool call afterwards.</li></ul><p>The higher you go, the more comes built in. The lower you go, the more control you get. <strong>Start with LangChain</strong>, which is what this article does. Only move down to LangGraph when you need custom flows, such as a fixed sequence of steps where only one step is decided by the model [4].</p><h3>The Three Building Blocks</h3><p>Before writing code, here are the three concepts that cover 80 percent of use cases:</p><ol><li><strong>Chat models</strong>: An object like ChatOllama or ChatOpenAI with a unified .invoke() method.</li><li><strong>Prompts and chains</strong>: Templates with placeholders, composed with model and output parser using the pipe operator |. The result is a &quot;Runnable&quot; you can call like a function.</li><li><strong>Agents and tools</strong>: An agent is a loop. The model decides whether to call a tool, receives the result, and decides again until it can answer. create_agent runs this loop for you [1].</li></ol><h3>Hands On: Everything Local with Ollama</h3><p>For this example you do not need an API key. We use <strong>Ollama</strong>, which runs open source models locally [7]. The integration lives in the langchain-ollama package [6].</p><h3>Step 0: Setup</h3><p>Install Ollama from <a href="https://ollama.com/">ollama.com</a> and pull a small model that supports tool calling:</p><pre>ollama pull llama3.2</pre><p>Then the Python packages:</p><pre>python -m venv .venv &amp;&amp; source .venv/bin/activate<br>pip install -U langchain langchain-ollama</pre><p>Important: the model tag in ollama pull must match the one in ChatOllama(model=...) exactly [6]. Run ollama list to see what is installed.</p><h3>Step 1: Call the Model Directly</h3><pre>from langchain_ollama import ChatOllama<br><br>llm = ChatOllama(model=&quot;llama3.2&quot;, temperature=0)<br>response = llm.invoke(&quot;Explain in one sentence what a data warehouse is.&quot;)<br>print(response.content)</pre><p>The result is not a string but an AIMessage object, with the text in .content. That sounds clunky, but it pays off: metadata such as token usage or tool calls live on the same object.</p><h3>Step 2: A Reusable Chain</h3><p>Instead of building prompts with f-strings, we define a template and compose it:</p><pre>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br><br>prompt = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, &quot;You are a concise tech explainer. Answer in at most three sentences.&quot;),<br>    (&quot;human&quot;, &quot;Explain {topic} for {audience}.&quot;),<br>])<br>chain = prompt | llm | StrOutputParser()<br>print(chain.invoke({&quot;topic&quot;: &quot;Apache Kafka&quot;, &quot;audience&quot;: &quot;marketing colleagues&quot;}))</pre><p>The pipe operator reads like a Unix command: fill the template, pass it to the model, extract the answer as a string. The chain automatically gets .batch() for multiple inputs and .stream() for token by token output.</p><p>A nice side effect: if you later want a cloud model, you only swap the llm = ... line. Prompt and parser stay the same.</p><h3>Step 3: An Agent with a Custom Tool</h3><p>Now it gets interesting. We give the model a Python function it may call on its own:</p><pre>from langchain.agents import create_agent<br>from langchain.tools import tool<br><br>@tool<br>def get_stock_level(product: str) -&gt; str:<br>    &quot;&quot;&quot;Return the current stock level for a product.&quot;&quot;&quot;<br>    inventory = {&quot;coffee&quot;: 42, &quot;tea&quot;: 7, &quot;cocoa&quot;: 0}<br>    quantity = inventory.get(product.lower())<br>    if quantity is None:<br>        return f&quot;Product &#39;{product}&#39; is not in the system.&quot;<br>    return f&quot;{product}: {quantity} units in stock&quot;<br>agent = create_agent(<br>    model=llm,<br>    tools=[get_stock_level],<br>    system_prompt=&quot;You are a warehouse assistant. Use the tool to look up stock levels.&quot;,<br>)<br>result = agent.invoke({<br>    &quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;How much tea and cocoa do we have left?&quot;}]<br>})<br>for message in result[&quot;messages&quot;]:<br>    message.pretty_print()</pre><p>What is happening here?</p><ul><li>The @tool decorator turns the function into a tool. <strong>The docstring is not optional</strong>: it is the description the model uses to decide when to call the tool.</li><li>create_agent builds the agent loop, which runs on LangGraph internally [1][9].</li><li>pretty_print() shows the full trace: the user question, the model&#39;s tool calls (probably two, one for tea and one for cocoa), the tool responses, and the final answer.</li></ul><p>A typical (shortened) output looks like this:</p><pre>================================ Human Message =================================<br>How much tea and cocoa do we have left?<br>================================== Ai Message ==================================<br>Tool Calls:<br>  get_stock_level (call_1)  Args: product: tea<br>  get_stock_level (call_2)  Args: product: cocoa<br>================================= Tool Message =================================<br>tea: 7 units in stock<br>================================= Tool Message =================================<br>cocoa: 0 units in stock<br>================================== Ai Message ==================================<br>We have 7 units of tea left. Cocoa is currently out of stock.</pre><p>The exact wording depends on the model. Small local models like the 3 billion parameter llama3.2 occasionally stumble over tool calls on more complex tasks. If your machine can handle it, a larger model is worth trying.</p><h3>Where to Go Next</h3><p>With these three steps you have the fundamentals. Natural next topics:</p><ul><li><strong>Middleware</strong>: Since 1.0 you can hook into the agent loop, for example to summarize long histories, redact sensitive data, or require human approval before certain tool calls [2].</li><li><strong>Structured output</strong>: Pass a Pydantic model as response_format to get validated objects instead of free text [1][2].</li><li><strong>RAG</strong>: With OllamaEmbeddings [7] and a vector store you can make your own documents searchable, still fully local.</li><li><strong>LangGraph</strong>: Once you need branching, recovery after failures, or multiple agents.</li></ul><h3>Conclusion</h3><p>With version 1.0, LangChain cleaned up its sprawl. Instead of dozens of chain variants there is now one clear path: pick a model, define tools as Python functions, call create_agent. Combined with Ollama it makes an ideal playground: free, privacy friendly, and close enough to production code that you only have to change one line later.</p><h3>References</h3><p>[1] LangChain Blog: LangChain and LangGraph Agent Frameworks Reach v1.0 Milestones. <a href="https://www.langchain.com/blog/langchain-langgraph-1dot0">https://www.langchain.com/blog/langchain-langgraph-1dot0</a></p><p>[2] LangChain Docs: What’s new in LangChain v1 (Python). <a href="https://docs.langchain.com/oss/python/releases/langchain-v1">https://docs.langchain.com/oss/python/releases/langchain-v1</a></p><p>[3] LangChain Changelog: LangChain 1.0 now generally available. <a href="https://changelog.langchain.com/announcements/ann_j9EkbzqXXeNod">https://changelog.langchain.com/announcements/ann_j9EkbzqXXeNod</a></p><p>[4] LangChain Docs: LangChain overview. <a href="https://docs.langchain.com/oss/python/langchain/overview">https://docs.langchain.com/oss/python/langchain/overview</a></p><p>[5] LangChain Docs: Philosophy. <a href="https://docs.langchain.com/oss/javascript/langchain/philosophy">https://docs.langchain.com/oss/javascript/langchain/philosophy</a></p><p>[6] LangChain Docs: ChatOllama integration. <a href="https://docs.langchain.com/oss/integrations/chat/ollama">https://docs.langchain.com/oss/integrations/chat/ollama</a></p><p>[7] PyPI: langchain-ollama. <a href="https://pypi.org/project/langchain-ollama">https://pypi.org/project/langchain-ollama</a></p><p>[8] IBM Think: What is LangChain? <a href="https://www.ibm.com/think/topics/langchain">https://www.ibm.com/think/topics/langchain</a></p><p>[9] LangChain Docs: What’s new in LangGraph v1. <a href="https://docs.langchain.com/oss/python/releases/langgraph-v1">https://docs.langchain.com/oss/python/releases/langgraph-v1</a></p><p>[10] @IT (ITmedia): LangChain &amp; LangGraph 1.0 official release (in Japanese). <a href="https://atmarkit.itmedia.co.jp/ait/articles/2510/30/news013.html">https://atmarkit.itmedia.co.jp/ait/articles/2510/30/news013.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=caa03d12145c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform for Beginners: A Handson Explanation]]></title>
            <link>https://medium.com/@gerstingmicha/terraform-for-beginners-a-handson-explanation-054133a0162c?source=rss-494e63d656b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/054133a0162c</guid>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Micha Gersting]]></dc:creator>
            <pubDate>Sat, 21 Nov 2026 15:49:25 GMT</pubDate>
            <atom:updated>2026-11-21T15:49:25.355Z</atom:updated>
            <content:encoded><![CDATA[<p>From “click around in the cloud portal” to infrastructure you can review, version and rebuild with one command. Includes a hands-on first project you can run on your laptop.</p><h3>The problem: infrastructure by clicking</h3><p>Picture a typical data project. You need a resource group, a storage account for your data lake, a key vault for secrets, maybe a Databricks workspace. The quickest way is to open the Azure portal and click through a few wizards. Done in twenty minutes.</p><p>Three months later the problems show up:</p><ul><li>Nobody remembers which settings were chosen, or why.</li><li>The test environment looks “almost” like production, and that “almost” causes bugs.</li><li>A colleague changed a firewall rule by hand, and nobody noticed.</li><li>Rebuilding the setup for a new customer means doing all the clicking again.</li></ul><p><strong>Infrastructure as Code (IaC)</strong> solves this by describing infrastructure in text files that live in Git, just like application code. Terraform is one of the most popular tools for doing exactly that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*u1DvBXwL8MvVt_r8D0llJA.png" /></figure><h3>1. What is Terraform?</h3><p>HashiCorp, the company behind it, describes Terraform as an infrastructure as code tool for building, changing and versioning both cloud and on premises resources. You describe those resources in human readable configuration files that you can version, reuse and share [1]. The language is called <strong>HCL</strong> (HashiCorp Configuration Language).</p><p>Three ideas make Terraform what it is:</p><p><strong>1. It is declarative.</strong> You do not write steps like “create a VM, then attach a disk”. You describe the end state you want, and Terraform works out how to get there [1]. If the VM already exists, nothing happens. If the disk is missing, only the disk gets created.</p><p><strong>2. It talks to everything through APIs.</strong> Terraform itself knows nothing about Azure or AWS. It uses <strong>providers</strong>, plugins that translate your configuration into API calls for a specific platform. HashiCorp and the community have written thousands of them, covering AWS, Azure, Google Cloud, Kubernetes, GitHub, Datadog and many more, and they are published on the Terraform Registry [1]. That means one tool and one workflow can manage low level things like networks and storage, as well as higher level things like DNS records or SaaS settings [1].</p><p><strong>3. It always shows you a plan first.</strong> Before changing anything, Terraform shows what it will create, update or destroy and waits for your approval [1]. This is the feature that makes infrastructure changes reviewable.</p><h3>2. What can you do with it?</h3><p>Some of the most common use cases, as described in the official documentation: <a href="https://developer.hashicorp.com/terraform/intro/use-cases">https://developer.hashicorp.com/terraform/intro/use-cases</a></p><ul><li><strong>Provision cloud environments reproducibly.</strong> Networks, servers, databases, containers and observability services, all from configuration files [2]. Need a second environment for testing? Same code, different variables.</li><li><strong>Multi cloud setups.</strong> Every cloud has its own consoles and tools. Terraform lets you use one workflow across providers and even handle dependencies that span clouds [2].</li><li><strong>Multi tier applications.</strong> Terraform manages the resources of each tier together and handles the ordering between them, for example creating the database before the web servers that depend on it [2].</li><li><strong>Self service for product teams.</strong> A platform team publishes reusable building blocks (modules), and product teams use them to manage their own infrastructure independently [2].</li><li><strong>Kubernetes.</strong> Terraform can deploy a cluster and also manage resources inside it [2].</li><li><strong>Guardrails and policy.</strong> Restricting which resource types teams are allowed to provision, for example with policy as code tools [2].</li></ul><p>For data engineers specifically, the typical use is a <strong>data platform landing zone</strong>: storage accounts or buckets for the lake, key vaults, service principals and role assignments, Databricks or Synapse workspaces, and the networking around them. Writing these once as code and rolling them out per environment or per customer is where Terraform pays off fastest.</p><h3>3. How it works, in one picture</h3><p>You only need three concepts to understand almost everything Terraform does:</p><ul><li><strong>Configuration</strong> (*.tf files): what you <em>want</em>.</li><li><strong>State</strong> (terraform.tfstate): what Terraform <em>remembers</em> it created, mapping each block in your code to a real object in the cloud [3].</li><li><strong>Reality</strong>: what actually exists, which Terraform reads through the providers.</li></ul><p>Terraform Core reads your configuration, compares it with the state and with reality, and asks the providers to make the necessary API calls. Providers run as separate plugin processes that Core talks to over RPC [4].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*BDJGH-pIUQOqsJh7eaVfjA.png" /></figure><p>Day to day, you work in a simple loop: <strong>Write</strong> your configuration, <strong>Plan</strong> to preview changes, <strong>Apply</strong> to make them real, then start over for the next change [5]. Before the first plan, terraform init downloads the providers your project needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*Zr5zRpkTiKTg6QUDNGZpqA.png" /></figure><h3>4. Hands-on: your first Terraform project</h3><p>The fastest way to understand Terraform is to use it. This example follows HashiCorp’s own getting started tutorial and uses <strong>Docker</strong> as the “cloud”, so you need no cloud account and it costs nothing [7]. All you need is Docker installed and running.</p><h3>Step 1: Install Terraform</h3><p>Terraform is a single command line executable for Windows, macOS and Linux [6]. On macOS with Homebrew:</p><pre>brew tap hashicorp/tap<br>brew install hashicorp/tap/terraform</pre><p>On Ubuntu or Debian, add HashiCorp’s apt repository and run sudo apt install terraform (the exact repository commands are in the official install guide [8]). On Windows, download the binary from the install page or use a package manager. Then check:</p><pre>terraform -version</pre><h3>Step 2: Write the configuration</h3><p>Create a folder and a file called main.tf:</p><pre>mkdir learn-terraform-docker &amp;&amp; cd learn-terraform-docker</pre><pre>terraform {<br>  required_providers {<br>    docker = {<br>      source  = &quot;kreuzwerker/docker&quot;<br>      version = &quot;~&gt; 4.2.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;docker&quot; {}<br>resource &quot;docker_image&quot; &quot;nginx&quot; {<br>  name         = &quot;nginx:latest&quot;<br>  keep_locally = false<br>}<br>resource &quot;docker_container&quot; &quot;nginx&quot; {<br>  image = docker_image.nginx.image_id<br>  name  = &quot;tutorial&quot;<br>  ports {<br>    internal = 80<br>    external = 8000<br>  }<br>}</pre><p>This is the configuration from HashiCorp’s tutorial [7]. On Windows, the provider block needs host = &quot;npipe:////.//pipe//docker_engine&quot; [7].</p><p>Reading it from top to bottom:</p><ul><li>The terraform block declares which <strong>provider</strong> we need and which version range is acceptable.</li><li>The provider block configures it (here, the defaults are fine).</li><li>Two resource blocks describe what we want: an nginx image and a container running it, with port 8000 on your machine mapped to port 80 in the container.</li></ul><p>Notice that the container refers to docker_image.nginx.image_id. That reference is how Terraform knows it has to pull the image <em>before</em> starting the container. You never specify the order yourself.</p><h3>Step 3: Initialize</h3><pre>terraform init</pre><p>This downloads the Docker provider and creates a .terraform.lock.hcl file that pins the exact provider version [7]. Commit the lock file to Git; it ensures everyone on the team uses the same provider build.</p><h3>Step 4: Format and validate</h3><pre>terraform fmt<br>terraform validate</pre><p>fmt normalizes the formatting, and validate checks the syntax and internal consistency of your configuration [7]. Both are worth running in CI on every pull request.</p><h3>Step 5: Plan</h3><pre>terraform plan</pre><p>Terraform compares your configuration with the (still empty) state and prints a plan: two resources to add. Nothing has been created yet. plan never changes real infrastructure; it only describes what would happen [9].</p><h3>Step 6: Apply</h3><pre>terraform apply</pre><p>Terraform shows the plan again and asks for confirmation. Type yes. A few seconds later, open http://localhost:8000 and you will see the nginx welcome page.</p><h3>Step 7: Inspect what Terraform knows</h3><pre>terraform show<br>terraform state list</pre><p>terraform show prints the current state, and terraform state list lists the managed resources, here docker_container.nginx and docker_image.nginx [7]. This state is Terraform&#39;s memory. Without it, Terraform could not tell which container on your machine belongs to this configuration [3].</p><h3>Step 8: Change something</h3><p>Change external = 8000 to external = 8080 and run terraform apply again. The plan now shows that the container has to be <strong>replaced</strong>, because a running container&#39;s port mapping cannot be changed in place. Terraform figures this out for you. Run apply, confirm, and the site moves to port 8080.</p><p>This is the core habit to build: <strong>change the code, read the plan, then apply.</strong> Never change managed resources by hand.</p><h3>Step 9: Clean up</h3><pre>terraform destroy</pre><p>This removes everything the configuration manages. Conceptually it is the same as deleting every resource block and running apply, just without editing the files [9].</p><h3>5. The next step: a real cloud</h3><p>Moving to Azure, AWS or GCP changes the provider, not the workflow. Here is a small data platform landing zone on Azure, now using <strong>variables</strong> and <strong>outputs</strong>:</p><pre>terraform {<br>  required_providers {<br>    azurerm = {<br>      source  = &quot;hashicorp/azurerm&quot;<br>      version = &quot;~&gt; 4.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;azurerm&quot; {<br>  features {}<br>}<br>variable &quot;env&quot; {<br>  type    = string<br>  default = &quot;dev&quot;<br>}<br>resource &quot;azurerm_resource_group&quot; &quot;data&quot; {<br>  name     = &quot;rg-data-${var.env}&quot;<br>  location = &quot;westeurope&quot;<br>}<br>resource &quot;azurerm_storage_account&quot; &quot;lake&quot; {<br>  name                     = &quot;stlake${var.env}01&quot;<br>  resource_group_name      = azurerm_resource_group.data.name<br>  location                 = azurerm_resource_group.data.location<br>  account_tier             = &quot;Standard&quot;<br>  account_replication_type = &quot;LRS&quot;<br>  is_hns_enabled           = true # ADLS Gen2<br>}<br>resource &quot;azurerm_storage_container&quot; &quot;bronze&quot; {<br>  name               = &quot;bronze&quot;<br>  storage_account_id = azurerm_storage_account.lake.id<br>}<br>output &quot;lake_name&quot; {<br>  value = azurerm_storage_account.lake.name<br>}</pre><p>Log in with az login, then run the same commands as before. To create a production copy, you only change a variable:</p><pre>terraform apply -var=&quot;env=prod&quot;</pre><p>(In practice you would keep separate state per environment, more on that below.)</p><p>Again, there is no explicit ordering. Terraform builds a <strong>dependency graph</strong> from the references: the resource group comes first, then the storage account, then the container. Resources that do not depend on each other are created in parallel, by default up to 10 at a time [10].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*Ql-PL6tVV57aC1-1q_uNYA.png" /></figure><h3>6. Working in a team: the rules that save you</h3><p>The hands-on example stored state in a local file. That is fine for learning but breaks in a team, because everyone would need the latest file and nobody could run Terraform at the same time [12]. The essentials:</p><ul><li><strong>Use a remote backend.</strong> Store state in shared storage, for example an Azure Storage blob or an S3 bucket [12]. The Azure backend supports locking through native Blob Storage capabilities [13], and on AWS the S3 backend locks natively with use_lockfile = true [14].</li><li><strong>Enable locking.</strong> Locking prevents two concurrent runs from corrupting the same state [12].</li><li><strong>Treat state as a secret.</strong> It is stored in plain text and can contain sensitive values [15].</li><li><strong>Watch for drift.</strong> If someone changes a resource by hand, terraform plan -refresh-only shows how reality differs from the state without proposing any changes to your infrastructure [16].</li><li><strong>Apply from CI.</strong> Run plan on every pull request, review it like a code diff, and apply only from the pipeline.</li></ul><h3>7. Terraform or OpenTofu?</h3><p>You will run into the name <strong>OpenTofu</strong> sooner or later. In 2023 HashiCorp moved Terraform from the open source Mozilla Public License to the Business Source License. Several companies then forked the last open source version, and the Linux Foundation launched it as OpenTofu in September 2023 [17]. OpenTofu aims to stay compatible with Terraform’s language and providers, so everything in this article applies to both. Meanwhile IBM completed its acquisition of HashiCorp in February 2025 [18].</p><p>For learning, it does not matter which you pick. For a company, it is mostly a licensing and governance decision.</p><h3>Key takeaways</h3><ul><li><strong>What:</strong> Terraform is an infrastructure as code tool. You describe the desired state of your infrastructure in HCL files and Terraform makes reality match.</li><li><strong>Why:</strong> reproducible environments, reviewable changes, everything in Git, one workflow for every cloud and many SaaS tools.</li><li><strong>How:</strong> init once, then loop through write, plan, apply. Read every plan before you approve it.</li><li><strong>Remember:</strong> state is Terraform’s memory. In a team, keep it remote, locked and protected.</li></ul><p>A good next step: take something you once clicked together in a cloud portal and rebuild it in Terraform.</p><h3>References</h3><p>[1] HashiCorp, <em>What is Terraform?</em> <a href="https://developer.hashicorp.com/terraform/intro">https://developer.hashicorp.com/terraform/intro</a></p><p>[2] HashiCorp, <em>Terraform Use Cases</em>. <a href="https://developer.hashicorp.com/terraform/intro/use-cases">https://developer.hashicorp.com/terraform/intro/use-cases</a> (see also <a href="https://docs.hashicorp.com/terraform/intro/v1.13.x/use-cases">https://docs.hashicorp.com/terraform/intro/v1.13.x/use-cases</a>)</p><p>[3] HashiCorp, <em>Purpose of Terraform State</em>. <a href="https://developer.hashicorp.com/terraform/language/v1.14.x/state/purpose">https://developer.hashicorp.com/terraform/language/v1.14.x/state/purpose</a></p><p>[4] HashiCorp, <em>How Terraform works with plugins</em>. <a href="https://developer.hashicorp.com/terraform/plugin/how-terraform-works">https://developer.hashicorp.com/terraform/plugin/how-terraform-works</a></p><p>[5] HashiCorp, <em>Core Terraform Workflow Overview</em>. <a href="https://developer.hashicorp.com/terraform/intro/core-workflow">https://developer.hashicorp.com/terraform/intro/core-workflow</a></p><p>[6] HashiCorp, <em>Install Terraform</em> (tutorial). <a href="https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli">https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli</a></p><p>[7] HashiCorp, <em>Build infrastructure</em> (Docker get started tutorial). <a href="https://developer.hashicorp.com/terraform/tutorials/docker-get-started/docker-build">https://developer.hashicorp.com/terraform/tutorials/docker-get-started/docker-build</a></p><p>[8] HashiCorp, <em>Install Terraform</em> (package managers). <a href="https://developer.hashicorp.com/terraform/cli/install/apt">https://developer.hashicorp.com/terraform/cli/install/apt</a></p><p>[9] HashiCorp, <em>Terraform workflow for provisioning infrastructure</em>. <a href="https://developer.hashicorp.com/terraform/cli/run">https://developer.hashicorp.com/terraform/cli/run</a></p><p>[10] HashiCorp, <em>Resource Graph</em> (Terraform internals). <a href="https://developer.hashicorp.com/terraform/internals/v1.8.x/graph">https://developer.hashicorp.com/terraform/internals/v1.8.x/graph</a> and <a href="https://developer.hashicorp.com/terraform/internals/v1.7.x/graph">https://developer.hashicorp.com/terraform/internals/v1.7.x/graph</a></p><p>[11] HashiCorp, <em>Modules overview</em>. <a href="https://developer.hashicorp.com/terraform/docs/language/modules">https://developer.hashicorp.com/terraform/docs/language/modules</a></p><p>[12] HashiCorp, <em>Remote State</em> and <em>State Storage and Locking</em>. <a href="https://developer.hashicorp.com/terraform/language/state/remote">https://developer.hashicorp.com/terraform/language/state/remote</a> and <a href="https://developer.hashicorp.com/terraform/language/state/backends">https://developer.hashicorp.com/terraform/language/state/backends</a></p><p>[13] HashiCorp, <em>azurerm backend</em>. <a href="https://developer.hashicorp.com/terraform/docs/backends/types/azurerm">https://developer.hashicorp.com/terraform/docs/backends/types/azurerm</a></p><p>[14] HashiCorp, <em>Upgrading to Terraform v1.11</em> (S3 native state locking). <a href="https://developer.hashicorp.com/terraform/language/v1.11.x/upgrade-guides">https://developer.hashicorp.com/terraform/language/v1.11.x/upgrade-guides</a></p><p>[15] Microsoft Learn, <em>Store Terraform state in Azure Storage</em>. <a href="https://docs.microsoft.com/en-us/azure/terraform/terraform-backend">https://docs.microsoft.com/en-us/azure/terraform/terraform-backend</a></p><p>[16] HashiCorp, <em>Manage resource drift</em> (tutorial). <a href="https://developer.hashicorp.com/terraform/tutorials/state/resource-drift">https://developer.hashicorp.com/terraform/tutorials/state/resource-drift</a></p><p>[17] Linux Foundation, <em>Linux Foundation Launches OpenTofu: A New Open Source Alternative to Terraform</em> (Sep 20, 2023). <a href="https://www.linuxfoundation.org/press/announcing-opentofu">https://www.linuxfoundation.org/press/announcing-opentofu</a></p><p>[18] IBM Newsroom, <em>IBM Completes Acquisition of HashiCorp</em> (Feb 27, 2025). <a href="https://newsroom.ibm.com/2025-02-27-ibm-completes-acquisition-of-hashicorp,-creates-comprehensive,-end-to-end-hybrid-cloud-platform">https://newsroom.ibm.com/2025-02-27-ibm-completes-acquisition-of-hashicorp,-creates-comprehensive,-end-to-end-hybrid-cloud-platform</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=054133a0162c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Slowly Changing Dimensions: Why Your Dimension Tables Need a Memory]]></title>
            <link>https://medium.com/@gerstingmicha/slowly-changing-dimensions-why-your-dimension-tables-need-a-memory-ca86ec5feb5b?source=rss-494e63d656b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca86ec5feb5b</guid>
            <category><![CDATA[scd]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[change-data-capture]]></category>
            <category><![CDATA[slowly-changing-dimension]]></category>
            <dc:creator><![CDATA[Micha Gersting]]></dc:creator>
            <pubDate>Sat, 25 Jul 2026 18:00:30 GMT</pubDate>
            <atom:updated>2026-07-25T18:00:30.015Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical guide to SCD Types 0 through 6, and how to actually build them in a modern warehouse</h4><p>Every data warehouse eventually runs into the same uncomfortable question: a customer moves cities, a product changes category, an employee switches departments. Do you overwrite the old value and move on, or do you keep a record of what used to be true?</p><p>This is the problem that Slowly Changing Dimensions (SCD) were built to solve. Ralph Kimball introduced the concept in 1996 as part of his dimensional modeling approach, and in more than three decades of studying the problem he concluded that a data warehouse really only needs a handful of standard responses to a changed dimension record [1][2]. Those responses are numbered, somewhat unglamorously, Type 0 through Type 7. This article walks through what each one actually means, when to reach for it, and how it gets implemented in a tool like dbt on a warehouse like BigQuery or Snowflake.</p><h3>What “slowly changing” actually means</h3><p>In a star schema, fact tables record events (an order, a click, a payment) and dimension tables describe the things involved in those events (a customer, a product, a store) [7]. Facts change constantly and predictably, arriving as a continuous stream of new rows. Dimension attributes change too, but rarely and unpredictably: a customer’s address doesn’t update every day, but it does update eventually [2].</p><p>The core design question for every attribute in a dimension table is: when it changes, should the warehouse forget the old value, keep it around, or do a bit of both? Kimball’s numbered types are really just three basic answers (overwrite, add a row, add a column) plus a handful of hybrids built by combining them [4][6].</p><h3>SCD Type 0: Fixed, never changes</h3><p>Some attributes should never be updated no matter what happens upstream, for example a date of birth or an original signup date. Type 0 simply means the value is locked at insert time and the ETL process is not allowed to touch it again [6].</p><h3>SCD Type 1: Overwrite</h3><p>The simplest response: when a value changes, you overwrite it and move on, exactly as if you had made a typo and corrected it [3]. If a product’s department field is wrong and gets fixed, Type 1 is the right call, there’s no reason to preserve a mistake.</p><p>The tradeoff is that you permanently lose the ability to reproduce old reports that depended on the previous value [8]. If a customer’s region changes and you overwrite it, all their historical orders retroactively appear to have shipped from the new region. That’s fine for corrections, but dangerous for anything the business actually wants to track over time.</p><h3>SCD Type 2: Add a new row</h3><p>This is, in practice, the workhorse of the whole SCD family [1]. Instead of overwriting the changed attribute, you insert a brand-new row for the dimension member with a new surrogate key, and mark the old row as no longer current. Type 2 is only possible because dimension tables use a surrogate key that is independent of the natural business key [1], which is what lets the same customer or product exist as multiple rows over time.</p><p>A typical Type 2 customer dimension looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RjZO7vD99rmAOcGbHWCczg.png" /></figure><p>customer_id is the stable business key, customer_key is the surrogate key that changes with every version, and valid_from / valid_to (sometimes paired with an is_current flag) define the window during which each row was the truth. Any fact table row that references customer_key = 1 permanently reflects &quot;Micha, living in Frankfurt at the time,&quot; which is exactly the point.</p><p>The cost is that Type 2 grows your dimension table over time and every query needs to be careful about which version it’s joining against, either by filtering on is_current for &quot;as of today&quot; reporting, or by joining on the date range for &quot;as of the time of the fact&quot; reporting [6].</p><h3>SCD Type 3: Add a column</h3><p>Type 3 takes a narrower approach: instead of a new row, you add a column to hold the previous value, for example previous_department alongside department [3]. This lets you compare &quot;then&quot; versus &quot;now&quot; in a single row, which is genuinely useful when the business wants to see both the old and new classification side by side, for instance during a transition period where some stakeholders still think in terms of old district boundaries [8].</p><p>The limitation is right there in the design: a Type 3 column can only hold one prior value. If the attribute changes a second time, the original history is gone, overwritten just like a Type 1 change would be [6]. Kimball himself notes this pattern is used far less often than Type 1 or Type 2, precisely because it doesn’t scale past a single change [3].</p><h3>SCD Type 4: Separate history table</h3><p>Type 4 splits the dimension in two: a “current” table that always reflects the latest state (kept small and fast for everyday queries), and a separate history table that accumulates every version of every row [4]. This keeps your primary dimension lean while still preserving full history somewhere queryable, and it’s a common pattern when a Type 2 table would otherwise grow uncomfortably large or when most queries only ever need the current state.</p><h3>SCD Type 6 (and the other hybrids): combine 1, 2, and 3</h3><p>Type 6 is exactly what its name implies once you see the math: 1 + 2 + 3 = 6 [5]. It behaves like a Type 2 table (a new row per change, with validity dates) but also keeps a Type 3-style “current value” column embedded in every historical row, kept in sync via Type 1-style overwrites [4]. That means you can filter fact data either by the value that was true when the transaction happened, or by the value that’s true today, without a second join. The naming was reportedly suggested by an HP engineer in 2000, and it stuck [4].</p><p>There are further hybrids in Kimball’s later writing, Types 5 and 7, that combine mini-dimensions and durable keys for specific performance needs, but Type 6 is the one that shows up most often in practice once a team outgrows plain Type 2 [4].</p><h3>Choosing between them</h3><p>In practice, most warehouses lean on Type 1 and Type 2, and reach for the others only when a specific reporting requirement demands it. A reasonable decision path looks like this [14]:</p><ul><li>Does the business ever need to see the old value? No → Type 1, simple overwrite.</li><li>Yes, and you need full point-in-time history? → Type 2.</li><li>Yes, but only the single most recent prior value matters, and you want it in the same row? → Type 3.</li><li>You need both a fast “current state” table and full history, and the dimension is large? → Type 4.</li><li>You need both historical and current values queryable side by side without extra joins? → Type 6.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t79Z3380mxzZSaB-_oYDPg.png" /><figcaption>Decision Diagram</figcaption></figure><h3>Implementing SCD Type 2 in a modern warehouse</h3><p>Historically, Type 2 meant writing MERGE statements by hand: detect changed rows, close out the old version by setting valid_to, and insert a fresh row with a new surrogate key. dbt now automates this with <strong>snapshots</strong>, which implement Type 2 SCDs directly over a source table [13]. A dbt snapshot compares the current state of a source table against what it recorded last time it ran, and for any row where a tracked column changed, it closes the old record and inserts a new one, populating dbt_valid_from and dbt_valid_to automatically [12].</p><p>There are two ways to tell dbt when a row has changed: a timestamp strategy, which trusts an updated_at column from the source system, and a check strategy, which compares a specified list of columns (or all of them) row by row [13]. The check strategy is useful when the source system doesn&#39;t reliably maintain an updated_at column, though it has one subtlety worth knowing: because SQL treats NULL = NULL as unknown rather than true, naive comparisons can miss a change from NULL to a real value, so dbt includes extra logic to handle that case correctly [11].</p><p>A snapshot only captures the state of the source table at the moment it runs, so if a value changes twice between two scheduled runs, the intermediate state is simply never recorded, which is why the run frequency should match how much granularity the business actually needs [11]. Snapshots are typically scheduled to run before the rest of the dbt models, since downstream dimension and fact models often depend on the historical table being up to date first [12].</p><p>On BigQuery specifically, teams often pair dbt snapshots with a change data capture source, for example streaming updates in through GCP Datastream, so that the snapshot always has a fresh view of the operational database to diff against [9]. For very large dimensions, some implementations also hash the tracked columns into a single value and compare hashes instead of comparing every column individually, which keeps the change-detection query cheap even as the number of tracked attributes grows [10].</p><h3>The takeaway</h3><p>SCD is the concept, not a single technique: it’s the general problem of deciding what a data warehouse should do when the real world changes underneath it. Type 1 forgets on purpose, Type 2 remembers everything, Type 3 remembers just enough to compare then and now, and Types 4 and 6 are ways of getting the benefits of Type 2 without paying its full cost in table size or query complexity. Picking the right one per attribute, not per table, is usually the detail that separates a warehouse that can answer “what did this look like on that date” from one that can only ever say “here’s what it looks like now.”</p><h3>References</h3><ol><li><a href="https://www.red-gate.com/simple-talk/databases/sql-server/bi-sql-server/clarifying-data-warehouse-design-with-historical-dimensions/">Clarifying Data Warehouse Design with Historical Dimensions — Simple Talk</a></li><li><a href="https://www.kimballgroup.com/2008/08/slowly-changing-dimensions/">Slowly Changing Dimensions — Kimball Group</a></li><li><a href="https://www.kimballgroup.com/2008/09/slowly-changing-dimensions-part-2/">Slowly Changing Dimensions, Part 2 — Kimball Group</a></li><li><a href="https://www.kimballgroup.com/2013/02/design-tip-152-slowly-changing-dimension-types-0-4-5-6-7/">Design Tip #152: Slowly Changing Dimension Types 0, 4, 5, 6 and 7 — Kimball Group</a></li><li><a href="https://www.luzmo.com/blog/slowly-changing-dimensions">Slowly Changing Dimensions: Types and Examples — Luzmo Blog</a></li><li><a href="https://en.wikipedia.org/wiki/Slowly_changing_dimension">Slowly changing dimension — Wikipedia</a></li><li><a href="https://www.datacamp.com/tutorial/mastering-slowly-changing-dimensions-scd">Mastering Slowly Changing Dimensions (SCD) — DataCamp</a></li><li><a href="https://www.holistics.io/blog/scd-cloud-data-warehouse/">Slowly Changing Dimensions (SCDs) In The Age of The Cloud Data Warehouse — Holistics</a></li><li><a href="https://yia333.medium.com/implementing-scd-type-2-data-acquisition-pipelines-to-bigquery-using-gcp-datastream-dbt-70b72134eb9b">Implementing SCD Type 2 Data Acquisition Pipelines to BigQuery Using GCP Datastream &amp; dbt — Yi Ai, Medium</a></li><li><a href="https://medium.com/towards-data-engineering/scd2-in-bigquery-dbt-historical-versioning-hashing-strategies-and-dof-full-load-processing-4b26fe317cd7">SCD2 in BigQuery + dbt: Historical Versioning, Hashing Strategies and DOF Full-Load Processing — Sendoa Moronta, Towards Data Engineering</a></li><li><a href="https://note.com/kenken_05/n/n66b20b030082?hl=en">The Complete Guide to dbt snapshot — Implementing SCD Type 2 — Ken</a></li><li><a href="https://oneuptime.com/blog/post/2026-02-17-how-to-use-dbt-snapshots-to-track-slowly-changing-dimensions-in-bigquery/view">How to Use dbt Snapshots to Track Slowly Changing Dimensions in BigQuery</a></li><li><a href="https://docs.getdbt.com/docs/build/snapshots">Add snapshots to your DAG — dbt Developer Hub</a></li><li><a href="https://www.thedataschool.co.uk/matthias-albert/dbt-snapshots-and-slowly-changing-dimensions-scds/">dbt Snapshots and Slowly Changing Dimensions (SCDs) — The Data School</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca86ec5feb5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explained: Hadoop — HDFS, MapReduce & YARN]]></title>
            <link>https://medium.com/@gerstingmicha/explained-hadoop-hdfs-mapreduce-yarn-8dd214258b4f?source=rss-494e63d656b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dd214258b4f</guid>
            <category><![CDATA[hdfs]]></category>
            <category><![CDATA[apache-hadoop]]></category>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[yarn]]></category>
            <category><![CDATA[mapreduce]]></category>
            <dc:creator><![CDATA[Micha Gersting]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 21:34:18 GMT</pubDate>
            <atom:updated>2026-07-17T21:34:18.216Z</atom:updated>
            <content:encoded><![CDATA[<h4>A solid technical overview of the three pillars behind big data processing, with examples</h4><p>Before cloud object storage and managed data warehouses became the default, a single open source project taught the industry how to store and process data across thousands of ordinary machines. That project is Apache Hadoop. This article walks through its three foundational components: HDFS for storage, YARN for resource management, and MapReduce for processing, and shows how they fit together with concrete examples.</p><h3>The problem Hadoop solves</h3><p>Around the mid 2000s, companies like Google and later Yahoo faced a simple but brutal constraint: a single server, no matter how powerful (vertical scaling limits), cannot store or process petabytes of data. The answer was to spread data and computation across many cheap, commodity machines and accept that hardware failure is not an exception but a daily occurrence. Hadoop is the open source implementation of that idea, inspired directly by two Google papers: the Google File System and MapReduce [1].</p><p>Hadoop consists of three core layers that map cleanly onto three questions:</p><ol><li>Where do I store huge files reliably? <strong>HDFS</strong></li><li>Who decides which machine runs which task? <strong>YARN</strong></li><li>How do I express a computation that can run in parallel? <strong>MapReduce</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*euDGAlzviHw42TgRFdv9hQ.png" /></figure><h3>HDFS: the storage layer</h3><p>The Hadoop Distributed File System (HDFS) is designed to store very large files reliably and stream them at high throughput to applications, even though it runs on hardware that fails regularly [2]. It deliberately relaxes some POSIX file system guarantees in exchange for throughput and simplicity, and it follows a write once, read many access pattern rather than supporting frequent in place edits [1].</p><h4>Architecture</h4><p>HDFS follows a master and worker design [1]:</p><ul><li><strong>NameNode</strong>: a single master process that holds the file system namespace (the directory tree and file to block mapping) entirely in memory. It never stores actual file content.</li><li><strong>DataNodes</strong>: one per worker machine, they store the real data blocks on local disks and report their status back to the NameNode through periodic heartbeats.</li><li><strong>Secondary NameNode</strong>: despite the name, this is not a hot standby. It periodically merges the edit log into the namespace image to keep NameNode startup time manageable [4].</li></ul><p>When a client wants to read or write a file, it first talks to the NameNode to get block locations, then transfers actual bytes directly with the relevant DataNodes. The NameNode is never in the data path itself [4].</p><h4>Blocks and replication</h4><p>Files in HDFS are split into large blocks, 128 MB by default in modern releases, and each block is replicated across multiple DataNodes, three copies by default. Replica placement is rack aware: HDFS tries to keep one replica on a different rack than the others so that a single rack failure, for example a switch going down, does not cause data loss and so that read bandwidth can be pulled from multiple racks at once [1].</p><p><strong>Example.</strong> Imagine you upload a 300 MB CSV export from your BigQuery pipeline into HDFS. With a 128 MB block size, HDFS splits it into three blocks: two full 128 MB blocks and one 44 MB block. Each of those three blocks then gets copied to three different DataNodes across at least two racks. If one DataNode dies, the NameNode notices the missing heartbeat, sees that a block has fewer than three live replicas, and instructs another DataNode to copy the block from a surviving replica, all without any client noticing.</p><p>This is the direct opposite of RAID style redundancy on a single machine. Instead of protecting one disk, HDFS protects an entire cluster by spreading copies across independent machines and racks [1].</p><h3>YARN: the resource manager</h3><p>Early Hadoop tied resource management directly to MapReduce through a single JobTracker process, which became a bottleneck and forced every workload to look like a MapReduce job. YARN, introduced with Hadoop 2, fixed this by splitting resource management from job scheduling into two separate concerns [3].</p><h4>Architecture</h4><ul><li><strong>ResourceManager</strong>: the global authority for the cluster. It has two internal parts, the Scheduler, which allocates resources to running applications based on constraints like queues and capacity, and the ApplicationsManager, which accepts job submissions and starts the first container for each new application [3].</li><li><strong>NodeManager</strong>: runs on every worker machine, launches and monitors containers, and reports resource usage (CPU, memory, and more) back to the ResourceManager [3].</li><li><strong>ApplicationMaster</strong>: a per application process, itself running inside a container, that negotiates additional containers from the ResourceManager and coordinates the actual work of that specific job [3].</li><li><strong>Container</strong>: a bundle of resources, for example 2 vCPUs and 4 GB of memory, granted on a specific node for a specific task to run in.</li></ul><h4>Example flow</h4><p>Say you submit a Spark job to a YARN cluster. The client contacts the ResourceManager, which asks some NodeManager to launch a container that becomes the ApplicationMaster for your Spark job. That ApplicationMaster then requests further containers from the ResourceManager for Spark executors, and NodeManagers across the cluster launch those containers and report their health. This decoupling is why YARN can run MapReduce, Spark, Tez, and other engines side by side on the same cluster, something the original JobTracker design could never do [3].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0FnxSqL8fbE9jhnZhURQvQ.png" /></figure><h3>MapReduce: the processing model</h3><p>MapReduce is a programming model, described originally by Dean and Ghemawat at Google, for processing enormous datasets by expressing a computation as two functions, map and reduce, and letting the underlying system handle parallelization, machine failures, and data movement automatically [5].</p><h4>The three phases</h4><ol><li><strong>Map</strong>: the framework splits input data into chunks (often aligned with HDFS blocks) and runs a user defined map function over each chunk in parallel. The map function emits intermediate key and value pairs.</li><li><strong>Shuffle and sort</strong>: the framework groups all intermediate values by key and transfers them across the network so that every value for a given key ends up at the same reducer, sorted by key [6].</li><li><strong>Reduce</strong>: a user defined reduce function receives each key along with the full list of values associated with it and produces the final output, which is written back to HDFS.</li></ol><h4>Example: word count</h4><p>The canonical MapReduce example counts word frequency across a large collection of text files. Conceptually it looks like this.</p><pre>Input:      &quot;the cat sat on the mat&quot;<br>Map:        (the,1) (cat,1) (sat,1) (on,1) (the,1) (mat,1)<br>Shuffle:    the -&gt; [1,1]   cat -&gt; [1]   sat -&gt; [1]   on -&gt; [1]   mat -&gt; [1]<br>Reduce:     the=2  cat=1  sat=1  on=1  mat=1</pre><p>Each mapper processes one split of the input independently and never talks to the others directly. The shuffle phase, handled entirely by the framework, is what makes the model powerful: developers only write the map and reduce logic and never touch networking, retries, or synchronization themselves [5][6].</p><p>If a task fails or simply runs slowly on a struggling machine, the framework can speculatively launch a duplicate copy of that task elsewhere and use whichever finishes first, a mechanism the original paper called backup tasks and which Hadoop still implements today as speculative execution [5][6].</p><h3>Putting it all together</h3><p>A single MapReduce job submitted to a Hadoop cluster touches all three systems in sequence.</p><ol><li>Input data already sits in HDFS, split into blocks and replicated across DataNodes.</li><li>The client submits the job to YARN’s ResourceManager, which launches an ApplicationMaster (the MapReduce ApplicationMaster in this case).</li><li>The ApplicationMaster requests containers from the ResourceManager. YARN tries to place map tasks on nodes that already hold the relevant HDFS block, a concept called data locality, so that computation moves to the data instead of the data moving across the network [3][1].</li><li>NodeManagers launch the requested containers and run the map tasks inside them.</li><li>The framework shuffles intermediate data to reduce tasks, again running inside YARN containers.</li><li>Reducers write their final output back into HDFS, replicated like any other file.</li></ol><p>The diagrams below illustrate the HDFS storage architecture and the YARN plus MapReduce execution flow.</p><h3>Where this stands today</h3><p>Pure MapReduce has largely been replaced in practice by engines like Apache Spark, which keep intermediate data in memory instead of writing every stage to disk, and by cloud native object stores such as Amazon S3 or Google Cloud Storage, which decouple storage from compute entirely. YARN, however, is still widely used as a resource manager for on premises clusters, and HDFS still underlies many enterprise data platforms that predate the cloud migration. Understanding the original three layer design remains useful because the concepts it introduced, block based distributed storage, resource negotiation independent of the processing engine, and a map and reduce style parallel computation model, still show up, in different clothing, inside modern systems like Spark on Kubernetes or BigQuery’s own distributed execution engine.</p><p>Thanks for reading!</p><h3>References</h3><p>[1] Apache Software Foundation. “HDFS Architecture Guide.” Apache Hadoop 3.4.3 Documentation. <a href="https://hadoop.apache.org/docs/r3.4.3/hadoop-project-dist/hadoop-hdfs/HdfsDesign.html">https://hadoop.apache.org/docs/r3.4.3/hadoop-project-dist/hadoop-hdfs/HdfsDesign.html</a></p><p>[2] Shvachko, K., Kuang, H., Radia, S., and Chansler, R. “The Hadoop Distributed File System.” Proceedings of the 2010 IEEE 26th Symposium on Mass Storage Systems and Technologies (MSST), pages 1 to 10, 2010. <a href="https://doi.org/10.1109/MSST.2010.5496972">https://doi.org/10.1109/MSST.2010.5496972</a></p><p>[3] Apache Software Foundation. “Apache Hadoop YARN.” Apache Hadoop Documentation. <a href="https://hadoop.apache.org/docs/stable/hadoop-yarn/hadoop-yarn-site/YARN.html">https://hadoop.apache.org/docs/stable/hadoop-yarn/hadoop-yarn-site/YARN.html</a></p><p>[4] Apache Software Foundation. “HDFS Users Guide.” Apache Hadoop 1.2.1 Documentation. <a href="https://hadoop.apache.org/docs/r1.2.1/hdfs_user_guide.html">https://hadoop.apache.org/docs/r1.2.1/hdfs_user_guide.html</a></p><p>[5] Dean, J. and Ghemawat, S. “MapReduce: Simplified Data Processing on Large Clusters.” 6th Symposium on Operating System Design and Implementation (OSDI 2004), pages 137 to 150. <a href="https://www.usenix.org/conference/osdi-04/mapreduce-simplified-data-processing-large-clusters">https://www.usenix.org/conference/osdi-04/mapreduce-simplified-data-processing-large-clusters</a></p><p>[6] Apache Software Foundation. “MapReduce Tutorial.” Apache Hadoop Documentation. <a href="https://hadoop.apache.org/docs/current/hadoop-mapreduce-client/hadoop-mapreduce-client-core/MapReduceTutorial.html">https://hadoop.apache.org/docs/current/hadoop-mapreduce-client/hadoop-mapreduce-client-core/MapReduceTutorial.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dd214258b4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Kafka explained]]></title>
            <link>https://medium.com/@gerstingmicha/apache-kafka-explained-83d9e31d108d?source=rss-494e63d656b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/83d9e31d108d</guid>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[data-streaming]]></category>
            <dc:creator><![CDATA[Micha Gersting]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 18:18:06 GMT</pubDate>
            <atom:updated>2026-07-16T18:18:06.471Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why a “distributed commit log” became the backbone of modern data engineering and what you actually need to know before your next interview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nhl89Hlu00jlVgZ7" /><figcaption>Photo by <a href="https://unsplash.com/@helgapettersen?utm_source=medium&amp;utm_medium=referral">Helga Pettersen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article walks through Kafka, not the legendary author, but the modern data-streaming powerhouse. From first principles: what problem it actually solves, how the pieces fit together, and because most of you reading this are prepping for something a deep dive into the questions that separate “I used Kafka once” from “I’ve fought Kafka in production” in an interview [1].</p><h3>1. The problem Kafka was built to solve</h3><p>Before Kafka, if Service A needed to tell Services B, C, and D that something happened, you had two bad options: A calls each of them directly (tight coupling, A now depends on B/C/D being up), or you bolt on a traditional message queue, which typically deletes a message once it’s been consumed so if a new consumer shows up next week wanting the last 30 days of events, it’s out of luck.</p><p>Kafka’s answer, born at LinkedIn, was to stop thinking of data as <em>messages to be delivered</em> and start thinking of it as a <em>log to be appended to</em>. <strong>A Kafka topic is not a queue, it’s an ordered, append-only file that consumers read from independently, at their own pace, without deleting anything </strong>for anyone else. That single design decision is why Kafka can support real-time analytics, log aggregation, and event sourcing with one platform, ingesting huge volumes of events with very low latency and no data loss [1].</p><h3>2. The core vocabulary and how the pieces click together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLZ-HvFzrt-bAveIjylR9w.png" /><figcaption>Simple Kafka Setup</figcaption></figure><p><strong>Topics and partitions.</strong> A topic (e.g. orders) is split into partitions, and a partition is the actual unit of storage: an ordered, immutable sequence of records, each with an integer <strong>offset</strong> marking its position [2]. Splitting a topic into partitions is what lets Kafka scale horizontally, different partitions can live on different machines and be written to and read from in parallel.</p><p><strong>Producers.</strong> Producers decide which partition a record goes to (usually by hashing a key, like a customer ID, so all events for that key land in the same partition and stay ordered) [2]. Producers write, brokers store, nothing more magical than that.</p><p><strong>Consumers and consumer groups.</strong> Consumers <em>pull</em> data from brokers rather than having it pushed to them, this is a deliberate design choice that lets each consumer control its own pace [2]. Consumers are organized into <strong>consumer groups</strong>: a group is a set of consumers cooperating to read a topic, <strong>where each partition is assigned to exactly one consumer </strong>within the group at a time. This is the mechanism that gives you parallel processing without duplicate work, the moment you have more consumers in a group than partitions in the topic, the extra consumers just sit idle, because a partition can’t be split further within a group [4].</p><p><strong>Offsets.</strong> Each consumer group tracks, per partition, how far it has read, the <strong>offset</strong>. Kafka doesn’t store this in some external database; it stores it in a regular (internal) Kafka topic called __consumer_offsets [3]. There&#39;s a subtlety worth internalizing: the <em>committed</em> offset represents the next record the consumer intends to read, not the last one it successfully processed, so after processing the record at offset 25, the consumer commits offset 26 [5].</p><p><strong>Brokers and the cluster.</strong> A broker is a single Kafka server; a cluster is a group of brokers working together. Each partition is stored, with its replicas across brokers in the cluster, and clients talk to whichever broker currently holds the “leader” copy of the partition they care about [1].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqyj9Ews_2ZLgpSytGzKVQ.png" /><figcaption>Example Flow</figcaption></figure><h3>3. Fault tolerance: replication, ISR, and leader election</h3><p>This is the part that trips people up conceptually, because it’s genuinely elegant once it clicks.</p><p>Every partition has one <strong>leader</strong> replica and zero or more <strong>follower</strong> replicas. All producer writes and consumer reads go through the leader; followers just pull from the leader to stay in sync [6]. The set of replicas that are actually caught up with the leader at any given moment is called the <strong>In-Sync Replica set (ISR)</strong> [7].</p><p>Why does the ISR matter so much? Because when a leader dies, Kafka only allows a replica <em>from the ISR</em> to become the new leader. This guarantees the new leader has every record that was already acknowledged, no silent data loss [8].</p><p>There’s a companion setting, min.insync.replicas, that determines how many replicas must acknowledge a write before the producer considers it &quot;acked&quot; when using acks=all. A common production pattern is replication.factor=3 with min.insync.replicas=2: you can lose one broker and keep writing safely; lose two, and Kafka correctly refuses to accept writes rather than silently risking data loss [10].</p><h3>4. Delivery guarantees: at-most-once, at-least-once, exactly-once</h3><p>Every messaging system has to answer: what happens on a retry? Kafka gives you three explicit tiers [11]:</p><ul><li><strong>At-most-once</strong> — the producer doesn’t retry on failure. Fast, but you can lose messages.</li><li><strong>At-least-once</strong> — the producer retries until it gets an ack. No data loss, but a broker can write successfully and the ack can get lost, so the producer retries and you get a duplicate.</li><li><strong>Exactly-once</strong> — every record is written and processed exactly one time, even across retries and broker failures.</li></ul><p>Kafka achieves exactly-once through two mechanisms working together [12]:</p><ol><li><strong>Idempotent producers.</strong> Each producer instance gets a unique Producer ID (PID), and every record is tagged with a per-partition sequence number. The broker remembers the last sequence number it saw for that PID and silently discards an exact repeat — so a retry after a lost ack no longer creates a duplicate [12].</li><li><strong>Transactions.</strong> For read-process-write pipelines that span multiple partitions or topics, Kafka lets you wrap the writes <em>and</em> the consumer offset commit in a single atomic transaction. Either everything in the transaction becomes visible, or none of it does. Downstream consumers set isolation.level=read_committed so they never see the in-flight, uncommitted part of a transaction [7].</li></ol><p>Worth knowing: as of Kafka 3.0, acks=all and enable.idempotence=true are the <em>default</em> producer settings. Kafka quietly upgraded its own baseline from &quot;fast but lossy&quot; to &quot;safe by default&quot; [12].</p><h3>5. Storage: retention and log compaction</h3><p>Kafka doesn’t keep data forever by default, it deletes old segments once they cross a <strong>time-based</strong> (retention.ms, default 7 days) or <strong>size-based</strong> (retention.bytes) threshold [13]. That&#39;s the delete cleanup policy, and it&#39;s what you want for high-volume event streams like clickstreams or logs.</p><p>But some topics represent <em>state</em>, not <em>events, </em>think “current address per customer ID.” For those, Kafka offers <strong>log compaction</strong>: instead of deleting by age, Kafka guarantees it will always retain at least the latest value for every key in the partition, discarding older values for the same key [14]. This is exactly the mechanism behind Kafka Streams’ KTable abstraction and behind Change-Data-Capture pipelines, where each message is a row update keyed by primary key and you only ever need the latest state [14]. You can even combine both policies (cleanup.policy=compact,delete) when you want the latest value per key <em>and</em> a hard cap on how long dead keys hang around [15].</p><h3>6. Interview deep dive: what actually gets asked</h3><p>Interviewers in 2026 aren’t looking for textbook definitions anymore, they’re listening for whether you’ve actually operated Kafka under load [17]. Here’s the shape of what tends to come up, organized by what it’s really testing.</p><h4>“Walk me through what happens when a producer sends a message”</h4><p>This tests whether you understand the write path end to end: the producer serializes the key/value, the partitioner picks a partition (hash of the key, or round-robin if there’s no key), the record is batched client-side for efficiency, sent to the partition’s leader broker, replicated to followers, and acknowledged back to the producer according to the acks setting. Mention batching and compression explicitly, that&#39;s what makes Kafka fast, not the network protocol.</p><h4>“How would you handle a hot partition?”</h4><p>A classic scenario question: one partition (usually because of a skewed key, e.g. one huge customer ID) is getting disproportionate traffic, causing lag on that one consumer while others sit idle [18]. The strong answer isn’t “add more partitions”, it’s diagnosing <em>why</em> the key distribution is skewed, then considering a composite key, a custom partitioner, or salting the key to spread load, while being explicit about the ordering trade-off you’re accepting (you lose strict per-original-key ordering the moment you salt it).</p><h4>“What’s the difference between acks=0, acks=1, and acks=all?&quot;</h4><p>acks=0 fire and forget, fastest, can silently lose data. acks=1leader acknowledges after writing locally, but a leader crash before replication still loses the record. acks=all (or -1) the leader waits for all <em>in-sync</em> replicas to acknowledge, giving you the strongest durability at the cost of latency. Tie this back to min.insync.replicas interviewers love that connection because it shows you understand the durability/availability trade-off, not just the config name.</p><h4>“How does Kafka guarantee ordering?”</h4><p>Only <em>within</em> a partition, never across partitions of the same topic. If a consumer needs global ordering, the honest answer is: you either use a single partition (and give up parallelism) or you redesign so ordering only needs to hold <em>per key</em>, which a well-chosen partition key already gives you for free.</p><h4>“Explain consumer rebalancing and why it’s disruptive”</h4><p>When a consumer joins or leaves a group (including a slow consumer getting kicked for missing heartbeats), Kafka has to reassign partitions across the remaining consumers, and in the classic eager rebalance protocol every consumer in the group stops processing during that window (“stop-the-world”). Bonus points if you know Kafka 4.0 introduced a newer, incremental “consumer rebalance” protocol specifically to reduce this disruption [3], and if you can describe symptoms you’ve seen from bad rebalance behavior (processing gaps, duplicate reprocessing right after a rebalance because offsets weren’t committed in time).</p><h4>“What’s the Transactional Outbox Pattern, and why not just write to Kafka directly from your service?”</h4><p>Directly worth knowing if you’re building this yourself (as many people learning Kafka do): if a service writes to its database <em>and</em> publishes to Kafka as two separate operations, a crash between them leaves you inconsistent. The outbox pattern writes the business change and an “event” row to an outbox table in the <em>same</em> database transaction, and a separate process (often Kafka Connect’s JDBC source connector, or a custom poller) tails that table and publishes to Kafka, turning a distributed-transaction problem into a single-database-transaction problem [20].</p><h4>Quick-fire concepts worth having crisp one-liners for</h4><ul><li><strong>Log compaction vs. retention</strong>: compaction keeps the latest value per key forever (state); retention deletes by age or size (events) [14].</li><li><strong>Idempotent producer vs. transactions</strong>: idempotence prevents duplicates from <em>retries within one producer session</em>; transactions provide atomicity <em>across multiple partitions/topics</em>, including tying together a write and an offset commit [12].</li></ul><p>The meta-point across all of these: interviewers aren’t grading whether you memorized min.insync.replicas. They&#39;re grading whether you can reason about the trade-off it represents. Go build something small with Kafka, break it on purpose, and you&#39;ll have real answers instead of recited ones.</p><h3>Sources</h3><p>[1] Apache Kafka Architecture Explained — Towards AI, <a href="https://pub.towardsai.net/understanding-kafka-architecture-a-comprehensive-overview-07596de526b9"><em>towardsai.net</em></a> <br>[2] Kafka Design Overview — Confluent Documentation, <a href="https://docs.confluent.io/kafka/design/index.html"><em>docs.confluent.io/kafka/design</em></a> <br>[3] Kafka Consumer Design: Consumers, Consumer Groups, and Offsets — Confluent Documentation, <a href="https://docs.confluent.io/kafka/design/consumer-design.html"><em>docs.confluent.io</em></a><em><br></em> [4] Kafka Consumer Group &amp; Offset Explained — Conduktor, <a href="https://www.conduktor.io/kafka/kafka-consumer-groups-and-consumer-offsets"><em>conduktor.io</em></a> <br>[5] Kafka Consumer Offsets Guide — Confluent Blog, <a href="https://www.confluent.io/blog/guide-to-consumer-offsets/"><em>confluent.io/blog</em></a> <br>[6] How to Configure Replication for Fault Tolerance in Kafka — OneUptime, <a href="https://oneuptime.com/blog/post/2026-01-25-kafka-replication-fault-tolerance/view"><em>oneuptime.com</em></a> <br>[7] Kafka Replication Factor &amp; Topic Replication Explained — Conduktor, <a href="https://www.conduktor.io/kafka/kafka-topic-replication"><em>conduktor.io</em></a> <br>[8] Understanding In-Sync Replicas (ISR) in Apache Kafka — GeeksforGeeks, <a href="https://www.geeksforgeeks.org/apache-kafka/understanding-in-sync-replicas-isr-in-apache-kafka/"><em>geeksforgeeks.org</em></a> <br>[9] Apache Kafka Documentation — AxonOps, <a href="https://axonops.com/docs/data-platforms/kafka/"><em>axonops.com/docs</em></a> <br>[10] Kafka Replication: Fault Tolerance Explained — ADHDecode, <a href="https://adhdecode.com/articles/kafka/19-kafka-replication-fault-tolerance/"><em>adhdecode.com</em></a> <br>[11] Exactly-once semantics with Kafka transactions — Strimzi, <a href="https://strimzi.io/blog/2023/05/03/kafka-transactions/"><em>strimzi.io/blog</em></a> <br>[12] Kafka Exactly-Once: Producers + Transactions — Conduktor, <a href="https://www.conduktor.io/glossary/exactly-once-semantics-in-kafka"><em>conduktor.io/glossary</em></a> <br>[13] Apache Kafka® Retention Explained — Confluent, <a href="https://www.confluent.io/learn/kafka-retention/"><em>confluent.io/learn</em></a> <br>[14] Kafka Log Compaction Explained — Conduktor, <a href="https://www.conduktor.io/glossary/kafka-log-compaction-explained"><em>conduktor.io/glossary</em></a> <br>[15] Kafka Log Compaction — Kafka supports two cleanup policies — Medium (Dare Famuyiwa), <a href="https://medium.com/@darefamuyiwa/kafka-log-compaction-9ce31ea3da70"><em>medium.com</em></a> <br>[16] Apache Kafka architecture: a complete guide — Factor House, <a href="https://factorhouse.io/articles/kafka-architecture"><em>factorhouse.io</em></a> <br>[17] 40 Apache Kafka Interview Questions Every Experienced Java Developer Must Know in 2026 — Medium (Meet2sudhakar), <a href="https://medium.com/@meet2sudhakar/40-apache-kafka-interview-questions-every-experienced-java-developer-must-know-in-2026-c700d254c36a"><em>medium.com</em></a> <br>[18] Kafka #3: Topic Scenarios based interview questions for experienced engineers — Medium (Sandeep), <a href="https://medium.com/@javalearners/kafka-topic-scenarios-based-interview-questions-for-experienced-engineers-7de199813860"><em>medium.com</em></a> <br>[19] Data Engineering Interview Questions for Senior Engineers (2026) — Algoroq, <a href="https://www.algoroq.io/interview-questions/data-engineering/"><em>algoroq.io</em></a> <br>[20] Achieving Exactly-Once Semantics in Kafka: Producer &amp; Consumer Idempotency — Medium (Anil Goyal), <a href="https://medium.com/@anil.goyal0057/achieving-exactly-once-semantics-in-kafka-producer-consumer-idempotency-abad50cba95c"><em>medium.com</em></a> <br>[21] 50 Kafka Interview Questions for Data Engineers (2026) — Datavidhya, <a href="https://datavidhya.com/blog/kafka-data-engineering-interview-questions/"><em>datavidhya.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83d9e31d108d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parquet, Delta, Iceberg, Hudi & Co.: A Simple Guide to Data File Formats]]></title>
            <link>https://medium.com/@gerstingmicha/parquet-delta-iceberg-hudi-co-a-simple-guide-to-data-file-formats-98a2777f4a61?source=rss-494e63d656b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/98a2777f4a61</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[filetype]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[filesystem]]></category>
            <dc:creator><![CDATA[Micha Gersting]]></dc:creator>
            <pubDate>Tue, 14 Jul 2026 16:40:04 GMT</pubDate>
            <atom:updated>2026-07-14T16:40:04.182Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve worked in data engineering for more than a week, you’ve heard these names thrown around like everyone just <em>knows</em> what they mean: Parquet, Avro, ORC, Delta Lake, Iceberg, Hudi. They get mentioned in the same breath, but they are not the same <em>kind</em> of thing and that’s exactly where the confusion starts.</p><p>This article gives you one clear mental model, a memory trick for each format, and a simple “when do I use this” guide. By the end, you’ll know exactly which format to reach for and why.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*brl6O8TAXUgUcwjA" /><figcaption>Photo by <a href="https://unsplash.com/@anniespratt?utm_source=medium&amp;utm_medium=referral">Annie Spratt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The one idea that makes everything click</h3><p>You need to think in two layers:</p><ol><li><strong>File formats</strong> — how the raw bytes on disk are structured. Examples: CSV, JSON, Avro, Parquet, ORC.</li><li><strong>Table formats</strong> (a.k.a. “open lakehouse formats”), a metadata layer <em>on top of</em> file formats that adds database-like features: transactions, versioning, time travel, safe updates and deletes. Examples: Delta Lake, Apache Iceberg, Apache Hudi.</li></ol><p><strong>Memory trick:</strong> think of a library.</p><ul><li>The <strong>file format</strong> is the paper and binding of each individual book (how the pages are physically laid out).</li><li>The <strong>table format</strong> is the library’s catalog system. The index cards that tell you which books exist, which edition is current, and what changed since last week.</li></ul><p>You need both. A Delta, Iceberg, or Hudi table is, underneath, just a folder of Parquet files <em>plus</em> a smart catalog sitting on top that combines the data files with a transaction log or metadata tree [4].</p><h3>Layer 1: The File Formats</h3><h4>CSV / JSON — the “sticky notes”</h4><p>Everyone starts here. Human-readable, easy to open in Excel, zero setup. But they’re row-based, uncompressed, and painfully slow once your dataset grows past a few GB, every query has to read <em>every column of every row</em>, even if you only need one field.</p><p><strong>Use it for:</strong> small config files, quick exports, sharing a sample with a non-technical colleague. <strong>Never</strong> for production analytics at scale.</p><h4>Apache Parquet — the “shipping container sorted by column”</h4><p>Parquet is a free, open-source, column-oriented data storage format built for the Hadoop ecosystem and beyond [2]. Instead of storing data row by row, it stores it column by column, so a query engine can read only the columns it actually needs and skip the rest, as laid out in the official file-format specification [1].</p><p><strong>Why it matters today:</strong> Parquet has become the de-facto standard storage layer underneath modern data lakes, cloud storage systems like S3, Azure Data Lake Storage, and Google Cloud Storage commonly store data in Parquet because of its efficient columnar layout [2]. It’s also the foundation that Delta Lake, Iceberg, and Hudi are usually built on top of, since these lakehouse frameworks add a metadata layer over Parquet files to support schema evolution, time travel, and ACID transactions [2].</p><p><strong>Use it for:</strong> BigQuery external tables, Spark/PySpark batch jobs, data science export, basically any “I need to store analytical data efficiently and query only some columns” scenario.</p><h4>Apache ORC — Parquet’s cousin from the Hive world</h4><p>ORC (Optimized Row Columnar) is also a columnar file format, self-describing and type-aware, built for large streaming reads with built-in indexes so it can jump straight to the relevant rows and skip everything else [9].</p><p><strong>Use it for:</strong> Hive-based data warehouses. Skip it if your stack is Spark/BigQuery/Snowflake-centric, where Parquet is the more common default.</p><h4>Apache Avro — the “envelope with the letter and the dictionary inside”</h4><p>Avro is a row-based data serialization format where the schema (written in JSON) travels together with the data, so that files can be processed later by any program and if the reader expects a different schema, both versions are present to resolve the difference [10].</p><p><strong>Use it for:</strong> Kafka messages, event streams, CDC (change-data-capture) payloads, anywhere schemas change over time and different services need to agree on structure. Not the right choice for large analytical scans; for that, you want a columnar format.</p><h3>Layer 2: The Table Formats (the “lakehouse” trio)</h3><p>These three don’t replace Parquet, they sit on top of it (Iceberg can also sit on top of ORC or Avro) and add the database features a plain folder of files can never give you: <strong>ACID transactions, safe concurrent writes, schema evolution, and time travel.</strong></p><h4>Delta Lake — the transaction log</h4><p>Delta Lake extends Parquet files with a file-based transaction log, giving you ACID transactions, scalable metadata handling, and unified batch/streaming support [3][4]. Every write creates a new table version, and the log records exactly what changed, when, and by whom, data files stay in Parquet, while the log itself lives as JSON, archived periodically into Parquet as well [5].</p><p><strong>Use it for:</strong> anything running on (or close to) Apache Spark or Databricks, it has the deepest, most mature integration there, and is the default table format in Databricks and Microsoft Fabric.</p><h4>Apache Iceberg — the open standard</h4><p>Iceberg is an open table format designed for huge analytic datasets, built to avoid the “unpleasant surprises” of older formats like Hive tables, silent data loss, slow queries from manual partitioning mistakes, and inconsistent reads during writes [6]. Its standout features are <strong>hidden partitioning</strong> (you don’t need to know the physical layout to write fast queries) and <strong>partition evolution</strong> (you can change how a table is partitioned later without rewriting it) [6].</p><p><strong>Use it for:</strong> multi-engine environments e.g., you ingest with Spark or Flink but query with Snowflake, BigQuery, or Trino, and you don’t want to be locked into one vendor’s ecosystem.</p><h4>Apache Hudi — the upsert specialist</h4><p>Hudi (“Hadoop Upserts Deletes and Incrementals”) was built at Uber specifically to handle fast, record-level updates and deletes on data lakes — something plain analytical formats were never designed for. It brings core database functionality directly to a data lake: transactions, efficient upserts and deletes, advanced indexing, and automatic table maintenance, all while keeping data in open file formats [8]. It offers two table types: <strong>Copy-on-Write</strong> (rewrite the affected file on every update — simpler, better for reads) and <strong>Merge-on-Read</strong> (write small delta logs and merge them later — faster writes, ideal for high-frequency streaming updates).</p><p><strong>Use it for:</strong> streaming CDC ingestion (e.g., Debezium/Kafka into your lake), workloads with frequent record-level updates/deletes.</p><h3>The decision guide</h3><p>Ask yourself these questions, in order:</p><ol><li><strong>Is this a message/event, not a table row?</strong> (Kafka topic, single CDC event) → <strong>Avro</strong>.</li><li><strong>Is this a Hive/Hadoop-only warehouse?</strong> → <strong>ORC</strong>.</li><li><strong>Do I just need fast analytical scans on static/append-only data, no updates?</strong> → <strong>Parquet</strong> alone is often enough.</li><li><strong>Do I need ACID transactions, time travel, or schema evolution on top of that?</strong> → You need a table format:</li></ol><ul><li>Mostly Spark/Databricks/Microsoft Fabric? → <strong>Delta Lake</strong>.</li><li>Multiple engines need to read/write the same table (Snowflake, BigQuery, Trino, DuckDB…)? → <strong>Apache Iceberg</strong>.</li><li>Constant stream of row-level updates/deletes (CDC, GDPR deletes, near-real-time upserts)? → <strong>Apache Hudi</strong>.</li></ul><p>And if you can’t decide: start with <strong>Parquet + Iceberg</strong> (or Delta, if you’re Spark-only). It’s the safest, most broadly compatible default in 2026, and you can always add Hudi-style streaming ingestion later if your update patterns demand it.</p><p><strong>Thanks for reading!</strong></p><h3>Sources</h3><p>[1] Apache Parquet — Official Documentation. <a href="https://parquet.apache.org/docs/">https://parquet.apache.org/docs/</a> <br>[2] Apache Parquet — Wikipedia. <a href="https://en.wikipedia.org/wiki/Apache_Parquet">https://en.wikipedia.org/wiki/Apache_Parquet</a> <br>[3] Delta Lake — Official Documentation. <a href="https://docs.delta.io/">https://docs.delta.io/</a> <br>[4] Databricks — “What is Delta Lake in Databricks?” <a href="https://docs.databricks.com/aws/en/delta/">https://docs.databricks.com/aws/en/delta/</a> <br>[5] IBM — “What is Delta Lake?” <a href="https://www.ibm.com/think/topics/delta-lake">https://www.ibm.com/think/topics/delta-lake</a> <br>[6] Apache Iceberg — Official Documentation. <a href="https://iceberg.apache.org/docs/latest/">https://iceberg.apache.org/docs/latest/</a> <br>[7] Apache Iceberg — Project Homepage. <a href="https://iceberg.apache.org/">https://iceberg.apache.org/</a> <br>[8] Apache Hudi — Official Documentation Overview. <a href="https://hudi.apache.org/docs/overview/">https://hudi.apache.org/docs/overview/</a> <br>[9] Apache ORC — Official Documentation. <a href="https://orc.apache.org/docs/">https://orc.apache.org/docs/</a> <br>[10] Apache Avro — Official Documentation. <a href="https://avro.apache.org/docs/">https://avro.apache.org/docs/</a> [11] Onehouse — “Apache Hudi vs Delta Lake vs Apache Iceberg: Lakehouse Feature Comparison” (updated October 2025). <a href="https://www.onehouse.ai/blog/apache-hudi-vs-delta-lake-vs-apache-iceberg-lakehouse-feature-comparison">https://www.onehouse.ai/blog/apache-hudi-vs-delta-lake-vs-apache-iceberg-lakehouse-feature-comparison</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98a2777f4a61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PySpark Architecture Explained Simply]]></title>
            <link>https://medium.com/@gerstingmicha/pyspark-architecture-explained-simply-6f8ab76bb0ef?source=rss-494e63d656b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f8ab76bb0ef</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Micha Gersting]]></dc:creator>
            <pubDate>Fri, 29 May 2026 04:53:36 GMT</pubDate>
            <atom:updated>2026-05-29T04:53:36.730Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Demystifying how Python commands turn into massive, distributed big data processing power.</em></p><p>If you’ve ever tried to process a 100GB dataset using standard Pandas, you probably know the feeling of your laptop fans sounding like a jet engine right before the dreaded MemoryError hits.</p><p>When data gets too big for a single machine, we look to <strong>Apache Spark</strong>. And if you love Python, you use <strong>PySpark</strong>.</p><p>But have you ever wondered how Python, a language known for being single-threaded and running on a single machine, can suddenly orchestrate a massive cluster of computers to crunch terabytes of data?</p><p>Let’s break down the PySpark architecture under the hood, keep it simple, and look at exactly how it works.</p><h3>The Big Picture: The Driver-Worker Model</h3><p>At its core, PySpark uses a <strong>Master-Worker architecture</strong>. Think of it like a highly efficient corporate project where one manager orchestrates everything, and a team of specialized workers does the heavy lifting.</p><p>The architecture consists of three main components:</p><ol><li><strong>The Driver Program (The Brain)</strong></li><li><strong>The Cluster Manager (The Orchestrator)</strong></li><li><strong>The Worker Nodes &amp; Executors (The Muscle)</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*EzZs4uEuO30lV51KV07_RA.png" /><figcaption>src: <a href="https://spark.apache.org/docs/latest/cluster-overview.html">https://spark.apache.org/docs/latest/cluster-overview.html</a></figcaption></figure><p>Let’s look at what each one actually does.</p><h3>1. The Driver Program</h3><p>The Driver is where your actual Python script runs. It holds the SparkSession (or SparkContext in older versions).</p><ul><li><strong>What it does:</strong> It translates your Python code into an execution plan, splits that plan into smaller logical pieces called <strong>Tasks</strong>, and schedules them.</li><li><strong>Analogy:</strong> The Head Chef who reads the recipe, plans who does what, and hands out tasks.</li></ul><h3>2. The Cluster Manager</h3><p>The Driver doesn’t directly manage the hardware. Instead, it asks the Cluster Manager for physical resources (like CPU and RAM).</p><ul><li><strong>What it does:</strong> It allocates resources across the cluster. PySpark plugs into different managers depending on your setup, such as <strong>YARN</strong> (common in Hadoop setups), <strong>Kubernetes</strong> (the modern cloud-native standard), or Spark’s built-in <strong>Standalone</strong> manager.</li><li><strong>Analogy:</strong> The restaurant manager who decides how many kitchen stations are open and allocates resources.</li></ul><h3>3. Worker Nodes &amp; Executors</h3><p>Worker nodes are the actual machines in the cluster. Inside each worker node, Spark runs <strong>Executors</strong>.</p><ul><li><strong>What it does:</strong> Executors are separate Java Virtual Machine (JVM) processes. They receive tasks from the Driver, execute them concurrently in threads (slots), and store the results in memory or disk.</li><li><strong>Analogy:</strong> The line cooks chop the vegetables and fry the meat.</li></ul><h3>The Secret Sauce: How Python Talks to Java (Py4J)</h3><p>Here is the catch: Apache Spark is written in Scala, which runs on the Java Virtual Machine (JVM). Python cannot natively talk to a JVM. So, how does PySpark bridge this gap?</p><p>In <strong>Classic PySpark</strong>, the magic happens via a library called <strong>Py4J</strong>.</p><blockquote><strong><em>How Py4J works:</em></strong><em> When you write PySpark code in Python, the Driver uses Py4J to launch a JVM locally. Every time you call a Spark function in Python, Py4J translates that call into an equivalent Java command inside the local JVM.</em></blockquote><ul><li><strong>On the Driver Side:</strong> When you launch your script, the Driver uses Py4J to start a local JVM. Every time you call a Spark DataFrame function in Python, Py4J translates that call into an equivalent Java command inside the local JVM. Once the instructions are in the JVM, the standard Spark engine takes over and sends those tasks across the cluster to the Workers.</li><li><strong>On the Worker Side:</strong> If you use standard DataFrame operations (like df.groupBy().count()), the processing happens entirely inside the ultra-fast JVM executors on the worker nodes. Your Python environment is just giving the orders!</li><li><strong>What about Python UDFs?</strong> If you write custom Python functions (like a Lambda or a non-vectorized UDF) that the JVM can’t understand, the Executor JVM spawns a <strong>Python Worker subprocess</strong> right on the worker node. It pipes the data out of the JVM into Python, processes it, and pipes it back.</li></ul><h3>💡 The Modern Evolution: Spark Connect</h3><p>In recent versions (Spark 3.4+ and fully matured in Spark 4.0), Spark introduced <strong>Spark Connect</strong>. This is a modern client-server architecture that allows you to run PySpark <em>without</em> needing a local JVM or Py4J on your application side. Your Python client simply transmits your data commands as a lightweight logical plan over a secure <strong>gRPC</strong> network connection to a remote Spark cluster.</p><h3>How It Works Step-by-Step (With an Example)</h3><p>Let’s look at a quick, real-world example. Imagine we want to read a massive log file, filter out errors, and count them.</p><pre>from pyspark.sql import SparkSession<br><br># 1. Initialize the Driver and local JVM<br>spark = SparkSession.builder.appName(&quot;ErrorCounter&quot;).getOrCreate()<br><br># 2. Tell workers to load the data across the cluster<br>logs_df = spark.read.text(&quot;hdfs://path/to/massive_log_file.txt&quot;)<br><br># 3. Define the transformation (Lazy Evaluation)<br>errors_df = logs_df.filter(logs_df.value.contains(&quot;ERROR&quot;))<br><br># 4. Trigger an action to get the result<br>error_count = errors_df.count()<br><br>print(f&quot;Total Errors: {error_count}&quot;)</pre><p><strong>What Happens Architecturally:<br>1) </strong>The Driver starts up, opens a local JVM via Py4J, and registers itself with the Cluster Manager to get worker resources.</p><p>2) The Driver tells the Executors to read different chunks (partitions) of the text file simultaneously from distributed storage.</p><p><strong>3) Nothing happens yet.</strong> Spark uses <em>Lazy Evaluation</em>. The Driver just notes down the filter step in a blueprint called a Directed Acyclic Graph (DAG).</p><p>4) The .count() is an <strong>Action</strong>. This triggers the Driver to look at the DAG blueprint, optimize it, break it into <strong>Tasks</strong>, and send those tasks to the Executors. The Executors count the rows on their local chunks, send the numbers back to the Driver, and the Driver sums them up.</p><h3>Why Is This Architecture So Efficient?</h3><ol><li><strong>Data Local Processing:</strong> Executors try to process data that is already physically located on their machine’s hard drive or SSD. This minimizes expensive network data transfer.</li><li><strong>Lazy Evaluation:</strong> Because Spark doesn’t execute code line-by-line, it can look at your entire script, optimize the execution plan (like skipping unnecessary data columns), and only run the code when you explicitly ask for an output.</li><li><strong>In-Memory Computing:</strong> Unlike older frameworks like Hadoop MapReduce which constantly read and write data to disks between steps, PySpark keeps intermediate results in RAM, making it up to 100x faster.</li></ol><h3>📌 Summary of Key Takeaways</h3><ul><li><strong>Driver-Worker Split:</strong> PySpark separates the coordination (Driver) from the execution (Executors residing on Worker Nodes). The Cluster Manager (YARN, K8s, Standalone) sits in between to allocate resources.</li><li><strong>The Language Bridge:</strong> Classic PySpark uses <strong>Py4J</strong> to translate Python code into JVM instructions on the driver side. For pure Python code execution on workers, the JVM spawns dedicated <strong>Python Worker</strong> processes.</li><li><strong>Modern Connectivity:</strong> Modern Spark applications can leverage <strong>Spark Connect</strong>, a client-server architecture using gRPC that eliminates the need for a local JVM on the client side entirely.</li><li><strong>Optimized Execution:</strong> Speed is achieved through <strong>In-Memory computing</strong>, <strong>Data Locality</strong> (bringing the code to where the data lives), and <strong>Lazy Evaluation</strong> (deferring execution until an Action is called to optimize the total plan).</li></ul><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f8ab76bb0ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostSQL Indexing Deep Dive]]></title>
            <link>https://medium.com/@gerstingmicha/postsql-indexing-deep-dive-794ed7285226?source=rss-494e63d656b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/794ed7285226</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[postgresql-index]]></category>
            <category><![CDATA[indexing]]></category>
            <dc:creator><![CDATA[Micha Gersting]]></dc:creator>
            <pubDate>Sun, 07 Dec 2025 16:12:53 GMT</pubDate>
            <atom:updated>2025-12-07T16:12:53.518Z</atom:updated>
            <content:encoded><![CDATA[<h3>PostgreSQL Indexing Deep Dive</h3><p>To truly understand SQL indexes, you need to understand how data is organized under the hood. Most relational databases, including PostgreSQL, MySQL, MariaDB, and SQL Server, use <strong>B-Tree indexes</strong> by default.<br>Why B-Trees?</p><p>Because they allow extremely fast lookups, inserts, and sorted scans with logarithmic complexity<br>→ O(log n) instead of O(n).</p><p>That’s the magic! Let’s explore how this works:</p><p><strong>What Actually Happens When You Query Without an Index</strong></p><p>Suppose your users table has 10 million rows.</p><p>A query like:</p><pre>SELECT * FROM users WHERE email = &#39;john@example.com&#39;;</pre><p>Without an index, PostgreSQL has to:</p><ol><li>Read the first row → check every column in that row to see if email = ‘john@example.com’</li><li>Read the second row → again, check every column</li><li>Continue through all remaining rows → row by row to find all the rows where the condition is met</li></ol><p>This is called a<strong> sequential scan</strong>. It’s simple but slow.<br>It doesn’t matter whether John is in the first row, the 5,000,000th row, or the 9,999,999th row — PostgreSQL has to check everything.</p><p><strong>What Happens With an Index</strong></p><p>When you create an index:</p><pre>CREATE INDEX idx_users_email ON users(email);</pre><p>PostgreSQL builds a separate data structure — the B-Tree index.</p><p>Think of it like:</p><ul><li>A sorted list of email values</li><li>With pointers to where each row is stored on disk</li></ul><p>This sorted structure allows PostgreSQL to:</p><ol><li>Navigate the tree logically</li><li>Narrow down possible matches</li><li>Jump directly to the row on disk</li></ol><p>→ No scanning of millions of rows<br>→ Just a tiny fraction of lookups</p><p><strong>B-Trees Explained Simply</strong></p><p>A B-Tree is a hierarchical structure:</p><ul><li>The root node</li><li>Several intermediate (branch) nodes</li><li>Multiple leaf nodes containing pointers to actual rows</li></ul><p>Visual:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*NhMJ8vWu0XSxm9JuyivJ6w.png" /></figure><p><strong>How a B-Tree search works</strong></p><p>Searching for <em>john@example.com</em>:</p><ol><li>Start at the root</li><li>Determine which branch contains the value</li><li>Go to that branch</li><li>Repeat until reaching the leaf node</li><li>Leaf node tells PostgreSQL exactly where the row lives</li></ol><p>This usually takes 3–5 steps even for millions of rows.</p><p>Why?<br>Because a B-Tree node can contain hundreds of values, so the tree stays extremely shallow.</p><p>→ Fast lookups<br>→ Fast range queries<br>→ Fast sorting<br>→ Fast inequality comparisons (&lt;, &gt;, BETWEEN)</p><p><strong>Why PostgreSQL Uses B-Trees for Most Indexes</strong></p><p>PostgreSQL uses B-Trees as the default index type because they support:</p><ul><li>= equality searches</li><li>&lt;, &lt;=, &gt;=, &gt; comparisons</li><li>BETWEEN queries</li><li>Sorting (ORDER BY)</li><li>Prefix text searches (LIKE ‘abc%’)</li><li>Unique constraints</li></ul><p>They’re incredibly versatile.</p><p><strong>How PostgreSQL Stores the Index</strong></p><p>This is an important detail:</p><p>An index is NOT stored in the table. It is stored in its own file inside PostgreSQL’s data directory. It is maintained automatically on every insert, update, or delete</p><p><strong>Why Indexes Slow Down Writes</strong></p><p>Every time you modify the table:</p><p>INSERT</p><ul><li>Must insert new value into the B-Tree</li><li>Tree may need rebalancing</li></ul><p>UPDATE</p><ul><li>If the indexed column changes:</li><li>Delete old index entry</li></ul><p>Insert new one</p><p>DELETE</p><ul><li>Remove index entries</li></ul><p>For write-heavy systems, this overhead matters.</p><p><strong>How PostgreSQL Decides Whether to Use an Index</strong></p><p>PostgreSQL has a <em>query planner</em>.<br>It analyzes:</p><ul><li>Table size</li><li>Index size</li><li>Column selectivity (uniqueness)</li><li>Disk cost vs. CPU cost</li><li>Statistical histograms of column values</li><li>Whether the index can support all parts of the query</li></ul><p>If PostgreSQL believes that:</p><ul><li>Sequential scan is cheaper<br>→ it will ignore the index.</li></ul><p>This is why indexes sometimes “don’t work” even when they exist.</p><p><strong>Why Composite Indexes Work Left-to-Right</strong></p><p>Example:</p><pre>CREATE INDEX idx_users_name_created <br>ON users(name, created_at);</pre><p>This creates a B-Tree sorted like:<br><em>name → created_at</em></p><p>Meaning:</p><ul><li>All entries sorted by name</li><li>Inside each name, sorted by created_at</li></ul><p>This can optimize:</p><ul><li>WHERE name = ‘John’</li><li>WHERE name = ‘John’ ORDER BY created_at</li><li>WHERE name = ‘John’ AND created_at &gt; …</li></ul><p><strong>But NOT:</strong></p><ul><li>WHERE created_at = … (skips first column → cannot navigate the tree)</li></ul><p>This is why “leftmost prefix” rule exists.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=794ed7285226" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Indexes Explained — A Beginner-Friendly Guide]]></title>
            <link>https://medium.com/@gerstingmicha/sql-indexes-explained-a-beginner-friendly-guide-d180a479bf08?source=rss-494e63d656b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d180a479bf08</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[indexing]]></category>
            <category><![CDATA[sql-indexing]]></category>
            <dc:creator><![CDATA[Micha Gersting]]></dc:creator>
            <pubDate>Sun, 07 Dec 2025 15:48:32 GMT</pubDate>
            <atom:updated>2025-12-07T16:13:35.722Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL Indexes Explained — A Beginner-Friendly Guide</h3><p>For a long time, I barely used indexes in SQL. I only knew that they <em>somehow</em> make queries faster or more efficient. But I always avoided them because I didn’t really understand how they worked or how exactly to use them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rCWlwrs-NmWNbGdv" /><figcaption>Photo by <a href="https://unsplash.com/@lingapp?utm_source=medium&amp;utm_medium=referral">Ling App</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you feel the same way, today I want to change that for you!<br>First in a simple and easy way, second we go deeper in the world of Indexes.</p><p><strong>What is an Index in SQL?</strong></p><p>An index in SQL is very similar to the index of a book.</p><ul><li>Without an index:<br>You would flip through every page to find what you’re looking for (slow).</li><li>With an index:<br>You jump directly to the relevant section (fast).</li></ul><p>SQL works the same way.<br>Without indexes, the database often has to scan through every row of a table — a full table scan.</p><p>With an index, SQL can find data much faster, especially in large tables.</p><p><strong>Creating your first Index:</strong></p><p>First create a table users:</p><pre>CREATE TABLE users (<br>    id INT PRIMARY KEY,<br>    name VARCHAR(100),<br>    email VARCHAR(255),<br>    created_at TIMESTAMP2<br>);</pre><p>If you frequently query users by their email, you can create an index like this:</p><pre>CREATE INDEX idx_users_email ON users(email);</pre><p>Now queries like this will be much faster:</p><pre>SELECT * FROM users WHERE email = &#39;john@example.com&#39;;</pre><p><strong>When Should You Use an Index?</strong></p><p>You frequently filter by a column (WHERE)</p><p>Example:</p><pre>SELECT * FROM orders WHERE customer_id = 42;</pre><p>→ Create an index on customer_id:</p><pre>CREATE INDEX idx_orders_customer_id ON orders(customer_id);</pre><p><strong>You search by text patterns that don’t start with a wildcard</strong></p><p>Example:</p><pre>SELECT * FROM products WHERE name LIKE &#39;Sam%&#39;;</pre><p>→ Good candidate for an index.</p><p><strong>You join tables on a specific column</strong></p><p>Example:</p><pre>SELECT *<br>FROM orders o<br>JOIN users u ON o.user_id = u.id;</pre><p>→ Make sure orders.user_id has an index:</p><pre>CREATE INDEX idx_orders_user_id ON orders(user_id);</pre><p><strong>When NOT to Use an Index</strong></p><p>Indexes are not free.<br>They have downsides too.</p><p><strong>Indexes slow down INSERT, UPDATE, DELETE</strong></p><p>Every time you change data, SQL must also update the index.<br>If you insert millions of rows daily, indexing everything will slow you down.</p><p><strong>Don’t index columns with low uniqueness</strong></p><p>Indexing a boolean column (is_active, is_admin) is mostly useless.<br>Why?<br>Because the index will contain almost the entire table in each bucket — not efficient.</p><p><strong>Don’t over-index</strong></p><p>A good rule of thumb:<br>Index only columns you frequently query.</p><p><strong>Composite Indexes (Multi-Column Indexes)</strong></p><p>You can index more than one column:</p><pre>CREATE INDEX idx_users_name_created<br>ON users(name, created_at);</pre><p>This index helps with queries like:</p><pre>SELECT *<br>FROM users<br>WHERE name = &#39;John&#39;<br>ORDER BY created_at;</pre><p>But be careful:</p><p>Composite indexes work left to right.</p><p>That means name must be used first.</p><p>Good:</p><pre>WHERE name = &#39;John&#39;</pre><p>Bad (no index used):</p><pre>WHERE created_at = &#39;2024–01–01&#39;</pre><p><strong>How to Check if an Index Is Being Used</strong></p><p>PostgreSQL example:</p><pre>EXPLAIN ANALYZE<br>SELECT * FROM users WHERE email = &#39;john@example.com&#39;;</pre><p>MySQL example:</p><pre>EXPLAIN SELECT * FROM users WHERE email = &#39;john@example.com&#39;;</pre><p>You’ll see whether SQL uses an index or a full table scan.</p><p><strong>Removing an Index</strong></p><p>If an index is no longer needed:</p><pre>DROP INDEX idx_users_email;</pre><p>If you want to go deeper into the world of indexes, here you go:</p><p><a href="https://medium.com/@gerstingmicha/postsql-indexing-deep-dive-794ed7285226">PostSQL Indexing Deep Dive</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d180a479bf08" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>