<?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 Thinking monster on Medium]]></title>
        <description><![CDATA[Stories by Thinking monster on Medium]]></description>
        <link>https://medium.com/@akash94thakur?source=rss-36df1949e96a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*E19RVmM1tgq-fVDw.</url>
            <title>Stories by Thinking monster on Medium</title>
            <link>https://medium.com/@akash94thakur?source=rss-36df1949e96a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:12:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akash94thakur/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[How We Finally Got Visibility Into Every Email We Send]]></title>
            <link>https://medium.com/@akash94thakur/how-we-finally-got-visibility-into-every-email-we-send-746a8e23b7ac?source=rss-36df1949e96a------2</link>
            <guid isPermaLink="false">https://medium.com/p/746a8e23b7ac</guid>
            <category><![CDATA[sns]]></category>
            <category><![CDATA[s]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Thinking monster]]></dc:creator>
            <pubDate>Mon, 11 May 2026 16:44:18 GMT</pubDate>
            <atom:updated>2026-05-11T16:44:18.791Z</atom:updated>
            <content:encoded><![CDATA[<p>For a long time, our email sending was a black box. We knew emails were going out — our application was calling AWS SES — but if something went wrong, we had almost no way to answer the questions that mattered:</p><ul><li>Did that email actually get delivered?</li><li>Why did it bounce?</li><li>Which recipient marked it as spam?</li><li>Was there a delivery delay, and for how long?</li></ul><p>We had SES set up and working. What we were missing was <strong>observability</strong>.</p><h3>The Problem: SES Doesn’t Log by Default</h3><p>This was the first surprise for the team. AWS SES does not write per-email logs anywhere on its own. There is no CloudWatch log group that just appears with “here are all the emails you sent.” The docs mention a CloudWatch destination for configuration sets, but if you go set that up expecting log streams, you’ll be disappointed — it only publishes <strong>aggregated metrics</strong> (counts of Send, Delivery, Bounce, etc.) to CloudWatch Metrics. Useful for dashboards, but not for debugging a specific message.</p><p>So we had:</p><ul><li><strong>No record of what message IDs were sent</strong></li><li><strong>No visibility into bounce reasons or SMTP diagnostic codes</strong></li><li><strong>No way to tie a complaint back to a recipient</strong></li><li><strong>No log trail to query when a user said “I never got that email”</strong></li></ul><p>We needed event-level logs: one structured line per email, per outcome.</p><h3>The Approach: SES → SNS → Lambda → CloudWatch Logs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*lw6C0DoHcuzosnzp3qgEYg.png" /></figure><p>The architecture that solved this is straightforward once you know about it:</p><p>SES can publish events to an SNS topic via a <strong>configuration set event destination</strong>. Every time an email is sent, delivered, bounced, complained about, rejected, delayed, or fails template rendering — SES fires a message to SNS. SNS triggers a Lambda function. Lambda parses the raw event payload and writes a clean, structured JSON log line to CloudWatch Logs.</p><p>The key insight is that you need <strong>two event destinations</strong> on your configuration set:</p><ol><li>A <strong>CloudWatch destination</strong> — for aggregate metrics (counts per event type, sliceable by dimensions like email type or campaign)</li><li>An <strong>SNS destination</strong> — for the per-event stream that flows into Lambda and produces searchable logs</li></ol><h3>What the Lambda Does</h3><p>The Lambda handler is intentionally small. It receives SNS records, extracts the SES event JSON from each record’s Message field, and calls a build_log_entry function that normalizes the event into a consistent shape.</p><pre>def handler(event, context):<br>    for record in event.get(&quot;Records&quot;) or []:<br>        sns = record.get(&quot;Sns&quot;) or {}<br>        raw_message = sns.get(&quot;Message&quot;)<br>        if not raw_message:<br>            continue<br>        try:<br>            ses_event = json.loads(raw_message) if isinstance(raw_message, str) else raw_message<br>        except json.JSONDecodeError:<br>            logger.warning(&quot;Invalid JSON in SNS Message: %s&quot;, raw_message[:200])<br>            continue</pre><pre>        log_entry = build_log_entry(ses_event)<br>        logger.info(&quot;SES_EVENT %s&quot;, json.dumps(log_entry))</pre><pre>    return {&quot;statusCode&quot;: 200}</pre><p>Every log line is prefixed with SES_EVENT and contains JSON. This makes them easy to grep, filter in CloudWatch Logs Insights, and eventually ship to a SIEM or log aggregation platform.</p><p>The build_log_entry function extracts different fields depending on the event type:</p><ul><li><strong>Send / Delivery</strong>: messageId, source, recipients, delivery timestamp, SMTP response</li><li><strong>Bounce</strong>: bounce type and subtype, list of failed recipients each with their email address, action, SMTP status code, and full diagnostic code</li><li><strong>Complaint</strong>: complaint feedback type, list of complainants</li><li><strong>Reject</strong>: rejection reason</li><li><strong>Rendering Failure</strong>: template name and error message</li><li><strong>DeliveryDelay</strong>: delay type, delayed recipients with diagnostic codes</li></ul><p>A Bounce log entry looks like this in CloudWatch:</p><pre>{<br>  &quot;eventType&quot;: &quot;Bounce&quot;,<br>  &quot;messageId&quot;: &quot;0102019612345678-abc-def-...&quot;,<br>  &quot;source&quot;: &quot;noreply@example.com&quot;,<br>  &quot;recipients&quot;: [&quot;user@domain.com&quot;],<br>  &quot;bounceType&quot;: &quot;Permanent&quot;,<br>  &quot;bounceSubType&quot;: &quot;General&quot;,<br>  &quot;failedRecipients&quot;: [<br>    {<br>      &quot;email&quot;: &quot;user@domain.com&quot;,<br>      &quot;action&quot;: &quot;failed&quot;,<br>      &quot;status&quot;: &quot;5.1.1&quot;,<br>      &quot;diagnosticCode&quot;: &quot;smtp; 550 5.1.1 The email account that you tried to reach does not exist.&quot;<br>    }<br>  ]<br>}</pre><p>This is the kind of information that was completely invisible to us before.</p><h3>IAM and Permissions</h3><p>Three permission boundaries to wire up:</p><ol><li><strong>SNS topic policy</strong> — allows ses.amazonaws.com to publish to the topic, scoped to the specific configuration set ARN (prevents other accounts from publishing)</li><li><strong>Lambda resource policy</strong> — allows sns.amazonaws.com to invoke the function, scoped to the topic ARN</li><li><strong>Lambda execution role</strong> — AWSLambdaBasicExecutionRole managed policy, which grants write access to CloudWatch Logs</li></ol><p>The SNS topic policy is the easiest to get wrong. The statement for SES needs both AWS:SourceAccount and AWS:SourceArn conditions:</p><pre>{<br>  &quot;Sid&quot;: &quot;AllowSESPublish&quot;,<br>  &quot;Effect&quot;: &quot;Allow&quot;,<br>  &quot;Principal&quot;: {&quot;Service&quot;: &quot;ses.amazonaws.com&quot;},<br>  &quot;Action&quot;: &quot;sns:Publish&quot;,<br>  &quot;Resource&quot;: &quot;&lt;topic-arn&gt;&quot;,<br>  &quot;Condition&quot;: {<br>    &quot;StringEquals&quot;: {<br>      &quot;AWS:SourceAccount&quot;: &quot;&lt;account-id&gt;&quot;,<br>      &quot;AWS:SourceArn&quot;: &quot;arn:aws:ses:&lt;region&gt;:&lt;account-id&gt;:configuration-set/&lt;config-set-name&gt;&quot;<br>    }<br>  }<br>}</pre><p>Omitting the AWS:SourceArn condition would allow any SES configuration set in the account to publish to the topic.</p><h3>Debugging Errors That SES Never Logs</h3><p>One thing we discovered while building this: SES event publishing only fires <strong>after SES accepts a message</strong>. If the send call itself is rejected — for example, because the recipient address is malformed (missing the @domain part) — no SNS event is published. The message was never accepted by SES, so no configuration set event is fired.</p><p>For those failures, the trail lives in <strong>CloudTrail</strong>, not CloudWatch Logs. Failed SendEmail API calls appear as CloudTrail events with an error response. But if the application is using SMTP rather than the API, even CloudTrail won&#39;t have a record — SMTP errors are returned directly to the calling application&#39;s SMTP client and are only visible in application-level logs.</p><p>This distinction matters when users report missing emails: delivery failures (bounces, complaints, delays) show up in our Lambda logs; API-level send rejections need CloudTrail; SMTP errors need the app logs.</p><h3>Cost</h3><p>For our volume (~50,000 emails/day, approximately 1.5M/month), the monitoring stack costs roughly <strong>$1.50–$5/month</strong> on top of SES sending costs. The math:</p><ul><li>Each email generates ~2 events on average (Send + Delivery for a successful send)</li><li>~3M SNS publishes/month → ~$1 (first 1M free, then $0.50/1M)</li><li>~3M Lambda invocations/month → ~$0.40 (first 1M free per month)</li><li>~1.5 GB CloudWatch Logs ingestion → $0–$0.75 (depending on free tier)</li></ul><p>The monitoring overhead is roughly <strong>1–3%</strong> of total email-related AWS spend. For what you get — full per-message traceability for every send, delivery, bounce, and complaint — it’s an obvious trade.</p><h3>What Changed After This Was Live</h3><p>Once the pipeline was running, the difference was immediate:</p><ul><li><strong>Bounce investigation</strong>: instead of guessing, we could look up a message ID and see the exact SMTP diagnostic code from the receiving mail server</li><li><strong>Complaint tracking</strong>: we could identify which recipient marked an email as spam, cross-reference with our send list, and suppress future sends</li><li><strong>Delivery confirmation</strong>: support tickets asking “was this sent?” became trivially answerable — search CloudWatch Logs Insights by recipient address</li><li><strong>Template errors</strong>: rendering failures (unresolved placeholders left in headers, for example) showed up immediately in logs with the template name and error, rather than silently producing malformed sends</li></ul><p>The Lambda function itself has been running for months with zero maintenance. At 128 MB / 30-second timeout, it handles even burst traffic without any issues.</p><h3>Summary</h3><p>The setup boils down to four decisions:</p><ol><li><strong>Use a configuration set</strong> — required for event publishing; make sure your SES identity is attached to it</li><li><strong>Add an SNS event destination</strong> — this is what gives you per-event granularity; the CloudWatch destination alone gives you only counts</li><li><strong>Write a Lambda to normalize events</strong> — SES event payloads are verbose and inconsistent across event types; normalizing at ingest makes querying much cleaner</li><li><strong>Log structured JSON</strong> — one line per event with a consistent prefix makes CloudWatch Logs Insights queries simple and the data portable if you ever want to ship it somewhere else</li></ol><p>The infrastructure is minimal (one SNS topic, one Lambda, one IAM role), the cost is negligible, and the observability gain is significant. If you’re running SES without this, you’re flying blind.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=746a8e23b7ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 3 — Catalog: PostgreSQL and Hive Metastore]]></title>
            <link>https://medium.com/@akash94thakur/day-3-catalog-postgresql-and-hive-metastore-a70a2dbccbe0?source=rss-36df1949e96a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a70a2dbccbe0</guid>
            <dc:creator><![CDATA[Thinking monster]]></dc:creator>
            <pubDate>Sun, 26 Apr 2026 06:34:20 GMT</pubDate>
            <atom:updated>2026-04-26T06:34:20.439Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A 7-day journey building a production-grade analytics pipeline on your laptop. Day 3 of 7.</em></p><blockquote><strong><em>Companion code:</em></strong><em> everything in this post lives under </em><a href="https://github.com/thinkingmonster/data-pipeline/tree/main/days/day-3"><em>days/day-3/</em></a><em> in the lab repository. Day 3 is a self-contained snapshot that builds on Days 1–2.</em></blockquote><h3>The Claim</h3><p>By the end of today, you will have — on the same laptop — a <strong>PostgreSQL StatefulSet</strong> running as the metadata backend for a <strong>Hive Metastore</strong> Deployment. HMS will be speaking at Thrift on port :9083, configured to treat MinIO as its warehouse via the S3A filesystem, and ready to record (database, table, partition) → s3a://path mappings the moment Spark starts writing in Phase 4.</p><p>You will understand why every modern lakehouse architecture splits the <strong>catalogue</strong> from the <strong>storage</strong>, what HMS actually stores in those ~60 PostgreSQL tables, why HMS speaks a binary RPC protocol from 2007 instead of HTTP, and why the catalogue is not reactive to writes you make directly to object storage.</p><p>You will also learn — by hitting them — two non-obvious quirks of the official apache/hive:4.0.0 image: it doesn&#39;t ship the PostgreSQL JDBC driver, and its default user can&#39;t write to its own lib directory. Both have one-line fixes once you know where to look.</p><p>This is <a href="https://github.com/thinkingmonster/data-pipeline/tree/main/days/day-3">Phase 3</a> of the <a href="https://medium.com/@akash94thakur/day-1-foundation-kafka-schema-registry-and-object-storage-fc15508a5faa">Learning Roadmap.</a></p><h3>Recap — Where We Left Off</h3><p>Days 1 and 2 gave us:</p><ul><li>A 3-broker Strimzi Kafka cluster in KRaft mode</li><li>Three application topics filled with Confluent-Avro wire-format bytes (analytics, engagement-topic, webrtc-analytics)</li><li>Confluent Schema Registry with three subjects, IDs cached in the gateway</li><li>A FastAPI ingest gateway producing at ~10 events per second across simulated virtual classrooms</li><li>MinIO with bucket analytics-lab waiting for somebody to write into it</li></ul><p>Bytes are landing on Kafka. Nobody is reading them yet. MinIO is empty. There is no notion of a “table” anywhere in the stack.</p><p>That changes today — but not the way you might think. Today, we <strong>don’t</strong> consume from Kafka. Today, we <strong>don’t</strong> write any data files. Today, we build the layer that makes “data” addressable as <strong>tables</strong> instead of as object-store keys. Tomorrow Spark will use it.</p><h3>The Slice We’re Building Today</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jATiAdmpVVNgoDgtvhcVyQ.png" /><figcaption>HMS</figcaption></figure><p>One arrow direction matters today: compute (HMS) ↔ metadata (Postgres). The compute → storage path is wired up but unused — Spark in Phase 4 is the first thing that writes a Delta file to MinIO.</p><h3>Why a Catalogue At All?</h3><p>Spark writes Parquet files to s3://bucket/some/folder/. Whoever wants to read them must know the path, schema, and partition layout. Everything is hand-coordinated. It works for one team, one table, one project.</p><p>It stops working the moment you have:</p><ul><li>More than one team writing tables to the same bucket</li><li>More than one engine reading those tables (Spark for ETL, Trino for queries, StarRocks for dashboards)</li><li>Tables with thousands of partitions, where listing the directory is too expensive on every query</li><li>Schema evolution, where readers and writers may disagree on column types until the next deploy</li><li>The need to revoke access to a single table without revoking access to the whole bucket</li></ul><p>A <strong>catalogue</strong> is the layer that solves this. Its only job is to answer:</p><ul><li><em>“What tables exist?”</em> → SHOW TABLES IN db_deltalake</li><li><em>“Where does table X live?”</em> → s3a://analytics-lab/warehouse/bronze/tbl_analytics_bronze/</li><li><em>“What columns does it have?”</em> → typed schema</li><li><em>“What partitions does it have?”</em> → zoneId=1, zoneId=2, …</li><li><em>“What format is it in?”</em> → Delta / Parquet / ORC</li><li><em>“Who can read it?”</em> → ACLs (in the variants that support them)</li></ul><p>The catalogue stores <strong>metadata about data</strong>. It does not store data. The data lives in object storage. The catalogue is the phone book; the data is the house.</p><p>This separation — catalogue ≠ storage — is the <strong>defining feature of the lakehouse architecture</strong>. Everything else in the modern data stack is a consequence of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9EEtsmw-9mUYXVPiv8wHQ.png" /></figure><p>Three boxes. <strong>Data</strong> flows between Compute and Storage. <strong>Metadata</strong> flows between Compute, HMS, and Postgres. They cross exactly once: when Compute writes data, it asks HMS to register the new location.</p><p>This is the same pattern you see at every cloud:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bsrBKsXM7b5rurMMIthLg.png" /></figure><p>We pick HMS for this lab because it’s still the most widely deployed catalogue in production today, and because every other engine in our stack — Spark, StarRocks — speaks its protocol natively.</p><h3>Why Thrift?</h3><p>We say “HMS speaks Thrift on :9083&quot; the same way you&#39;d say &quot;Postgres speaks the Postgres wire protocol on :5432&quot;Thrift is a protocol — specifically, a <strong>binary RPC framework</strong> built at Facebook in 2007. It does three things:</p><ol><li>An <strong>IDL</strong> (interface definition language) — you write a .thrift file describing methods and types</li><li>A <strong>code generator</strong> — thrift --gen java foo.thrift produces server stubs and client libraries in your chosen language</li><li>A <strong>wire format</strong> — compact binary serialisation for the actual RPC traffic</li></ol><p>Compared to alternatives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nFG2LRYGDs9-WHCZiW0wXg.png" /></figure><p>Thrift is gRPC’s older cousin — same idea, eight years earlier. HMS shipped in 2009; gRPC didn’t exist until 2015. The decision tree at the time was: “we need cross-language RPC, JSON over HTTP is too slow and untyped, Java RMI doesn’t help our Python clients” — and Thrift was what was on the shelf.</p><p>The HMS Thrift IDL is <a href="https://github.com/apache/hive/blob/master/standalone-metastore/metastore-common/src/main/thrift/hive_metastore.thrift">hive_metastore.thrift</a> — about 2,000 lines defining methods like:</p><pre>get_databases()                              -&gt; list of DB names<br>get_tables(db, pattern)                      -&gt; list of table names matching glob<br>get_table(db, tbl)                           -&gt; full table metadata<br>get_partitions(db, tbl, max_parts)           -&gt; list of partition specs<br>create_database(db_object)                   -&gt; insert into DBS<br>append_partition(db, tbl, values)            -&gt; insert into PARTITIONS<br>alter_partition(db, tbl, new_part)           -&gt; update PARTITIONS</pre><p>Spark’s HiveMetaStoreClient, StarRocks&#39;s Hive connector, Trino&#39;s Hive connector — they&#39;re all Thrift-generated stubs from that one IDL.</p><p>Three operational consequences of HMS being Thrift, not HTTP:</p><ol><li><strong>Debugging is harder.</strong> Nocurl, no Postman, no browser. You need a Thrift client. kubectl exec into the pod and use the hive or metatool CLIs.</li><li><strong>Load balancers behave differently.</strong> L7 (HTTP-aware) load balancers can’t see method names. You use L4 (TCP) load balancing — no per-method routing.</li><li><strong>Wire compatibility is brittle.</strong> Like protobuf, every IDL change must be additive (new fields with explicit IDs). Get it wrong on an HMS upgrade and every client breaks.</li></ol><p>Modern catalogues (Polaris, Unity, Iceberg REST) deliberately moved off Thrift to HTTP+JSON. HMS is stuck with Thrift because changing it would break every Hive client written in the last 15 years.</p><h3>What’s Actually Inside the Catalogue Database?</h3><p>Run \dt against the metastore Postgres DB schematool has initialised it, and you see roughly <strong>60 tables</strong>. The ones that matter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vLv9V4Eg_Ad-64P3bX1KIQ.png" /></figure><p>Look at this layout once, and you’ll never again be confused about what “the catalogue knows”. The answer is exactly these rows.</p><p>A concrete example. After Spark (Phase 4) writes one Delta table with three partitions zoneId={1,2,3}, the rows look like:</p><pre>SELECT &quot;NAME&quot;, &quot;DB_LOCATION_URI&quot; FROM &quot;DBS&quot;;<br>  -- db_deltalake | s3a://analytics-lab/warehouse/db_deltalake.db</pre><pre>SELECT &quot;TBL_NAME&quot;, &quot;TBL_TYPE&quot; FROM &quot;TBLS&quot;;<br>  -- tbl_analytics_bronze | EXTERNAL_TABLE</pre><pre>SELECT &quot;PART_NAME&quot; FROM &quot;PARTITIONS&quot;;<br>  -- zoneId=1<br>  -- zoneId=2<br>  -- zoneId=3</pre><pre>SELECT &quot;PARAM_KEY&quot;, &quot;PARAM_VALUE&quot; FROM &quot;TABLE_PARAMS&quot;<br>WHERE &quot;PARAM_KEY&quot; LIKE &#39;spark.sql.sources%&#39;;<br>  -- spark.sql.sources.provider     = delta<br>  -- spark.sql.sources.schema.numParts = 1<br>  -- spark.sql.sources.schema.part.0   = {&quot;type&quot;:&quot;struct&quot;,&quot;fields&quot;:[...]}</pre><p>Everything you’d want to know about a table is the rows in these tables. That’s the whole catalogue model.</p><h3>Why a Separate Service? Couldn’t Spark Just Talk to Postgres?</h3><p>Technically, yes — and Hive’s <em>embedded</em> metastore works exactly that way. Every client opens its own JDBC connection to the catalogue DB. So why bother running a standalone HMS pod?</p><p>Five reasons, all of which become obvious at production scale:</p><ol><li><strong>Connection pool control.</strong> 200 Spark executors opening 200 Postgres connections will melt a small DB. HMS pools them down to a handful.</li><li><strong>Authentication boundary.</strong> Kerberos/LDAP auth occurs at HMS, not in Postgres. Clients don’t need DB credentials.</li><li><strong>Schema upgrades happen in one place.</strong> Bumping HMS gives all clients the new schema view at once. With embedded, every client version ships its own schema code.</li><li><strong>Caching.</strong> HMS has an optional cached-metastore mode that serves get_partitions from memory.</li><li><strong>Blast-radius isolation.</strong> A compromised Spark cluster can’t DROP TABLE directly — it goes through HMS, which can enforce ACLs.</li></ol><p>Our lab runs the simplest form: one HMS replica, one Postgres, no auth. Everything in the list above is what you’d add in production.</p><h3>What HMS Is Not</h3><p>This is the part that trips people up. HMS sounds like it owns the tables. It doesn’t — it owns the <em>metadata about</em> tables. Subtle distinction, enormous consequences.</p><h3>HMS does not watch storage</h3><p>If you run mc cp file.parquet s3://analytics-lab/warehouse/t/zoneId=99/ and then SELECT * FROM t WHERE zoneId=99 through Spark — you get <strong>zero rows</strong>. The data is there. HMS doesn&#39;t know. Spark asks HMS, &quot;What partitions exist?&quot; HMS says {1,2,3}Spark reads only those prefixes.</p><p>Two ways out:</p><ul><li><strong>MSCK REPAIR TABLE t</strong> — HMS does a listing diff: scans the table&#39;s root path, compares directory names to known partitions, and adds the missing ones. Works because partition paths follow the key=value/ convention.</li><li><strong>ALTER TABLE t ADD PARTITION (zoneId=99) LOCATION &#39;s3a://...&#39;</strong> — explicit registration.</li></ul><h3>HMS does not know about the table content</h3><p>HMS has column statistics — LOW_VALUE, HIGH_VALUE, NUM_NULLS. They&#39;re only accurate if someone ran ANALYZE TABLE recently. Nothing automatically refreshes them on write. Stale stats = bad query plans.</p><h3>HMS has no referential integrity with storage</h3><p>You can DROP TABLE in HMS without deleting the S3 files (for EXTERNAL_TABLEs, which are the lakehouse defaults. You can delete the S3 files and leave the HMS row pointing at nothing. HMS will happily return a table whose data has been removed. Clients receive a &quot;file not found&quot; error at query time.</p><h3>Delta Lake relaxes HMS’s role</h3><p>In the pure-Hive world, HMS is the source of truth for partitions. With Delta Lake (which Phase 4 uses), HMS stores only the <em>table root path</em>. Inside that path, _delta_log/NNN.json files describe what&#39;s actually live: which Parquet files matter, which are tombstoned, and the current schema.</p><p>Net effect: with Delta, HMS shrinks to a <strong>naming service</strong>. “Find me the root path for db_deltalake.tbl_analytics_bronze.&quot; Everything else is in the _delta_log/.</p><p>This is why experienced lakehouse engineers say “we’re moving off HMS” — Iceberg + REST catalogue (Polaris, Nessie, Unity) gives you the same naming service over HTTP + JSON + fine-grained RBAC, without the Postgres + Thrift baggage. We use HMS in this lab because it’s the most prevalent catalogue in production <em>today</em>, but you should know the industry&#39;s trajectory.</p><h3>The hive-site.xml Contract</h3><p>HMS reads exactly <strong>one</strong> config file at startup. Every knob lives there. The ones that matter for us:</p><pre>&lt;property&gt;<br>  &lt;name&gt;javax.jdo.option.ConnectionURL&lt;/name&gt;<br>  &lt;value&gt;jdbc:postgresql://hms-postgres:5432/metastore&lt;/value&gt;<br>&lt;/property&gt;</pre><p><em>Where the catalogue DB lives. </em><em>javax.jdo because HMS uses DataNucleus (a JDO-over-JPA layer) internally.</em></p><pre>&lt;property&gt;<br>  &lt;name&gt;datanucleus.schema.autoCreateAll&lt;/name&gt;<br>  &lt;value&gt;false&lt;/value&gt;<br>&lt;/property&gt;<br>&lt;property&gt;<br>  &lt;name&gt;hive.metastore.schema.verification&lt;/name&gt;<br>  &lt;value&gt;true&lt;/value&gt;<br>&lt;/property&gt;</pre><p><em>Don’t auto-create tables. Check the schema version on boot, refuse to start if it’s wrong. These two together force you to run </em><em>schematool -initSchema (or </em><em>-upgradeSchema) explicitly. Prod-correct behaviour.</em></p><pre>&lt;property&gt;<br>  &lt;name&gt;metastore.warehouse.dir&lt;/name&gt;<br>  &lt;value&gt;s3a://analytics-lab/warehouse&lt;/value&gt;<br>&lt;/property&gt;</pre><p><em>Default location for </em><em>CREATE TABLE without an explicit </em><em>LOCATION.</em></p><pre>&lt;property&gt;<br>  &lt;name&gt;fs.s3a.endpoint&lt;/name&gt;<br>  &lt;value&gt;http://minio:9000&lt;/value&gt;<br>&lt;/property&gt;<br>&lt;property&gt;<br>  &lt;name&gt;fs.s3a.path.style.access&lt;/name&gt;<br>  &lt;value&gt;true&lt;/value&gt;<br>&lt;/property&gt;<br>&lt;property&gt;<br>  &lt;name&gt;fs.s3a.aws.credentials.provider&lt;/name&gt;<br>  &lt;value&gt;org.apache.hadoop.fs.s3a.auth.EnvironmentVariableCredentialsProvider&lt;/value&gt;<br>&lt;/property&gt;</pre><p><em>Point Hadoop S3A at MinIO. Path-style URLs (</em><em>http://minio/bucket/key) because MinIO doesn&#39;t serve virtual-host-style by default. Credentials via env vars so the XML stays credential-free.</em></p><p>The full file lives in <a href="https://medium.com/days/day-3/k8s/03-postgres-hms/hms-configmap.yaml">hms-configmap.yaml</a>. Two things to notice about what&#39;s <em>not</em> in it:</p><ol><li><strong>No database password.</strong> It would be inlined in &lt;javax.jdo.option.ConnectionPassword&gt; — and in production, that&#39;s a real problem (the file gets dumped by hive --service metatool -showConfig pod env inspectors). We accept it for this lab because the password is publicly available hive/hive. In a real deploy, you&#39;d use a secret-aware JDBC URL or a custom ConnectionPasswordProvider.</li><li><strong>No S3 credentials.</strong> We use EnvironmentVariableCredentialsProvider, which reads AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY at runtime. We populate those env vars from a separate Kubernetes Secret. This mirrors the IRSA pattern on EKS — pods get AWS creds from their IAM role, no hardcoded keys anywhere.</li></ol><h3>The Two Quirks of apache/hive:4.0.0</h3><p>Both of these cost real time during the lab build. Neither is documented in the image’s README. Both have one-line fixes once you know them.</p><h3>Quirk 1 — The image doesn’t ship a Postgres JDBC driver</h3><p>Inspect /opt/hive/lib:</p><pre>kubectl run hms-debug --rm -it --image=apache/hive:4.0.0 \<br>  --command -- ls /opt/hive/lib | grep -i postgres<br># (no output)</pre><p>Empty. apache/hive:4.0.0 ships only the embedded Derby driver. The moment HMS&#39;s entry point callsschematool -initOrUpgradeSchema -dbType postgres, you get:</p><pre>java.lang.ClassNotFoundException: org.postgresql.Driver<br>Schema initialization failed!</pre><p>This is by design — JDBC driver licensing varies, so the base image stays Postgres-free. You bring your own.</p><p><strong>Fix:</strong> an initContainer that downloads postgresql-42.7.4.jar into a shared emptyDir, and a startup command in the main container that copies it into /opt/hive/lib/ before exec&#39;ing the entrypoint. Excerpt from <a href="https://medium.com/days/day-3/k8s/03-postgres-hms/hms-deployment.yaml">hms-deployment.yaml</a>:</p><pre>initContainers:<br>  - name: fetch-postgres-jdbc<br>    image: curlimages/curl:8.10.1<br>    command:<br>      - sh<br>      - -c<br>      - |<br>        set -eu<br>        JAR=/drivers/postgresql.jar<br>        if [ ! -f &quot;$JAR&quot; ]; then<br>          curl -fsSL -o &quot;$JAR&quot; \<br>            https://jdbc.postgresql.org/download/postgresql-42.7.4.jar<br>        fi<br>    volumeMounts:<br>      - name: drivers<br>        mountPath: /drivers</pre><pre>containers:<br>  - name: hive-metastore<br>    image: apache/hive:4.0.0<br>    command:<br>      - /bin/bash<br>      - -c<br>      - |<br>        set -euo pipefail<br>        cp /drivers/postgresql.jar /opt/hive/lib/postgresql.jar<br>        cp /hive-site-cm/hive-site.xml /hive-conf/hive-site.xml<br>        exec /entrypoint.sh</pre><p>This is the same pattern you’ll hit with <strong>every</strong> generic database-backed Java application: Trino → any DB, Flink → any CDC source, Debezium → all of its connectors. Drivers are licensed separately, so they stay out of the base image, and you bring them in at deploy time.</p><h3>Quirk 2 — The image’s default user can’t write to /opt/hive/lib</h3><p>Apply the deployment with the JDBC fix, and you still get:</p><pre>cp: cannot create regular file &#39;/opt/hive/lib/postgresql.jar&#39;: Permission denied</pre><p>The image’s Dockerfile sets USER hive as the final stage. The hive user doesn&#39;t own /opt/hive/lib, so the copy fails.</p><p><strong>Three options to fix:</strong></p><ol><li><strong>Build a custom image.</strong> FROM apache/hive:4.0.0, then COPY postgresql.jar /opt/hive/lib/. Cleanest in production (no runtime download), but adds a build pipeline.</li><li><strong>Use </strong><strong>HIVE_AUX_JARS_PATH.</strong> Hive&#39;s classpath logic respects this env var; you&#39;d put the jar at a writable path (/opt/hive/aux/postgresql.jar) and set the env var. Works for the metastore runtime; needs verification for schematool.</li><li><strong>Run as root.</strong> securityContext.runAsUser: 0 on the pod. No isolation gain in a single-tenant lab.</li></ol><p>We picked option 3:</p><pre>spec:<br>  securityContext:<br>    runAsUser: 0</pre><p>This is a lab-honest concession. In a production deploy with this image, you’d build a derived image (option 1) so that no runtime privilege elevation is needed.</p><p>The pattern matters: most “official” OCI images that say “just run me” embed assumptions about runtime writability. When you wire in extra jars, certificates, or config, you either build a derived image (prod shape) or relax the security context (lab shape). The middle path with HIVE_AUX_JARS_PATH works but adds enough complexity that it&#39;s rarely worth it for a small dependency.</p><h3>How the Pod Actually Comes Up</h3><p>Trace the boot sequence end-to-end:</p><pre>1. Pod scheduled<br>       │<br>       ▼<br> 2. initContainer  fetch-postgres-jdbc  runs<br>       │  curl -o /drivers/postgresql.jar https://jdbc.postgresql.org/...<br>       │  exit 0<br>       ▼<br> 3. Main container  hive-metastore  starts<br>       │  cp /drivers/postgresql.jar /opt/hive/lib/postgresql.jar<br>       │  cp /hive-site-cm/hive-site.xml /hive-conf/hive-site.xml<br>       │  exec /entrypoint.sh<br>       │<br>       │  Inside /entrypoint.sh (image-provided):<br>       │    HIVE_CONF_DIR=$HIVE_HOME/conf<br>       │    symlink /hive-conf/* into $HIVE_HOME/conf/<br>       │    initialize_hive() {<br>       │      schematool -dbType postgres -initOrUpgradeSchema --verbose<br>       │    }<br>       │    initialize_hive       ← runs against Postgres, creates 60 tables<br>       │                            (or no-ops if schema already current)<br>       │    if SERVICE_NAME == &quot;metastore&quot;:<br>       │      exec hive --service metastore   ← Java process binds :9083<br>       │<br>       ▼<br> 4. Readiness probe  TCP :9083  succeeds<br> 5. Pod marked Ready</pre><p>A few things to internalise:</p><ul><li><strong>-initOrUpgradeSchema is idempotent in Hive 4.</strong> Fresh DB → creates 60 tables. Already-initialised DB → checks the version, no-op. This is why we don&#39;t need a separate Kubernetes Job to run schematool once before HMS boots — the entrypoint handles it on every start.</li><li><strong>The schema-init log is verbose and educational.</strong> Watch with make hms-logs on first boot — you&#39;ll see ~60 CREATE TABLE statements stream past, ending with INSERT INTO &quot;VERSION&quot; (&quot;VER_ID&quot;, &quot;SCHEMA_VERSION&quot;, &quot;VERSION_COMMENT&quot;) VALUES (1, &#39;4.0.0&#39;, &#39;Hive release version 4.0.0&#39;). That&#39;s the row that hive.metastore.schema.verification=true checks for on every subsequent boot.</li><li><strong>Postgres readiness is implicit.</strong> HMS doesn’t wait for Postgres — it just tries to connect. If Postgres is still starting, HMS crash-loops a few times and self-recovers when Postgres becomes reachable. This is fine for a lab; in production, you’d add an initContainer that explicitly waits on Postgres readiness.</li></ul><h3>Running It — Fresh Start to First Catalogue Query</h3><p>We continue the Day 1 / Day 2 pattern: destroy yesterday’s state, rebuild deterministically, and verify each layer before moving on.</p><p>All commands run from days/day-3/.</p><h3>Step 0 — Destroy and rebuild</h3><pre>make minikube-destroy<br>make minikube-up</pre><h3>Step 1 — Day 1 + Day 2 (carried forward unchanged)</h3><pre>make phase0          &amp;&amp; make verify-phase0<br>make minio           &amp;&amp; make verify-minio<br>make kafka           &amp;&amp; make verify-kafka<br>make schema-registry &amp;&amp; make verify-schema-registry<br>make apps-build      &amp;&amp; make apps-deploy</pre><p>Same targets. Same output. After this is complete, events are flowing from classroom-simulator through mock-gap into Kafka.</p><h3>Step 2 — Phase 3a: Postgres for HMS</h3><pre>make postgres<br>make verify-postgres</pre><p>What this does:</p><ul><li>Applies <a href="https://medium.com/days/day-3/k8s/03-postgres-hms/postgres-secret.yaml">postgres-secret.yaml</a> — DB user/pass/dbname (hive/hive/metastore)</li><li>Applies <a href="https://medium.com/days/day-3/k8s/03-postgres-hms/postgres-service.yaml">postgres-service.yaml</a> — ClusterIP hms-postgres:5432 plus a headless Service for StatefulSet DNS</li><li>Applies <a href="https://medium.com/days/day-3/k8s/03-postgres-hms/postgres-statefulset.yaml">postgres-statefulset.yaml</a> — Postgres 16, 10Gi PVC, mounted at /var/lib/postgresql/data</li><li>Waits for rollout Ready (~30–60s)</li></ul><p>verify-postgres runs three checks: StatefulSet Ready, psql \l shows the metastore DB, and a one-shot Postgres pod connects via the Service and runs SELECT 1.</p><h3>Step 3 — Phase 3b: HMS config + deploy</h3><pre>make hms-config<br>make hms-deploy</pre><p>hms-config applies the S3A credentials Secret and the hive-site.xml ConfigMap. hms-deploy applies the Deployment and Service, then waits for the rollout to be Ready (~90–120s on first run, including image pull).</p><p>Watch the entrypoint do its thing:</p><pre>make hms-logs</pre><p>You’ll see the JDBC driver fetch, then ~60 CREATE TABLE statements stream past, then:</p><pre>Initialized schema successfully..<br>+ exec /opt/hive/bin/hive --skiphadoopversion --skiphbasecp --verbose --service metastore<br>2026-04-25 ...: Starting Hive Metastore Server<br>Starting hive metastore on port 9083</pre><p>That last line is the one that matters. From here on, the Thrift listener is live.</p><h3>Step 4 — Verify end-to-end</h3><pre>make verify-hms</pre><p>Five checks:</p><ol><li>HMS Deployment Ready</li><li>Postgres has the HMS schema tables (DBS, TBLS, PARTITIONS present)</li><li>VERSION row populated (proves schematool ran)</li><li>Thrift :9083 reachable from a sidecar pod</li><li>metatool -listFSRoot round-trips through HMS → Postgres → S3A</li></ol><p>The last check is the litmus test. If metatool can list the FS root, then HMS has parsed hive-site.xml, connected to Postgres, resolved the S3A filesystem, <em>and</em> authenticated to MinIO via env-var credentials. Four layers in one command.</p><h3>Behind the Scenes — Commands That Show What’s Actually Happening</h3><p>“HMS Ready” tells you the Java process is up. It does not tell you what’s stored, what the schema looks like, or that Spark would actually be able to register a table tomorrow. For each of those, there’s a command that proves the thing.</p><h3>See the catalogue schema in Postgres</h3><pre>make hms-psql</pre><p>Then inside psql:</p><pre>\dt<br>-- ~60 tables. Key ones: DBS, TBLS, PARTITIONS, SDS, COLUMNS_V2, TABLE_PARAMS, SERDES, VERSION</pre><pre>SELECT * FROM &quot;VERSION&quot;;<br>-- VER_ID | SCHEMA_VERSION |       VERSION_COMMENT<br>-- -------+----------------+------------------------------<br>--      1 | 4.0.0          | Hive release version 4.0.0</pre><pre>SELECT &quot;NAME&quot;, &quot;DB_LOCATION_URI&quot; FROM &quot;DBS&quot;;<br>-- empty for now — Spark hasn&#39;t created any DBs yet</pre><h3>Watch the HMS schema row appear after a write</h3><p>In one shell, open psql and watch:</p><pre>SELECT count(*) FROM &quot;DBS&quot;;<br>-- 0</pre><p>In another shell, create a database via HMS directly. The image ships the Hive CLI, which talks to HMS over Thrift on localhost:9083:</p><pre>kubectl --context=data-pipeline -n data-pipeline exec deploy/hive-metastore -- \<br>  /opt/hive/bin/hive -e &quot;CREATE DATABASE IF NOT EXISTS db_deltalake; SHOW DATABASES;&quot;</pre><p>Expected output:</p><pre>OK<br>default<br>db_deltalake<br>Time taken: 0.582 seconds</pre><p>Now go back to psql:</p><pre>SELECT &quot;NAME&quot;, &quot;DB_LOCATION_URI&quot; FROM &quot;DBS&quot;;<br>-- default      | s3a://analytics-lab/warehouse<br>-- db_deltalake | s3a://analytics-lab/warehouse/db_deltalake.db</pre><p>The row showed up. That’s the entire HMS round-trip in miniature: Thrift call → DataNucleus → JDBC → INSERT INTO DBS. Everything Spark does in Phase 4 is more of the same, just with TBLS PARTITIONS rows piling up.</p><h3>See the S3A filesystem from HMS’s perspective</h3><pre>POD=$(kubectl --context=data-pipeline -n data-pipeline get pod -l app=hive-metastore \<br>        -o jsonpath=&#39;{.items[0].metadata.name}&#39;)</pre><pre>kubectl --context=data-pipeline -n data-pipeline exec &quot;$POD&quot; -- \<br>  /opt/hive/bin/metatool -listFSRoot</pre><p>Expected:</p><pre>Listing FS Roots..<br>s3a://analytics-lab/warehouse</pre><p>metatool is the Hive maintenance CLI. -listFSRoot walks every DBS.DB_LOCATION_URI and prints the unique filesystem roots — proving that HMS has correctly parsed the warehouse config <em>and</em> can resolve the S3A filesystem via its env-var credentials.</p><h3>See the JDBC driver actually loaded</h3><pre>kubectl --context=data-pipeline -n data-pipeline exec deploy/hive-metastore -- \<br>  ls /opt/hive/lib | grep -i postgres</pre><p>Expected:</p><pre>postgresql.jar</pre><p>If this is empty, the initContainer didn’t run, the copy failed, or the entrypoint started before the copy finished, and HMS would not be Ready. This is your sanity check that the multi-step boot actually worked.</p><h3>See the env-based S3A credentials</h3><pre>kubectl --context=data-pipeline -n data-pipeline exec deploy/hive-metastore -- \<br>  env | grep AWS_</pre><p>Expected:</p><pre>AWS_ACCESS_KEY_ID=minioadmin<br>AWS_SECRET_ACCESS_KEY=minioadmin</pre><p>The values come from the s3a-credentials Secret. The names match what EnvironmentVariableCredentialsProvider looks for. If either is missing, S3A operations would fail, Access Denied even though the values are right.</p><h3>The Failures We Hit (And What They Teach)</h3><p>Both happened during the actual build of Day 3. Knowing the shape of each error is 80% of the diagnosis.</p><h3>Failure 1 — cp: cannot create regular file &#39;/opt/hive/lib/postgresql.jar&#39;: Permission denied</h3><p><strong>Symptom:</strong> HMS pod CrashLoopBackOff. Main-container logs end with the Permission denied line and nothing else.</p><p><strong>Root cause:</strong> the image’s Dockerfile sets USER hive. The hive user doesn&#39;t own /opt/hive/lib, so the JDBC driver copy fails.</p><p><strong>Fix (already applied):</strong> securityContext.runAsUser: 0 on the pod.</p><p><strong>What it teaches:</strong> “Official” container images often embed assumptions about runtime writability that break the moment you customise them. When wiring extra jars, certificates, or config into a stock image, you either build a derived image (production shape — additional pipeline complexity, no runtime privilege) or relax the security context (lab shape — simple, single-tenant only).</p><h3>Failure 2 — ClassNotFoundException: org.postgresql.Driver</h3><p><strong>Symptom:</strong> the entrypoint’s schematool -initOrUpgradeSchema fails with:</p><pre>Underlying cause: java.lang.ClassNotFoundException : org.postgresql.Driver<br>Schema initialization failed!</pre><p>This was the first failure we actually hit, and it was nasty to diagnose because the Job we initially used (since removed) had backoffLimit: 4 and the Pods got garbage-collected before we could read their logs. Hours wasted. Lesson: when a Job or Pod fails fast, set restartPolicy: Never and backoffLimit: 0 <em>First</em>, then debug. Or just run the failing command in a one-shot pod kubectl run --restart=Never so you keep the logs.</p><p><strong>Root cause:</strong> apache/hive:4.0.0 ships only the Derby driver. PostgreSQL JDBC isn&#39;t bundled.</p><p><strong>Fix (already applied):</strong> the fetch-postgres-jdbc initContainer downloads the driver; the main container copies it into /opt/hive/lib/.</p><p><strong>What it teaches:</strong> Every generic database-backed Java application has this gap. JDBC driver licensing varies enough that base images stay backend-free. The fix pattern (initContainer → shared volume → copy at start) generalises to any image where you need to side-load a dependency without rebuilding.</p><h3>Failure 3 (potential) — MetaException: Version information not found in metastore</h3><p>We didn’t hit this in the build, but you will if you ever swap Postgres backends without rerunning init. The shape is:</p><pre>MetaException(message:Version information not found in metastore.)</pre><p><strong>Root cause:</strong> the entrypoint’s schematool didn’t run, didn’t complete, or ran against a different Postgres than the one HMS is now reading. HMS reads SELECT * FROM &quot;VERSION&quot; on startup; no row → refuse to start.</p><p><strong>Fix:</strong> restart the deployment. The entry point runs -initOrUpgradeSchema again, which is idempotent — fresh DB gets the schema, already-initialised DB is a no-op:</p><pre>kubectl --context=data-pipeline -n data-pipeline rollout restart deployment/hive-metastore</pre><p><strong>What it teaches:</strong> hive.metastore.schema.verification=true is the prod-safe default. It forces schema changes to be an explicit migration step rather than &quot;the app will fix it on boot&quot;. You want this in prod — you do not want HMS auto-upgrading its own schema mid-rollout.</p><h3>Failure 4 (potential) — AccessDenied: 403 from S3A</h3><p>If you misconfigure S3A, metatool -listFSRoot will print:</p><pre>Failed to listObjects: AmazonS3Exception:<br>  Access Denied (Service: Amazon S3; Status Code: 403)</pre><p>Root cause tree:</p><ol><li><strong>Env vars not set.</strong> kubectl exec deploy/hive-metastore -- env | grep AWS_ should show both. If missing, the Secret isn&#39;t wired.</li><li><strong>Endpoint wrong.</strong> fs.s3a.endpoint must be http://minio:9000, not https, not minio:9000 (no scheme).</li><li><strong>Path style disabled.</strong> fs.s3a.path.style.access=true is required for MinIO. Without it, Hadoop tries http://analytics-lab.minio:9000/ (virtual-host style), which MinIO doesn&#39;t serve by default.</li></ol><p><strong>What it teaches:</strong> S3A misconfig is the single most common HMS-with-MinIO failure. In production, the same shape appears differently (IRSA fails silently, bucket policies block the role, endpoint URLs drift between regions), but the diagnostic question is identical: “Access Denied” tells you nothing — you check each layer in turn until one is wrong.</p><h3>Foreshadowing — How Phase 4 Uses What We Built Today</h3><p>Tomorrow Spark starts writing. When it does, it touches all three corners of our triangle in one transaction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7ZiZoYfoI1q_injD-45Dw.png" /></figure><p>Three pieces of state. Any two out of sync = data correctness bug.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAmBPxX_EvA71kbDe067Gw.png" /></figure><p>That’s why we needed HMS <em>before</em> Spark. Without it, Spark’s Delta writer falls back to its embedded Derby catalogue — the table only exists in that one Spark session, and StarRocks (Phase 6) has no way to find it later.</p><h3>Points to Ponder</h3><p>These don’t have quick answers. Sit with each.</p><ol><li><strong>If you drop the Postgres StatefulSet’s PVC, what breaks?</strong> <strong>What survives?</strong> What’s the recovery procedure? (Hint: object data is fine; HMS metadata is gone. Recovery requires starting schematool -initSchema from scratch, then a list of CREATE TABLE statements you&#39;d better have written down somewhere, and then MSCK REPAIR TABLE for every partitioned table. This is why HMS Postgres backup is non-optional in production.)</li><li><strong>HMS has two schema-verification knobs: </strong><strong>hive.metastore.schema.verification and </strong><strong>datanucleus.schema.autoCreateAll.</strong> They&#39;re related but not redundant. What does each gate do? (Hint: one gates startup, the other gates runtime DDL.)</li><li><strong>Why is HMS deployed as a Kubernetes</strong><strong>Deployment, but Postgres as a </strong><strong>StatefulSet?</strong> What invariants does each satisfy? (Hint: HMS is stateless — all state is in Postgres. A new HMS pod can replace an old one. Postgres needs stable identity and stable PVC binding.)</li><li><strong>You change </strong><strong>metastore.warehouse.dir from </strong><strong>s3a://analytics-lab/warehouse to </strong><strong>s3a://analytics-lab/newwarehouse after writing one table.</strong> What happens to existing tables? To new ones? (Hint: existing DB_LOCATION_URI rows are frozen at creation time — they don&#39;t auto-update. New DBs get the new warehouse. Moving the existing table means ALTER DATABASE ... SET LOCATION actually copying the files.)</li><li><strong>Run </strong><strong>\dt In psql after one </strong><strong>CREATE DATABASE and nothing else.</strong> Which of the ~60 HMS tables actually have rows? Which stay empty until CREATE TABLE? (Hint: only 1–2 tables populated at this point. Worth seeing firsthand — it teaches you which tables to check first when debugging.)</li><li><strong>HMS uses Thrift; modern catalogues use HTTP+REST.</strong> What makes the Thrift design painful in 2026? What did it solve in 2009? (Hint: cross-language RPC was hard then; debugging HTTP is easy now.)</li><li><strong>Why is the HMS schema upgrade path version-sensitive?</strong> Why do you have to step through versions instead of jumping straight from 2.3 to 4.0? (Hint: schematool migration scripts are per-version diffs, not idempotent CREATEs. Skipping versions = running scripts in the wrong order = corrupt schema.)</li></ol><h3>Key Takeaways</h3><p>If you remember only these eight:</p><ol><li><strong>Catalogue stores metadata only.</strong> Tables live in storage; HMS stores where they are, their shape, and which partitions exist. Not one byte of analytics data passes through HMS.</li><li><strong>HMS is synchronous and pull-based.</strong> No push, no events, no listeners. Clients ask; HMS answers. Staleness is the caller’s problem.</li><li><strong>schematool is your migration runner.</strong> Explicit, version-sensitive. -initSchema once ever; -upgradeSchema for every bump. Hive 4&#39;s -initOrUpgradeSchema collapses both into one idempotent command, which is why the official entrypoint can run it on every boot.</li><li><strong>hive-site.xml is the one config file.</strong> No env overrides worth relying on. Keep credentials out — env-var providers for S3A, secret-aware JDBC URLs for the catalogue DB.</li><li><strong>Thrift </strong><strong>:9083 is the public API.</strong> TCP-level health checks prove the listener is alive; metatool -listFSRoot proves the full chain (HMS → Postgres → S3A).</li><li><strong>Postgres is the real state; HMS is stateless.</strong> Deploy HMS horizontally (behind a Service), Postgres vertically (one StatefulSet, careful backups, point-in-time recovery in production).</li><li><strong>Delta relaxes HMS’s role.</strong> In the lakehouse, HMS is mostly a naming service; it _delta_log/ is the primary source of truth. With raw Parquet + Hive, HMS <em>is</em> the source of truth. Different failure modes.</li><li><strong>MSCK REPAIR TABLE is your reconciliation tool.</strong> When the catalogue and storage drift, listing-diff from storage back into HMS. Know it exists.</li></ol><h3>Checkpoints — Can You Answer These?</h3><p>If yes, Day 4 will land cleanly.</p><ol><li>What does HMS store, and what does it not store? Where does the actual table data live?</li><li>Why is Hive Metastore separated from its Postgres backend instead of being embedded?</li><li>What is Thrift, and why does HMS use it instead of HTTP?</li><li>What does schematool -initOrUpgradeSchema do, and why is it safe to run on every pod start?</li><li>Name three of the ~60 HMS catalogue tables and what each holds.</li><li>What does it MSCK REPAIR TABLE do, and when do you need it?</li><li>Why is EnvironmentVariableCredentialsProvider a better choice for S3A than inlining keys in hive-site.xml?</li><li>With Delta Lake, what role does HMS play vs. what role does _delta_log/ play?</li></ol><h3>What’s Next — Day 4</h3><p>We have a catalogue. We have an empty warehouse. We have events landing in Kafka. Tomorrow we connect them.</p><p><strong>Day 4 — Compute: Spark Operator and Structured Streaming.</strong> We’ll deploy the spark-operator (CRDs and controller), Then submit four SparkApplication CRs that run inside a single Spark driver: three Structured Streaming queries (one per topic, writing to Delta tables in dl_analytics_bronze style) and a JobControlStream that watches for meeting_end events and triggers downstream Airflow runs (in Phase 5).</p><p>You’ll learn:</p><ul><li>The SparkApplication CR lifecycle and why operators beat spark-submit</li><li>Structured Streaming semantics: micro-batches, watermarks, stateful operators</li><li>Checkpointing — the most important concept in the entire pipeline</li><li>Why “exactly-once” is a property of (source + sink + checkpoint), not Spark alone</li><li>How Delta Lake’s _delta_log/000.json actually commits an atomic write</li><li>How Spark calls HMS create_table_with_environment_context + append_partition as part of its write path</li></ul><p>Phase 4 is the longest day in the lab (~6 hours of focused work) and the densest in learning. HMS will suddenly get interesting once Delta starts writing to it.</p><p>See you then.</p><p><em>This is part of a 7-day series building a full analytics pipeline from scratch on Minikube. </em><a href="https://medium.com/day-0-kickoff.md"><em>Day 0 — Kickoff</em></a><em>. </em><a href="https://medium.com/day-1-foundation.md"><em>Day 1 — Foundation</em></a><em>. </em><a href="https://medium.com/day-2-event-source.md"><em>Day 2 — Event Source</em></a><em>. </em><a href="https://medium.com/"><em>All posts and source code</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a70a2dbccbe0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Subnet That Lied: Debugging EKS CNI IP Exhaustion That Wasn’t]]></title>
            <link>https://medium.com/@akash94thakur/the-subnet-that-lied-debugging-eks-cni-ip-exhaustion-that-wasnt-4244bce53e83?source=rss-36df1949e96a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4244bce53e83</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[aws-cni]]></category>
            <dc:creator><![CDATA[Thinking monster]]></dc:creator>
            <pubDate>Wed, 22 Apr 2026 03:00:21 GMT</pubDate>
            <atom:updated>2026-04-22T03:00:21.864Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A war story about subnet fragmentation, a 2.5-hour outage, and the invisible failure mode hiding inside a feature you probably enabled and forgot about.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNhjF5fwYhtsbJA8jJIUSA.png" /><figcaption>AWS CNI</figcaption></figure><p>It was a routine Tuesday afternoon when the alerts started rolling in.</p><p>Airflow Spark jobs failing. Fluent Bit not running. EBS CSI driver pods stuck. Over 120 pods across the cluster frozen in ContainerCreating or Init:0/1 — just sitting there, never starting.</p><p>The cluster had autoscaled earlier. Nothing unusual about that — it happens all the time. 11 nodes had quietly grown to 33 nodes in roughly 11 minutes. The nodes were healthy. The control plane was healthy. Every node had registered successfully with the cluster.</p><p>And yet pods simply refused to start.</p><h3>“Failed to assign an IP address to container”</h3><p>The first real clue came from kubectl describe on one of the stuck pods:</p><pre>Failed to create pod sandbox: rpc error: code = Unknown desc = failed to set up<br>sandbox container: failed to set up network for sandbox: NetworkPlugin cni<br>failed to set up pod network: failed to assign an IP address to container</pre><p>The CNI couldn’t assign an IP address. That’s odd — the subnets had hundreds of free IPs. AWS Console confirmed it: over 600 available IPs in one subnet, over 500 in the other. By any reasonable measure, we had plenty of room.</p><p>So why were pods failing with IP assignment errors?</p><h3>Peering Inside the Node</h3><p>The key tool here was one most engineers never reach for: the <strong>aws-node introspection endpoint</strong>.</p><p>Every aws-node DaemonSet pod exposes a local HTTP API on port 61679. It shows you exactly what IPAMD — the IP address management daemon — thinks the node&#39;s IP pool looks like. Not what AWS thinks. Not what the VPC thinks. What the node&#39;s own CNI agent believes it has.</p><pre>AWSNODE=$(kubectl get pods -n kube-system -l k8s-app=aws-node --no-headers \<br>  -o custom-columns=&#39;NAME:.metadata.name,NODE:.spec.nodeName&#39; \<br>  | grep &lt;node-ip-fragment&gt; | awk &#39;{print $1}&#39;)</pre><pre>kubectl port-forward -n kube-system $AWSNODE 61679:61679 &amp;<br>curl -s <a href="http://localhost:61679/v1/enis">http://localhost:61679/v1/enis</a> | python3 -m json.tool</pre><p>The response was stark:</p><pre>{<br>  &quot;TotalIPs&quot;: 0,<br>  &quot;AssignedIPs&quot;: 0<br>}</pre><p>TotalIPs: 0. On every single new node. IPAMD hadn&#39;t failed with a crash or an error log. It had just silently given up trying to allocate IPs — and every pod scheduled to those nodes was doomed.</p><h3>The Diagnosis: Fragmentation, Not Exhaustion</h3><p>Here’s where it gets interesting. The subnets weren’t <em>exhausted</em>. They were <em>fragmented</em>.</p><p>The cluster was running with <strong>prefix delegation</strong> enabled (ENABLE_PREFIX_DELEGATION=true). This is an AWS VPC CNI feature that lets a node get a whole /28 block (16 IPs) assigned to an ENI at once, rather than one IP at a time. It&#39;s great for high-density clusters — fewer EC2 API calls, more IPs per node, better scaling.</p><p>The catch: /28 blocks must be <strong>contiguous</strong> in the subnet&#39;s address space. AWS needs to find 16 aligned, adjacent IPs to hand you a prefix block.</p><p>Over five days of normal cluster activity — pods starting and stopping, nodes recycling, IPs being allocated and released one at a time — the subnets had become Swiss cheese. Individual IPs were plentiful. But contiguous /28 blocks? Gone.</p><p>When we tried to reproduce the failure directly via the EC2 API:</p><pre>aws ec2 assign-private-ip-addresses \<br>  --network-interface-id $ENI_ID \<br>  --ipv4-prefix-count 1</pre><p>The response was immediate and unambiguous:</p><pre>InsufficientCidrBlocks: The specified subnet does not have enough free<br>cidr blocks to satisfy the request.</pre><p>There it was. Not “InsufficientIPAddresses.” Not “SubnetFull.” InsufficientCidrBlocks — because the fragmentation had destroyed the contiguous blocks that prefix delegation requires, even while the raw IP count looked fine.</p><h3>The Fix — and the Second Problem It Created</h3><p>The fastest fix was to disable prefix delegation and fall back to individual secondary IP allocation:</p><pre>kubectl set env daemonset aws-node -n kube-system \<br>  ENABLE_PREFIX_DELEGATION=false \<br>  WARM_ENI_TARGET=0 \<br>  WARM_PREFIX_TARGET=0 \<br>  WARM_IP_TARGET=1 \<br>  MINIMUM_IP_TARGET=1</pre><p>kubectl set env on a DaemonSet automatically triggers a rolling update — no manual restarts needed.</p><p>But we immediately hit a second problem.</p><p>The moment IPAMD switched from prefix mode to individual secondary IPs, all 33 nodes simultaneously tried to warm up their IP pools. With WARM_ENI_TARGET=0 but no tight upper bound on individual IPs, every node started grabbing what it could — and within minutes, both subnets hit <strong>zero available IPs</strong>.</p><p>We’d traded one exhaustion mode for another.</p><p>The fix for the fix:</p><pre>kubectl set env daemonset aws-node -n kube-system \<br>  WARM_IP_TARGET=3 \<br>  MINIMUM_IP_TARGET=3</pre><p>Capping the warm pool to 3 IPs per node across 33 nodes meant only ~99 IPs reserved for warming instead of ~957. Within minutes, IPAMD released the excess IPs back to the subnet, the subnets recovered, and pods began starting normally.</p><p>Total outage: <strong>2.5 hours</strong>.</p><h3>The Three Things That Surprised Us</h3><h3>1. “Available IPs” means nothing when you need prefix blocks</h3><p>This is the most counterintuitive part of the whole incident. You look at your subnet in the AWS console, see 600 available IPs, and think you’re fine. You’re not — if those 600 IPs are scattered as non-contiguous fragments, prefix delegation simply cannot use them. The error you get (InsufficientCidrBlocks) sounds like a quota issue. It isn&#39;t. It&#39;s a geometry problem.</p><p><strong>The right diagnostic:</strong> Always test with --ipv4-prefix-count 1 via the EC2 API, not by looking at available IP counts.</p><h3>2. IPAMD doesn’t log to stdout</h3><p>This one cost time. When something looks wrong with CNI, the natural instinct is kubectl logs aws-node -n kube-system. But aws-node logs its init container to stdout — not IPAMD itself. IPAMD writes to a file inside the pod.</p><p>The fast path is the introspection endpoint. Port-forward to 61679 and check /v1/enis. If TotalIPs is zero, IPAMD has no IPs to work with, full stop.</p><h3>3. Warm pools feel free — until you have 33 nodes</h3><p>WARM_ENI_TARGET=1 is a sensible default on a small cluster. But on an m5.4xlarge, one warm ENI = 29 secondary IPs. Across 33 nodes, that&#39;s <strong>957 IPs permanently reserved</strong> just to keep warm pools stocked. On a /22 subnet with 1019 usable IPs, that&#39;s nearly the entire subnet, before a single pod runs.</p><p>Never set warm pool parameters without doing the math:</p><pre>warm_ip_target × node_count = total reserved IPs</pre><p>If that number approaches your subnet size, you’re living dangerously.</p><h3>What Good Looks Like</h3><p>After the incident, the safe configuration for this cluster size and subnet:</p><pre>ENABLE_PREFIX_DELEGATION = false       # re-enable only after larger subnets<br>WARM_ENI_TARGET          = 0<br>WARM_PREFIX_TARGET       = 0<br>WARM_IP_TARGET           = 3<br>MINIMUM_IP_TARGET        = 3</pre><p>And the long-term remediation plan:</p><ul><li><strong>Provision larger subnets</strong> — /20 or /19. A /22 (1019 IPs) simply isn&#39;t enough for 33+ nodes with prefix delegation and headroom for scaling.</li><li><strong>Alert on subnet IP availability</strong> — Set a CloudWatch or Grafana alert on AvailableIpAddressCount at &lt; 200 IPs. Don&#39;t wait to find out during an outage.</li><li><strong>Cap autoscaler max nodes</strong> — Sudden scale-outs that double node count are the fastest way to trigger this. A gradual scale ceiling gives you time to notice before it blows up.</li></ul><h3>TL;DR</h3><p>What happened Prefix delegation (/28 blocks) failed because 5 days of pod churn fragmented the subnets — hundreds of IPs available, zero contiguous /28 blocks <strong>How it manifested </strong>All new nodes had TotalIPs: 0 in IPAMD; every pod scheduled there failed with failed to assign an IP address<strong>How we diagnosed</strong>kubectl port-forward aws-node 61679:61679 → curl /v1/enis showed zero IPs; EC2 assign-private-ip-addresses --ipv4-prefix-count 1 returned InsufficientCidrBlocks<strong>How we fixed it </strong>Disabled prefix delegation, capped warm pool to 3 IPs/node <strong>Long-term fix </strong>Larger subnets + alerting on available IPs</p><p>Kubernetes networking failures are some of the hardest to debug because the error messages point at symptoms, not causes. A pod that can’t get an IP address looks the same whether your subnets are genuinely full, fragmented, or misconfigured at the CNI level. The only way through is knowing which layer to look at — and having the right tools to look with.</p><p>The introspection endpoint at :61679 is your friend. Use it.</p><p><em>If this helped you, share it with whoever manages your cluster networking. The person who enables prefix delegation and the person who provisions subnets are rarely the same person — and that gap is exactly where this incident lives.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4244bce53e83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 2 — Event Source: Mock GAP and the Classroom Simulator]]></title>
            <link>https://medium.com/@akash94thakur/day-2-event-source-mock-gap-and-the-classroom-simulator-f69ab4544b27?source=rss-36df1949e96a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f69ab4544b27</guid>
            <category><![CDATA[schemaregistry]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <dc:creator><![CDATA[Thinking monster]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 18:56:31 GMT</pubDate>
            <atom:updated>2026-04-14T18:56:31.097Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A 7-day journey building a production-grade analytics pipeline on your laptop. Day 2 of 7.</em></p><blockquote><strong><em>Companion code:</em></strong><em> everything in this post lives under </em><a href="https://github.com/thinkingmonster/data-pipeline/tree/main/days/day-2"><em>days/day-2/</em></a><em> in the lab repository. </em><a href="https://github.com/thinkingmonster/data-pipeline/tree/main/days/day-2"><em>Day 2</em></a><em> is a self-contained snapshot that builds on Day 1.</em></blockquote><h3>The Claim</h3><p>By the end of today, you will have — on the same laptop — a FastAPI-based <strong>ingress gateway</strong> that accepts JSON events over HTTP, validates them, serialises each one to Confluent-Avro wire format, and produces to the right Kafka topic with a stable partition key, idempotent writes, and acks=all. You will have a <strong>traffic generator</strong> driving ~10 events per second across three concurrent simulated virtual classrooms, realistically skewed across five geographic zones.</p><p>You will watch three Kafka topics filled with wire-format bytes. You will watch Schema Registry register three schemas, exactly once each, and then get out of the hot path forever. You will hand-decode a message from raw bytes back into JSON. You will break the pipeline in three specific ways and understand why each failure mode looks the way it does.</p><p>And you will end the day with a working mental model of <strong>producer semantics</strong>, <strong>schema lifecycle</strong>, and <strong>the Confluent wire format</strong> — the three things every Kafka developer eventually has to internalise.</p><p>This is Phase 2 of the <a href="https://medium.com/@akash94thakur/building-a-production-grade-analytics-pipeline-on-your-laptop-a-7-day-learning-journey-976e0032119f">Learning Roadmap.</a></p><h3>Recap — Where We Left Off</h3><p>Day 1 gave us the substrate:</p><ul><li>A minikube profile, data-pipeline, sized for the full stack</li><li>A namespace with an admission-controlled quota</li><li>MinIO with bucket analytics-lab ready for Delta writes</li><li>A 3-broker Strimzi Kafka cluster in KRaft mode</li><li>Three application topics (analytics, engagement-topic, webrtc-analytics) plus the internal _schemas compacted topic</li><li>Confluent Schema Registry backed by _schemas, reachable at schema-registry:8081</li></ul><p>Nothing was producing. The cluster was idle. Today, we change that.</p><h3>The Slice We’re Building Today</h3><p>Nothing consumes yet. That’s Phase 4 (Spark). Today is <strong>producer-side</strong>: establish the contract, put bytes on the log, verify those bytes are what we think they are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*16ffkeR9he1rfulE78IXqA.png" /><figcaption>gap ingestion service</figcaption></figure><h3>Why a Gateway at All?</h3><p>In a toy tutorial, the traffic generator would produce straight to Kafka itself. We don’t do that, and the reason is worth examining before we write any code.</p><p>Picture a real platform with dozens of clients — mobile apps, browsers, third-party integrations, internal services — all needing to write events. If each client produces directly to Kafka, every one of them needs:</p><ul><li>Kafka credentials (MSK IAM, SASL/SCRAM, mTLS…)</li><li>The current list of bootstrap servers</li><li>Schema Registry credentials</li><li>Knowledge of which topic accepts which event type</li><li>The discipline to serialise in the exact right wire format</li><li>The discipline to retry correctly, batch correctly, and respect rate limits</li></ul><p>Push all that to every client and you’ve built a distributed system where one bad mobile client can poison a topic with malformed bytes and a valid schema_id prefix. Spark picks it up in Phase 4, Delta commits it, and now you have corrupt rows in an ACID-governed Parquet file. The only fix is a time-travel revert.</p><p>The <strong>Global Analytics Platform gateway</strong> pattern solves this. One service owns all the Kafka-facing responsibility. Clients speak plain HTTP + JSON. The gateway enforces:</p><ul><li><strong>AuthZ</strong> — who is allowed to send what</li><li><strong>Schema validation</strong> — every payload must match a registered Avro schema, or 422</li><li><strong>Wire format</strong> — correct magic byte, correct schema_id, correct Avro encoding</li><li><strong>Topic routing</strong> — by event type, not by client</li><li><strong>Partition key discipline</strong> — per-meeting ordering is preserved because the gateway picks the key, not the client</li><li><strong>Idempotent retry semantics</strong> — one place to tune acks, linger.ms, compression</li><li><strong>Back-pressure</strong> — if Kafka is overloaded, the gateway fails closed with 429 instead of every client discovering it independently</li></ul><p>This is the single most important architectural pattern in real-time analytics ingestion, and the mock we’re building today captures all of it except AuthZ.</p><h3>Mock GAP — Anatomy of the Ingest Gateway</h3><p>Three files do 90% of the work. Let’s walk each.</p><h3>1. Routing — eventType to topic and schema</h3><p><a href="https://medium.com/days/day-2/apps/mock-gap/app/schemas.py">mock-gap/app/schemas.py</a> holds three Avro schemas and an EVENT_ROUTING dict:</p><pre>EVENT_ROUTING: dict[str, tuple[str, dict]] = {<br>    &quot;meeting_start&quot;:    (&quot;analytics&quot;,         ANALYTICS_SCHEMA),<br>    &quot;meeting_end&quot;:      (&quot;analytics&quot;,         ANALYTICS_SCHEMA),<br>    &quot;user_join&quot;:        (&quot;analytics&quot;,         ANALYTICS_SCHEMA),<br>    &quot;user_leave&quot;:       (&quot;analytics&quot;,         ANALYTICS_SCHEMA),<br>    &quot;mic_toggle&quot;:       (&quot;webrtc-analytics&quot;,  WEBRTC_SCHEMA),<br>    &quot;cam_toggle&quot;:       (&quot;webrtc-analytics&quot;,  WEBRTC_SCHEMA),<br>    &quot;network_quality&quot;:  (&quot;webrtc-analytics&quot;,  WEBRTC_SCHEMA),<br>    &quot;speech_time&quot;:      (&quot;engagement-topic&quot;,  ENGAGEMENT_SCHEMA),<br>    &quot;attention_score&quot;:  (&quot;engagement-topic&quot;,  ENGAGEMENT_SCHEMA),<br>}</pre><p>Everything downstream — the wire format, the topic choice, the Avro field layout — is a function of this dict. Add a new eventType, add a row here. Add a new topic, add a row <em>and</em> a new schema.</p><p>Notice the schema split(<a href="https://medium.com/days/day-2/apps/mock-gap/app/schemas.py">mock-gap/app/schemas.py</a>): analytics and webrtc-analytics both use camelCase zoneId. engagement-topic uses snake_case zone_id. This is <strong>intentional and production-faithful</strong>. Real schemas evolve organically across teams, and you inherit whatever casing the original author picked. Today this is a curiosity. In Phase 3 it becomes a learning point — Hive Metastore partition keys mirror field casing exactly, so zoneId=3/ and zone_id=3/ are literally different directory trees on object storage.</p><h3>2. Schema Registry interaction — register-or-fetch</h3><p>This is the part most developers get wrong the first time, so let’s go deep.</p><p>When GAP sees the very first event of a given type, it needs a schema_id to put in the wire format header. Where does it come from?</p><p>Three patterns exist in production:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofpxjFjyoQ9xQdWtAUwfSA.png" /><figcaption>Schema registry patterns</figcaption></figure><p>We picked the first pattern. Simpler, tighter feedback loop, great for a lab. The discipline: <strong>run schemas registered at runtime through compatibility checks in CI</strong> before the code ships. In our lab we skip CI, but the design would break cleanly into two stages for a real deploy.</p><p>The specific call <a href="https://medium.com/days/day-2/apps/mock-gap/app/producer.py#L60">SchemaCache.get()</a> makes it:</p><pre>POST http://schema-registry:8081/subjects/engagement-topic-value/versions<br>Content-Type: application/vnd.schemaregistry.v1+json</pre><pre>{&quot;schemaType&quot;: &quot;AVRO&quot;, &quot;schema&quot;: &quot;&lt;Avro schema JSON as a string&gt;&quot;}</pre><p>This endpoint is <strong>register-if-new / lookup-if-existing</strong> — one HTTP call covers both cases:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5rldNOn4CB48je8wT5vrA.png" /></figure><p>We cache the returned schema_id per subject. After that first call, GAP never contacts Schema Registry again for that subject for the life of the pod. At 10k events per second, this distinction is the difference between SR running fine and SR on fire.</p><p>You can see this live. With LOG_LEVEL=DEBUG, on the very first event GAP logs:</p><pre>DEBUG app.producer - sr cache_miss subject=engagement-topic-value -&gt; POST http://schema-registry:8081/subjects/engagement-topic-value/versions<br>INFO  httpx        - HTTP Request: POST http://schema-registry:8081/subjects/engagement-topic-value/versions &quot;HTTP/1.1 200 OK&quot;<br>INFO  app.producer - registered subject=engagement-topic-value schema_id=3 (sr responded 200)</pre><p>On every event after:</p><pre>DEBUG app.producer - sr cache_hit subject=engagement-topic-value schema_id=3</pre><p>The Prometheus counter tells the same story:</p><pre>gap_schema_registry_hits_total{result=&quot;cache_hit&quot;}   8234<br>gap_schema_registry_hits_total{result=&quot;registered&quot;}  3<br>gap_schema_registry_hits_total{result=&quot;lookup_fail&quot;} 0</pre><p>registered=3 — one per subject, ever. cache_hit grows with traffic. In a production SLO dashboard, you&#39;d alert on a non-zero derivative registered after the first minute of uptime. A producer re-registering schemas at steady state means <em>something changed unexpectedly</em>.</p><h3>3. The Confluent wire format — byte by byte</h3><p>This is the contract every consumer in the pipeline has to honor. It’s five bytes plus payload:</p><pre>byte 0      : 0x00                   magic byte (format version — only 0 exists)<br>bytes 1–4   : uint32 big-endian      Schema Registry ID<br>bytes 5+    : Avro binary            the payload, per the referenced schema</pre><p>The <a href="https://medium.com/days/day-2/apps/mock-gap/app/producer.py#L98">encode() function</a> is three lines:</p><pre>def encode(schema_id: int, parsed_schema: dict, record: dict) -&gt; bytes:<br>    buf = io.BytesIO()<br>    buf.write(b&quot;\x00&quot;)                         # magic byte<br>    buf.write(struct.pack(&quot;&gt;I&quot;, schema_id))    # 4-byte BE uint32<br>    schemaless_writer(buf, parsed_schema, record)  # Avro binary<br>    return buf.getvalue()</pre><p>Concrete example. An event:</p><pre>{&quot;meetingId&quot;: &quot;m-d94b0c9979&quot;, &quot;zone_id&quot;: 3, &quot;eventType&quot;: &quot;speech_time&quot;,<br> &quot;timestamp&quot;: 1776184087728, &quot;value&quot;: 2.547}</pre><p>Encoded against schema_id=3 becomes 45 bytes:</p><pre>offset  byte(s)           meaning<br> ------  ----------------  -----------------------------------------<br> 0       00                magic byte (wire format v0)<br> 1-4     00 00 00 03       schema_id = 3 (big-endian uint32)<br> 5       18                Avro zigzag-long: (24&gt;&gt;1)=12 → length of meetingId<br> 6-17    6d 2d 64 39 34    &quot;m-d94b0c9979&quot;<br>         62 30 63 39 39<br>         37 39<br> 18      06                zigzag long: zone_id = 3<br> 19      16                zigzag long: length of eventType = 11<br> 20-30   73 70 65 65 63    &quot;speech_time&quot;<br>         68 5f 74 69 6d 65<br> 31-38   ... 8 bytes       timestamp (long, zigzag)<br> 39-44   ... 6 bytes       value (double, IEEE 754)</pre><p>Why does this matter? Because Spark’s from_avro() in Phase 4 <strong>does not understand</strong> the first 5 bytes. Feed it the raw Kafka value, and it&#39;ll try to interpret 0x00 0x00 0x00 0x00 0x03 0x18 ... As Avro, which is garbage. Every team implementing Confluent-wire-format Avro in Spark learns this the painful way once. Phase 4 will strip the prefix with substring(value, 6, length(value) - 5) before handing the bytes to the reader.</p><h3>4. Producer configuration — the tuning knobs that matter</h3><p><a href="https://medium.com/days/day-2/apps/mock-gap/app/producer.py#L119">Producer </a><a href="https://medium.com/days/day-2/apps/mock-gap/app/producer.py#L119">start()</a>:</p><pre>self._producer = AIOKafkaProducer(<br>    bootstrap_servers=self._bootstrap,<br>    acks=&quot;all&quot;,<br>    enable_idempotence=True,<br>    linger_ms=10,<br>    max_batch_size=32_768,<br>    request_timeout_ms=30_000,<br>    compression_type=&quot;lz4&quot;,<br>)</pre><p>Each knob earns its place:</p><p><strong>acks=&quot;all&quot;</strong> — the broker must wait for min.insync.replicas (=2, from our cluster config) to acknowledge before returning success. Cost: ~1ms extra per record. Benefit: the record survives any single broker failure.</p><p><strong>enable_idempotence=True</strong> — the producer attaches a (producer_id, sequence_number) tuple to every record. If a network blip causes a retry, the broker sees the duplicate sequence and silently drops it. Guarantees <strong>no duplicates within one producer session</strong>. Doesn&#39;t help against client-level retries (those use different sequences), or pod restarts (which get a new producer_id).</p><p><strong>linger_ms=10</strong> — don&#39;t send each record as its own batch. Wait up to 10ms, collect records going to the same partition, batch them. Latency cost: ~10ms in the tail. Throughput gain: often 10–100×. This knob is invisible at 10 eps; absolutely critical at 10k eps.</p><p><strong>compression_type=&quot;lz4&quot;</strong> — compresses the record <em>batch</em> before the produce request. With Avro (already compact binary) the ratio is modest, maybe 2–3×. Not worth it at very low rates; worth it at high rates. We use it to exercise the dependency (aiokafka needs cramjam as a backend — see the failures section below).</p><h3>Classroom Simulator — Anatomy of the Traffic Generator</h3><p>The simulator is simpler because it has none of the responsibility. It generates events, POSTs them, observes the result, loops. Interesting design notes:</p><h3>Concurrency model</h3><p><a href="https://medium.com/days/day-2/apps/classroom-simulator/sim/simulator.py">simulator.py</a> spawns N async tasks, one per concurrent meeting:</p><pre>tasks = [<br>    asyncio.create_task(run_meeting(cfg, client, stats, stop))<br>    for _ in range(cfg.concurrent_meetings)<br>]</pre><p>Each run_meeting loops forever:</p><pre>create meeting (unique meetingId, picked zone, list of students)<br>emit meeting_start<br>while meeting not finished:<br>    sleep(random.expovariate(1 / mean_gap))   # Poisson inter-arrival<br>    emit random_mid_stream(meeting)<br>emit meeting_end<br>(loop — start a new meeting)</pre><p>The expovariate is the important detail. Real traffic is <strong>bursty</strong> — not a perfectly spaced 1-event-every-100ms. Poisson arrivals capture that bustiness. At 10 events per second you&#39;ll see runs of 3–4 events in 10ms followed by a 400ms gap. That&#39;s realistic.</p><h3>Zone distribution</h3><pre>ZONE_WEIGHTS = (0.5, 0.25, 0.15, 0.07, 0.03)</pre><p>Zone 1 gets half the traffic, zone 5 gets 3%. This mirrors how real multi-region platforms actually behave — traffic is never uniform. Later in the pipeline we’ll partition Delta tables by zoneId, and this skew will surface as wildly uneven partition sizes. That&#39;s fine. It&#39;s the data telling us the truth.</p><h3>The meeting_end event</h3><p>Most event types are fire-and-forget analytics. meeting_end is different: in Phase 5, the JobControlStream Spark query will watch for eventType=meeting_end on the analytics topic and, when it sees one, POST to Airflow&#39;s REST API to trigger a silver-table batch for that meeting.</p><p>So meeting_end is a <strong>coordination signal</strong>, not just a data point. Today it looks like any other event. In four days it becomes the glue between the streaming lane and the batch lane.</p><h3>Multi-arch Container Builds — Why and How</h3><p>Minikube on an Apple Silicon laptop runs arm64 nodes. A CI cluster typically runs amd64. You will eventually want the same image to work on both. Enter docker buildx.</p><p>The problem: docker build on your laptop produces a single-arch image matching your host CPU. Load that into an amd64 cluster and every pod crashes with exec format error.</p><p>The solution: docker buildx with the docker-container driver can build for arbitrary target platforms using QEMU emulation. One command, multi-arch artifact.</p><p>The twist: docker buildx build --load (which pushes into your local Docker daemon) <strong>does not support multi-arch</strong>. Docker&#39;s image format is single-arch. So we work around it:</p><ol><li>buildx builds for both platforms</li><li>Exports to an OCI-spec tarball (OCI supports manifest lists)</li><li>minikube image load &lt;tarball&gt; imports the OCI tarball into the node&#39;s containerd; containerd extracts the arch matching the node</li></ol><p>From <a href="https://medium.com/days/day-2/apps/Makefile">apps/Makefile</a>:</p><pre>build-gap: buildx-init<br>	docker buildx build \<br>		--platform linux/amd64,linux/arm64 \<br>		--tag mock-gap:day2 \<br>		--output type=oci,dest=.build/mock-gap.tar \<br>		mock-gap<br>	minikube --profile data-pipeline image load .build/mock-gap.tar</pre><p>The dance is slightly clunky. It’s also the simplest multi-arch-to-minikube path that actually works today. A future buildx --load with OCI support (already proposed in Docker upstream) will eventually collapse the three steps to one.</p><h3>Running It — Fresh Start to First Event</h3><p>We start every day by destroying yesterday’s state. Stale Schema Registry subjects, half-terminated pods, and leftover topic data can silently break today’s runs in ways that take hours to debug. A clean 15-minute rebuild is always cheaper than the second hour of “why is this 409-ing.”</p><p>All commands run from days/day-2/ unless noted.</p><h3>Step 0 — Destroy and rebuild the cluster</h3><pre>make minikube-destroy          # wipes the profile entirely<br>make minikube-up               # fresh, 60–90s</pre><h3>Step 1 — Day 1 infrastructure (Phase 0 + Phase 1)</h3><pre>make phase0         &amp;&amp; make verify-phase0<br>make minio          &amp;&amp; make verify-minio<br>make kafka          &amp;&amp; make verify-kafka             # 3–5 minutes, the long pole<br>make schema-registry &amp;&amp; make verify-schema-registry</pre><p>Expected pod state after this completes:</p><pre>kubectl --context=data-pipeline -n data-pipeline get pods</pre><pre>NAME                                             READY   STATUS      AGE<br>data-pipeline-broker-0                           1/1     Running     3m<br>data-pipeline-broker-1                           1/1     Running     3m<br>data-pipeline-broker-2                           1/1     Running     3m<br>data-pipeline-controller-3                       1/1     Running     3m<br>data-pipeline-controller-4                       1/1     Running     3m<br>data-pipeline-controller-5                       1/1     Running     3m<br>data-pipeline-entity-operator-xxxx               2/2     Running     2m<br>minio-0                                          1/1     Running     4m<br>minio-bucket-init-xxxx                           0/1     Completed   4m<br>schema-registry-xxxx                             1/1     Running     2m<br>strimzi-cluster-operator-xxxx                    1/1     Running     5m</pre><h3>Step 2 — Build and deploy the apps</h3><p>One-time on a new laptop:</p><pre>make -C apps buildx-init</pre><p>Every day:</p><pre>make apps-build     # multi-arch buildx + minikube image load<br>make apps-deploy    # apply Deployments, wait for rollout</pre><h3>Step 3 — Watch it flow</h3><pre># terminal 1<br>make -C apps logs-sim</pre><pre># terminal 2<br>make -C apps logs-gap</pre><p>Expected simulator output (every 10 seconds):</p><pre>INFO simulator - meeting started id=m-7292f72b10 zone=1 students=5<br>INFO simulator - stats sent=193 failed=0 rate_eps=9.6 elapsed=20.0s</pre><p>Expected GAP output (first event of each type shows schema registration, then silence until the next unique type):</p><pre>INFO app.producer - registered subject=analytics-value schema_id=2 (sr responded 200)<br>INFO app.producer - registered subject=engagement-topic-value schema_id=3 (sr responded 200)<br>INFO app.producer - registered subject=webrtc-analytics-value schema_id=4 (sr responded 200)<br>INFO:     10.244.0.25:40336 - &quot;POST /api/gap/ingest HTTP/1.1&quot; 200 OK<br>INFO:     10.244.0.25:40336 - &quot;POST /api/gap/ingest HTTP/1.1&quot; 200 OK</pre><p>Notice the source IP:port in the uvicorn access log. It&#39;s the same tuple for every request. Same source port = same TCP socket = HTTP connection reuse. httpx is doing the right thing, and so is uvicorn.</p><h3>Behind the Scenes — Commands That Show What’s Actually Happening</h3><p>“200 OK from the gateway” tells you the request <em>was accepted</em>. It does not tell you the bytes in Kafka are correct, or that the partition key is stable, or that Schema Registry did what you expected. For each of those, you run the command that proves the thing.</p><h3>See what Schema Registry knows</h3><pre># list subjects<br>kubectl --context=data-pipeline -n data-pipeline exec deploy/schema-registry -- \<br>  curl -sS http://localhost:8081/subjects</pre><pre># expected: [&quot;analytics-value&quot;,&quot;engagement-topic-value&quot;,&quot;webrtc-analytics-value&quot;]</pre><pre># pull the current analytics schema<br>kubectl --context=data-pipeline -n data-pipeline exec deploy/schema-registry -- \<br>  curl -sS http://localhost:8081/subjects/analytics-value/versions/latest | jq .</pre><pre># reverse lookup — &quot;what is schema id 2&quot;?<br>kubectl --context=data-pipeline -n data-pipeline exec deploy/schema-registry -- \<br>  curl -sS http://localhost:8081/schemas/ids/2 | jq .</pre><pre># the compatibility mode (top-level, applies to all subjects unless overridden)<br>kubectl --context=data-pipeline -n data-pipeline exec deploy/schema-registry -- \<br>  curl -sS http://localhost:8081/config<br># expected: {&quot;compatibilityLevel&quot;:&quot;BACKWARD&quot;}</pre><pre># is my proposed schema compatible with what&#39;s already registered?<br>kubectl --context=data-pipeline -n data-pipeline exec deploy/schema-registry -- \<br>  curl -sS -X POST http://localhost:8081/compatibility/subjects/analytics-value/versions/latest \<br>    -H &#39;Content-Type: application/vnd.schemaregistry.v1+json&#39; \<br>    -d &#39;{&quot;schema&quot;: &quot;&lt;escaped schema JSON&gt;&quot;}&#39;</pre><p>The last one is the dry-run call — exactly what a CI pipeline should run on schema-change PRs <em>before</em> the code deploys.</p><h3>See the underlying Kafka topic that backs the Schema Registry</h3><pre>kubectl --context=data-pipeline -n data-pipeline exec data-pipeline-broker-0 -c kafka -- \<br>  bin/kafka-console-consumer.sh \<br>    --bootstrap-server data-pipeline-kafka-bootstrap:9092 \<br>    --topic _schemas --from-beginning --timeout-ms 5000 \<br>    --property print.key=true --property key.separator=&#39; | &#39;</pre><p>You’ll see JSON records like:</p><pre>{&quot;keytype&quot;:&quot;SCHEMA&quot;,&quot;subject&quot;:&quot;analytics-value&quot;,&quot;version&quot;:1,&quot;magic&quot;:1} | {&quot;subject&quot;:&quot;analytics-value&quot;,&quot;version&quot;:1,&quot;id&quot;:2,&quot;schema&quot;:&quot;…&quot;}</pre><p><strong>This is the actual storage.</strong> Schema Registry is a stateful cache in front of this log. Restart Schema Registry, it rebuilds its in-memory state by re-reading _schemas. Lose _schemas and Schema Registry forgets everything.</p><p>That’s the reason _schemas is <strong>log-compacted</strong> and replicated with RF=3, min.insync.replicas=2. It&#39;s not analytics data — it&#39;s configuration data that consumers depend on being eventually consistent and durable.</p><h3>See topic offsets (how many messages exist, per partition)</h3><pre>for t in analytics engagement-topic webrtc-analytics; do<br>  echo &quot;-- $t --&quot;<br>  kubectl --context=data-pipeline -n data-pipeline exec data-pipeline-broker-0 -c kafka -- \<br>    bin/kafka-get-offsets.sh --bootstrap-server data-pipeline-kafka-bootstrap:9092 --topic &quot;$t&quot;<br>done</pre><pre># example output after a few minutes of traffic:<br># -- analytics --<br># analytics:0:0<br># analytics:1:382<br># analytics:2:451<br># -- engagement-topic --<br># engagement-topic:0:0<br># engagement-topic:1:405<br># engagement-topic:2:497</pre><p>topic:partition:end_offset. Partition 0 often has fewer messages because a tiny number of unique keys (3 concurrent meetings × a few per hour) hash unevenly into 3 partitions. With hundreds of meetings in prod, skew flattens.</p><h3>See raw bytes in a topic (the proof-of-wire-format)</h3><pre>kubectl --context=data-pipeline -n data-pipeline exec data-pipeline-broker-0 -c kafka -- \<br>  bin/kafka-console-consumer.sh \<br>    --bootstrap-server data-pipeline-kafka-bootstrap:9092 \<br>    --topic analytics \<br>    --partition 1 --offset 0 --max-messages 2 \<br>    --timeout-ms 5000 \<br>    --property print.key=true --property key.separator=&#39; | &#39;</pre><p>You’ll see something like:</p><pre>m-d94b0c9979 |     m-d94b0c9979user_join���̱gs-d7814f4frolestudent</pre><p>The key (m-d94b0c9979) is printable — that&#39;s our plain-UTF-8 meetingId. The value is partially printable (schema field values are strings) and partially binary (schema_id bytes, zigzag-encoded lengths). The non-printable bytes are where the wire format lives.</p><h3>Decode a message fully, end-to-end, from inside the cluster</h3><p>We can’t run the decoder on our laptop directly — Strimzi’s internal listener advertises in-cluster hostnames unreachable from outside the cluster. Instead we copy a Python decoder into the mock-gap pod (which already has aiokafka + fastavro + httpx) and run it there.</p><pre>POD=$(kubectl --context=data-pipeline -n data-pipeline get pod -l app=mock-gap \<br>       -o jsonpath=&#39;{.items[0].metadata.name}&#39;)</pre><pre>kubectl --context=data-pipeline -n data-pipeline cp \<br>  apps/scripts/decode_samples.py $POD:/tmp/decode_samples.py</pre><pre>kubectl --context=data-pipeline -n data-pipeline exec $POD -- \<br>  python /tmp/decode_samples.py</pre><p>Expected output:</p><pre>=== analytics ===<br>  [p=1 off=0 key=&#39;m-9e1adea5de&#39; sid=4 61B]<br>    {&quot;eventType&quot;:&quot;user_join&quot;,&quot;meetingId&quot;:&quot;m-9e1adea5de&quot;,&quot;payload&quot;:{&quot;role&quot;:&quot;student&quot;},&quot;timestamp&quot;:1776183753951,&quot;userId&quot;:&quot;s-d7814f4f&quot;,&quot;zoneId&quot;:3}<br>  [p=1 off=1 key=&#39;m-9e1adea5de&#39; sid=4 62B]<br>    {&quot;eventType&quot;:&quot;user_leave&quot;,&quot;meetingId&quot;:&quot;m-9e1adea5de&quot;,&quot;payload&quot;:{&quot;role&quot;:&quot;student&quot;},&quot;timestamp&quot;:1776183755198,&quot;userId&quot;:&quot;s-ffa25621&quot;,&quot;zoneId&quot;:3}</pre><p>This is the moment you’ve <em>actually verified</em> the pipeline. The simulator sent JSON. The gateway encoded it. Kafka stored the bytes. The decoder pulled them back, parsed the 5-byte header, fetched the schema from Schema Registry by ID, and round-tripped the Avro bytes back to a dict that looks <em>exactly like</em> what the simulator sent. Any drift at any layer would show up here.</p><h3>See which arch ended up in the cluster</h3><pre>minikube --profile data-pipeline ssh -- \<br>  sudo ctr -n k8s.io images ls | grep mock-gap</pre><p>On an arm64 laptop:</p><pre>docker.io/library/mock-gap:day2   application/vnd.oci.image.index.v1+json   sha256:…   85 MiB   linux/arm64</pre><p>The linux/arm64 at the end is what kubelet actually runs. The multi-arch manifest list is stored alongside, so a theoretical amd64 node joining this cluster would pick up the amd64 variant without a rebuild.</p><h3>See Prometheus metrics</h3><pre>POD=$(kubectl --context=data-pipeline -n data-pipeline get pod -l app=mock-gap \<br>       -o jsonpath=&#39;{.items[0].metadata.name}&#39;)</pre><pre>kubectl --context=data-pipeline -n data-pipeline exec $POD -- \<br>  python -c &#39;import urllib.request; print(urllib.request.urlopen(&quot;http://localhost:8000/metrics&quot;).read().decode())&#39; \<br>  | grep ^gap_ | head -20</pre><p>Four counter/histogram families to watch:</p><ul><li>gap_records_sent_total{topic, event_type} — throughput per event shape</li><li>gap_records_failed_total{topic, reason} — should stay at 0; reason diagnoses</li><li>gap_produce_latency_seconds_bucket{topic, le} — latency histogram</li><li>gap_schema_registry_hits_total{result} — cache_hit vs registered vs lookup_fail</li></ul><p>At 10 eps steady state, you should see cache_hits climbing while registered stays at exactly 3 and lookup_fail at 0.</p><h3>See every stage of an event’s journey (DEBUG mode)</h3><pre>kubectl --context=data-pipeline -n data-pipeline set env deploy/mock-gap LOG_LEVEL=DEBUG<br>kubectl --context=data-pipeline -n data-pipeline logs deploy/mock-gap --tail=20 -f</pre><p>You’ll see, per event:</p><pre>DEBUG app.producer - route eventType=speech_time -&gt; topic=engagement-topic subject=engagement-topic-value<br>DEBUG app.producer - sr cache_hit subject=engagement-topic-value schema_id=3<br>DEBUG app.producer - encoded wire=[magic|sid=3|avro] 45B first16=00 00 00 00 03 18 6d 2d 64 39 34 62 30 63 39 39<br>DEBUG aiokafka     - Sending (key=b&#39;m-d94b0c9979&#39; value=b&#39;\x00\x00\x00\x00\x03\x18m-d94b0c9979...&#39;) to TopicPartition(topic=&#39;engagement-topic&#39;, partition=1)<br>DEBUG aiokafka.conn - Request 20: ProduceRequest_v7(required_acks=-1, ...)<br>DEBUG aiokafka.conn - Response 20: ProduceResponse_v7(...partition=1, error_code=0, offset=453...)<br>DEBUG app.producer - kafka sent topic=engagement-topic partition=1 offset=453 key=m-d94b0c9979 schema_id=3<br>INFO:     10.244.0.25:40336 - &quot;POST /api/gap/ingest HTTP/1.1&quot; 200 OK</pre><p>Eight lines for one event. Each line is a different layer: our code’s routing decision, the schema cache lookup, the wire encoding, aiokafka’s partition choice, the network request, the network response, our code’s summary, uvicorn’s access log. This is what “full-stack observability” looks like on a single-record path.</p><p>Turn it back off when you’re done — at 10 eps, DEBUG is manageable. At 10k eps it would flood your log pipeline.</p><pre>kubectl --context=data-pipeline -n data-pipeline set env deploy/mock-gap LOG_LEVEL=INFO</pre><h3>The Failures We Hit (And What They Teach)</h3><p>Every one of these happened during the actual build of this lab. None were hypothetical. Knowing the shape of each error is 80% of the diagnosis.</p><h3>Failure 1 — RuntimeError: Compression library for lz4 not found</h3><p><strong>Symptom:</strong> mock-gap pod CrashLoopBackOff. Logs show:</p><pre>File &quot;.../aiokafka/producer/producer.py&quot;, line 248, in __init__<br>    raise RuntimeError(...)<br>RuntimeError: Compression library for lz4 not found</pre><p><strong>Root cause:</strong> the lz4 PyPI package is not what aiokafka actually looks for. aiokafka checks via has_lz4(), which requires cramjam (pulled in by aiokafka[lz4] extra).</p><p><strong>Fix:</strong> in <a href="https://medium.com/days/day-2/apps/mock-gap/requirements.txt">requirements.txt</a>:</p><pre>-aiokafka==0.12.0<br>-lz4==4.3.3<br>+aiokafka[lz4]==0.12.0</pre><p><strong>What it teaches:</strong> always use the library’s own “extras” syntax for optional codecs, TLS backends, and SASL mechanisms. pip install &#39;aiokafka[lz4,snappy,zstd,gssapi]&#39; is the correct shape. Don&#39;t guess the underlying package name.</p><h3>Failure 2 — 409: Schema being registered is incompatible with an earlier schema</h3><p><strong>Symptom:</strong> every POST /api/gap/ingest for one event type returns 502. GAP logs show:</p><pre>schema registry returned 409 for analytics-value: ...<br>&#39;eventType&#39; at path &#39;/fields/2&#39; in the new schema has no default value<br>and is missing in the old schema ... {oldSchemaVersion: 1}<br>{validateFields: &#39;false&#39;, compatibility: &#39;BACKWARD&#39;}</pre><p><strong>Root cause:</strong> something registered a simpler schema under analytics-value earlier (in our case, Day 1&#39;s verify script, with only {meetingId, zoneId, ts}). Schema Registry is in BACKWARD compat — the new schema must be readable by old consumers. Adding required fields without defaults breaks that.</p><p><strong>Fix for the lab (destroys history, lab-only):</strong></p><pre># two-step delete — SR requires soft-then-hard to prevent accidents<br>kubectl --context=data-pipeline -n data-pipeline exec deploy/schema-registry -- \<br>  curl -sS -X DELETE &quot;http://localhost:8081/subjects/analytics-value&quot;</pre><pre>kubectl --context=data-pipeline -n data-pipeline exec deploy/schema-registry -- \<br>  curl -sS -X DELETE &quot;http://localhost:8081/subjects/analytics-value?permanent=true&quot;</pre><pre>kubectl --context=data-pipeline -n data-pipeline rollout restart deployment/mock-gap</pre><p>If you try the hard delete first, SR returns error_code 40405: &quot;Subject &#39;analytics-value&#39; was not deleted first before being permanently deleted&quot;. That two-step is SR&#39;s &quot;are you really sure&quot; — soft delete stages it, hard delete commits.</p><p><strong>Fix for production (never hard-delete):</strong> either (a) evolve the schema to be BACKWARD-compatible — add defaults to every new field — or (b) register under a different subject name and migrate consumers over. Never hard-delete a subject consumers have schema IDs cached from.</p><p><strong>What it teaches:</strong> compatibility modes are <strong>deploy-ordering contracts</strong>:</p><p>ModeNew schema must be readable byDeploy orderBACKWARDold consumersupgrade consumers first (or at least before producers bump)FORWARDnew consumers reading old dataupgrade producers firstFULLbotheither orderNONEnobodyonly use for throwaway topics</p><p>Choose the mode to match how you deploy. Lab default is BACKWARD — consumers (Spark, Phase 4) will see the evolved schema first.</p><h3>Failure 3 — BAD MAGIC: 0x64 in the first decoded message</h3><p><strong>Symptom:</strong> the decoder script reports the very first message in analytics partition 0 has magic byte 0x64 (&#39;d&#39; ASCII), not 0x00.</p><p><strong>Root cause:</strong> Day 1’s verify-kafka.sh used kafka-console-producer to smoke-test the cluster. That tool sends plain UTF-8 text, not Avro. The first message in the topic is literally the string day-1-smoke-test.</p><p><strong>Fix:</strong> the decoder should skip non-wire-format messages:</p><pre>if raw[0] != 0x00:<br>    non_wire += 1<br>    continue</pre><p><strong>What it teaches:</strong> in production you <em>will</em> get garbage in topics. Consumers must defend themselves. The producer-side “I promise to use wire format” is never a guarantee you can rely on — topic retention is days to weeks, a rogue writer from last Tuesday will bite you Friday. Always validate the magic byte.</p><h3>Failure 4 — KafkaConnectionError: No connection to node with id 2 (running GAP locally)</h3><p><strong>Symptom:</strong> running mock-gap on the laptop against port-forwarded Kafka fails every produce.</p><p><strong>Root cause:</strong> Strimzi’s default plain listener is type: internal — it advertises broker addresses like data-pipeline-broker-2.data-pipeline-kafka-brokers.data-pipeline.svc, which resolve only from inside the cluster. Bootstrap connects fine through localhost:9092, but then the broker metadata hands your client in-cluster DNS names.</p><p><strong>Fix for the lab:</strong> don’t run GAP locally. Deploy it. The apps image + kubectl exec workflow is sufficient for everything useful.</p><p><strong>Fix for real external access:</strong> add a NodePort or LoadBalancer listener to the Kafka spec:</p><pre>listeners:<br>  - name: plain<br>    port: 9092<br>    type: internal<br>    tls: false<br>  - name: external<br>    port: 9094<br>    type: nodeport<br>    tls: false</pre><p><strong>What it teaches:</strong> Kafka listeners are a <strong>two-step resolution</strong>: the client connects to bootstrap, bootstrap replies with a topology, the client then connects directly to the advertised addresses. Step 3 is what fails across network boundaries. MSK, Confluent Cloud, Strimzi — all have this pattern. “Can I reach the broker IP?” isn’t the diagnostic question; “can I resolve and connect to the <em>advertised</em> broker name?” is.</p><h3>Points to Ponder</h3><p>These don’t have quick answers. Sit with each for a bit — they’re more valuable than any feature you could add today.</p><ol><li><strong>The GAP pod dies with 50 records in aiokafka’s batch buffer that haven’t been flushed yet.</strong> What happens to them? Walk the shutdown path. (Hint: look at aiokafka’s producer.stop() and whether uvicorn&#39;s graceful shutdown gives us enough time to flush.)</li><li><strong>You run two mock-gap replicas behind the same Service.</strong> The simulator POSTs the <em>same event body</em> twice — same meetingId, same timestamp, same everything. Do the idempotent producers on the two replicas deduplicate? (Hint: what&#39;s a producer_id?)</li><li><strong>linger.ms=10, </strong><strong>batch.size=32KB, records are 200 bytes.</strong> At 10 events per second, is batching helping at all? At 10,000 events per second? Work the math.</li><li><strong>You’re adding a new </strong><strong>sessionId field to the analytics schema.</strong> Old consumers (Spark) have schema_id=4 cached; they now see a record with schema_id=5. Walk through what they do. (Hint: Confluent deserializers fetch the reader&#39;s schema by ID, project into the reader&#39;s cached schema. Does sessionId have a default? If not, what happens?)</li><li><strong>Why does Schema Registry back its state onto a Kafka topic rather than a SQL database?</strong> (Hint: availability profile, restart semantics, multi-region replication.)</li><li><strong>The engagement-topic schema has </strong><strong>zone_id (snake_case); analytics has </strong><strong>zoneId (camelCase).</strong> Is this a bug, a learning point, or both? What problem does it create downstream in Hive Metastore partitioning? What would it take to fix after the fact?</li><li><strong>Strimzi runs 3 controllers AND 3 brokers as separate pods in KRaft mode.</strong> What does the controller <em>actually</em> do? Why can’t one broker be its own controller in a single-broker cluster? (Hint: Raft quorum math — 3 is the minimum.)</li></ol><h3>Key Takeaways</h3><p>If you remember only these eight:</p><ol><li><strong>An ingest gateway is not optional architectural fluff.</strong> It’s the only place to centralize schema validation, topic routing, and partition-key discipline. Without it, every client owns those responsibilities — and gets them wrong.</li><li><strong>Ordering is a partition-key property, not a topic property.</strong> Pick the key when you create the topic; changing it later means a migration.</li><li><strong>Idempotent producer is a session-local guarantee.</strong> Exactly-once end-to-end requires the consumer to also participate (checkpoints in Spark, transactions in Kafka, or idempotent sinks).</li><li><strong>Schema Registry’s </strong><strong>POST /subjects/&lt;name&gt;/versions is a register-or-fetch endpoint.</strong> It creates if new, returns existing ID if identical, rejects if incompatible. One HTTP call handles all three cases.</li><li><strong>Cache schema IDs aggressively.</strong> Steady state should be zero SR calls per record. A production Kafka client making per-record SR calls at 10k eps will bring SR down.</li><li><strong>The Confluent wire format is </strong><strong>[0x00][4B schema_id BE][Avro].</strong> Five bytes. Non-negotiable. Every consumer must strip them, or interpret them, or both.</li><li><strong>Compatibility mode determines deploy order.</strong> BACKWARD = upgrade consumers first. Get this wrong and you’ll find out within minutes. Check compatibility <em>before</em> deploy in CI via POST /compatibility/….</li><li><strong>Listeners are two-step.</strong> Bootstrap → topology → per-broker connect. Failures live at the second hop and look like failures at the first.</li></ol><h3>Checkpoints — Can You Answer These?</h3><p>If yes, Day 3 will land cleanly.</p><ol><li>What are the two phases of an HTTP POST /api/gap/ingest request? At what point is the record durably stored?</li><li>How does the gateway know which topic to produce to for a given event?</li><li>What is the difference between a <strong>schema</strong>, a <strong>subject</strong>, a <strong>version</strong>, and a <strong>schema ID</strong> in Schema Registry?</li><li>What does it mean that SR is backed by the _schemas topic? What happens if you delete that topic?</li><li>How many Schema Registry HTTP calls does the gateway make per record at steady state? What would change that number?</li><li>Given a 45-byte Avro wire-format message on Kafka, how many of those bytes are the schema_id?</li><li>If two pod replicas of the gateway both produce the same record, do they deduplicate?</li><li>What Makefile target rebuilds the app images multi-arch and loads them into minikube? What’s the faster single-arch alternative?</li></ol><h3>What’s Next — Day 3</h3><p>Events are flowing. Nothing is reading them. Tomorrow we&#39;ll fix half of that.</p><p><strong>Day 3 — Catalog: PostgreSQL and Hive Metastore.</strong> We’ll deploy a PostgreSQL StatefulSet and a Hive Metastore backed by it. You’ll learn why data pipelines separate metadata from storage, what Thrift is, why HMS is not reactive to S3 writes, and why it MSCK REPAIR TABLE exists.</p><p>The events you’re producing today become rows in dl_analytics_bronze in Phase 4. Day 3 is what makes &quot;where does that table live?&quot; a question with an answer.</p><p>See you then.</p><p><em>This is part of a 7-day series building a full analytics pipeline from scratch on Minikube. </em><a href="https://medium.com/day-0-kickoff.md"><em>Day 0 — Kickoff</em></a><em>. </em><a href="https://medium.com/@akash94thakur/building-a-production-grade-analytics-pipeline-on-your-laptop-a-7-day-learning-journey-976e0032119f"><em>Day 1 — Foundation.</em></a><em> </em><a href="https://github.com/thinkingmonster/data-pipeline/tree/main/days/day-2"><em>All posts and source code.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f69ab4544b27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 1 — Foundation: Kafka, Schema Registry, and Object Storage]]></title>
            <link>https://medium.com/@akash94thakur/day-1-foundation-kafka-schema-registry-and-object-storage-fc15508a5faa?source=rss-36df1949e96a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc15508a5faa</guid>
            <category><![CDATA[confluent-schema-registry]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[minio]]></category>
            <dc:creator><![CDATA[Thinking monster]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 19:09:38 GMT</pubDate>
            <atom:updated>2026-04-13T19:13:34.010Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A 7-day journey building a production-grade analytics pipeline on your laptop. Day 1 of 7.</em></p><blockquote><a href="https://github.com/thinkingmonster/data-pipeline"><strong><em>Companion code</em></strong></a><strong><em>:</em></strong><em> everything in this post lives under </em><a href="https://github.com/thinkingmonster/data-pipeline"><em>days/day-1/</em></a><em> in the lab repository. Each day is a self-contained snapshot — Day 2 will copy this folder and add to it.</em></blockquote><h3>The Claim</h3><p>By the end of today, you will have — on a single laptop — a Kubernetes namespace running a 3-broker Kafka cluster in KRaft mode, a Confluent Schema Registry, and a MinIO object store with pre-created buckets for bronze, silver, and checkpoint data. You will have produced a message to Kafka and consumed it back. You will have registered an Avro schema, fetched it by ID, tried to break it, and watched Schema Registry refuse the breaking change.</p><p>More importantly: you will understand <em>why</em> every one of those pieces exists, what it would fail at without the others, and what class of bug each one prevents.</p><p>This is Phase 0 and Phase 1 of the <a href="https://medium.com/LEARNING-ROADMAP.md">Learning Roadmap</a> — the substrate every other day builds on.</p><h3>The Slice We’re Building</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*du74uF67lFT_4fefFVe1Hw.png" /><figcaption>Day one tools and data flow</figcaption></figure><p>Nothing streams data between these yet. Day 1 is about the <em>substrate</em>: the three systems everything else reads from or writes to. Day 2 introduces the first producer. Day 4 introduces Spark as the first consumer. Today is foundation.</p><h3>Phase 0 — The K8s Substrate</h3><h3>Why a dedicated minikube profile?</h3><p>Minikube supports multiple named profiles, each a separate Kubernetes cluster. If you already use minikube for other work, a bare minikube start shares resources with whatever else was running. That&#39;s fine for a toy cluster. Not fine for a cluster that will shortly be running 3 Kafka brokers, 3 KRaft controllers, a Spark driver, a StarRocks FE, and Airflow workers.</p><p>The profile we use is defined in <a href="https://medium.com/days/day-1/minikube/profile.sh">days/day-1/minikube/profile.sh</a>:</p><pre>minikube start \<br>  --profile data-pipeline \<br>  --driver docker \<br>  --kubernetes-version v1.33.0 \<br>  --cpus 10 \<br>  --memory 24576 \<br>  --disk-size 80g \<br>  --container-runtime=containerd \<br>  --addons=metrics-server,dashboard,ingress</pre><p>Three decisions worth unpacking:</p><p><strong>--container-runtime=containerd</strong>. Docker-the-runtime was deprecated from Kubernetes itself as of 1.24. Every production cluster you&#39;ll touch uses containerd (or CRI-O). Using containerd here means the container-lifecycle plumbing you learn is transferable.</p><p><strong>--kubernetes-version v1.33.0</strong>. Recent enough to match what a modern cloud cluster runs. This choice will bite us later in the post — older Strimzi releases don&#39;t handle the new version field — but that&#39;s exactly the kind of friction worth encountering in a lab.</p><p><strong>--cpus 10 --memory 24576</strong>. Generous. Go smaller and you&#39;ll hit scheduler evictions halfway through Day 4 when Spark starts pulling in 4 executor pods.</p><h3>Namespace, ResourceQuota, LimitRange — the trio</h3><p>Three objects, one manifest (<a href="https://medium.com/days/day-1/k8s/00-namespace/namespace.yaml">k8s/00-namespace/namespace.yaml</a>):</p><pre>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: data-pipeline<br>---<br>apiVersion: v1<br>kind: ResourceQuota<br>metadata: { name: data-pipeline-quota, namespace: data-pipeline }<br>spec:<br>  hard:<br>    requests.cpu: &quot;20&quot;<br>    requests.memory: 48Gi<br>    limits.cpu: &quot;32&quot;<br>    limits.memory: 96Gi<br>    persistentvolumeclaims: &quot;40&quot;<br>---<br>apiVersion: v1<br>kind: LimitRange<br>metadata: { name: data-pipeline-defaults, namespace: data-pipeline }<br>spec:<br>  limits:<br>    - type: Container<br>      default:        { cpu: 500m,  memory: 512Mi }<br>      defaultRequest: { cpu: 100m,  memory: 128Mi }<br>      max:            { cpu: &quot;8&quot;,   memory: 16Gi  }</pre><p>These three objects cooperate in a way that matters to internalize once, forever.</p><p><strong>Namespace</strong> is a <em>soft boundary</em>. It’s an organizational label. It gives you a place to scope RBAC, naming, and network policies. Two different namespaces can use the same resource names. That’s it — a namespace itself enforces nothing about resource consumption.</p><p><strong>ResourceQuota</strong> is a <em>hard boundary</em>. It’s a Kubernetes admission plugin that rejects any new pod that would push the namespace above its hard values. Not &quot;let the pod start and OOM later.&quot; Rejected at the API server, before the scheduler ever sees it. Try it yourself:</p><pre>kubectl -n data-pipeline run too-big \<br>  --image=busybox --restart=Never \<br>  --overrides=&#39;{&quot;spec&quot;:{&quot;containers&quot;:[{&quot;name&quot;:&quot;too-big&quot;,&quot;image&quot;:&quot;busybox&quot;,&quot;resources&quot;:{&quot;requests&quot;:{&quot;cpu&quot;:&quot;30&quot;,&quot;memory&quot;:&quot;80Gi&quot;},&quot;limits&quot;:{&quot;cpu&quot;:&quot;30&quot;,&quot;memory&quot;:&quot;80Gi&quot;}}}]}}&#39; \<br>  -- sleep 60</pre><pre># Error from server (Forbidden): pods &quot;too-big&quot; is forbidden:<br># exceeded quota: data-pipeline-quota,<br># requested: requests.cpu=30, used: requests.cpu=..., limited: requests.cpu=20</pre><p>That rejection is the whole point of a ResourceQuota. In prod, it’s what stops one runaway deploy from starving every other team sharing a cluster.</p><p><strong>LimitRange</strong> is the partner you discover by accident. The moment a ResourceQuota declares requests.cpu/limits.cpu, admission <strong>requires</strong> every container in the namespace to declare those fields. Miss them, and you get:</p><pre>Error creating: pods &quot;minio-bucket-init-xxx&quot; is forbidden:<br>failed quota: data-pipeline-quota: must specify limits.cpu for: mc;<br>limits.memory for: mc; requests.cpu for: mc; requests.memory for: mc</pre><p>This is exactly what happened to me the first time I ran make minio. The MinIO bucket-init Job didn&#39;t declare resources, the quota required them, admission rejected the pod, the Job controller retried forever. The LimitRange fixes it by supplying <strong>defaults</strong> for containers that forgot: defaultRequest becomes the pod&#39;s requests, default becomes the limits. Explicit manifests still win; the LimitRange is a backstop.</p><p>You will see this pattern in every production K8s namespace. ResourceQuota for the cap, LimitRange for the per-pod defaults + per-container ceiling. They&#39;re designed to work together.</p><h3>Deploy and verify</h3><pre>cd days/day-1<br>make minikube-up        # ~2 min, first time<br>make phase0             # apply namespace + quota + limitrange<br>make verify-phase0      # including the over-quota admission test</pre><p>The verify step (<a href="https://medium.com/days/day-1/scripts/verify-phase0.sh">scripts/verify-phase0.sh</a>) checks:</p><ol><li>The namespace exists.</li><li>The ResourceQuota is reporting Used vs Hard.</li><li>An intentional over-quota pod gets rejected.</li></ol><p>That last step is non-negotiable if you want to actually believe the quota works. Reading describe resourcequota is not the same as proving admission denies a bad pod.</p><h3>Mental model to lock in</h3><blockquote><em>A </em><strong><em>namespace</em></strong><em> is a soft boundary — organizational. A </em><strong><em>ResourceQuota</em></strong><em> is a hard boundary — scheduling admission. A </em><strong><em>LimitRange</em></strong><em> is the defaulter that keeps the ResourceQuota from rejecting every pod that forgot its resources block.</em></blockquote><h3>Phase 1a — MinIO, the Object Store</h3><h3>S3 is not a filesystem</h3><p>Every platform person has to internalize this at some point. S3 (and MinIO, its open-source API-compatible cousin) looks like a filesystem. It’s not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mzrUDLEG9fk1suNOBXwT4g.png" /><figcaption>file storage vs block store</figcaption></figure><p><strong>This one matters for Day 4</strong>: Delta Lake works on object storage because it uses the <em>one</em> atomic primitive S3 does offer — “put-if-absent” for new keys. Delta commits are just _delta_log/00000000000000000123.json files. Two writers racing both try to put 123.json; only one wins (the other gets 412 Precondition Failed). The loser retries as 124.json. That&#39;s the full mechanism behind Delta&#39;s optimistic concurrency.</p><p>MinIO supports this primitive, which is why the rest of the pipeline works locally. Not every S3-compatible store does — some of Delta’s more exotic failure modes come from stores that advertise “S3 compatibility” without implementing put-if-absent correctly.</p><h3>The manifests</h3><p>Four files under <a href="https://medium.com/days/day-1/k8s/01-minio/">k8s/01-minio/</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vEOrMn_LKB-W_iMauZWz4Q.png" /><figcaption>minio installation on k8</figcaption></figure><p><strong>Why StatefulSet and not Deployment?</strong> A Deployment assumes pods are stateless and interchangeable. A Deployment pod that reschedules to a different node gets a fresh (empty) volume. That’s catastrophic for a storage system. A StatefulSet gives each pod a stable identity (minio-0, minio-1, …) and keeps its PVC attached across rescheduling. Even with one replica, StatefulSet is the right primitive — it&#39;s a statement of intent.</p><p><strong>The bucket-init Job.</strong> Buckets in S3/MinIO aren’t created by the server automatically; the first thing any client does is “ensure bucket exists.” Rather than repeat that in every app, we do it once in a one-shot Kubernetes Job on deploy. The Job uses the minio/mc client to create analytics-lab/ with bronze/, silver/, and checkpoints/ subkeys. When Spark writes its first Delta file to s3a://analytics-lab/bronze/..., the prefix is already there.</p><h3>Deploy and verify</h3><pre>make minio              # apply secret, services, StatefulSet, bucket-init job<br>make verify-minio       # pod ready, bucket layout exists, round-trip write+read</pre><p>The verify script (<a href="https://medium.com/days/day-1/scripts/verify-minio.sh">scripts/verify-minio.sh</a>) runs a throwaway mc pod inside the cluster, sets an alias to http://minio:9000, lists analytics-lab/, copies a file, reads it back, deletes it. That proves the end-to-end data path works — not just that the pod is Running.</p><h3>Browse the console</h3><p>Useful for debugging, and kind of satisfying to see the buckets visually:</p><pre>make minio-console<br># Then open http://localhost:9001 in a browser<br># User: minioadmin  / Pass: minioadmin</pre><h3>Phase 1b — Kafka, via Strimzi, in KRaft Mode</h3><p>Three ideas stacked: <strong>Kafka</strong> is the replicated log. <strong>Strimzi</strong> is the Kubernetes operator that manages Kafka via Custom Resources. <strong>KRaft</strong> is Kafka’s native consensus mode that replaced Zookeeper.</p><h3>Kafka is not a queue</h3><p>This is the first thing people get wrong. A queue delivers each message to one consumer and then forgets it. Kafka is a <strong>log</strong>: messages are written to a topic, partitioned, replicated across brokers, and <strong>retained</strong> regardless of whether any consumer has read them yet. Consumers track their own read position (offset) and can rewind, fork, or replay.</p><p>Concretely: if you write 1M messages to analytics and never start a consumer, those messages sit on disk for the retention period (7 days by default in this lab). Start a consumer; it reads from wherever you configure it — beginning, end, a specific offset, a specific timestamp. Start a second consumer in a different consumer group; both read the full 1M, independently. This decoupling of writers and readers is the <em>entire</em> value proposition of a log-based system.</p><h3>Operators and CRDs — the declarative shift</h3><p>If you’ve only used Helm charts or raw Deployments, the operator pattern is a mental upgrade.</p><ul><li><strong>CRD (CustomResourceDefinition)</strong>: a schema you install once per cluster that teaches the API server a new resource type. Strimzi’s install ships 14 of them — Kafka, KafkaNodePool, KafkaTopic, KafkaUser, KafkaConnect, etc.</li><li><strong>CR (Custom Resource)</strong>: an <em>instance</em> of one of those kinds. You write kind: Kafka YAML and kubectl apply it. The cluster stores it in etcd.</li><li><strong>Operator</strong>: a controller pod that watches CRs of its kind and reconciles reality to match. Write a Kafka CR; the Strimzi operator creates StatefulSets, Services, PVCs. Delete it; the operator tears them all down.</li></ul><p>This is the same shape as every built-in Kubernetes controller (Deployment → Pods, Job → Pods), extended to arbitrary infrastructure. You&#39;ll see this pattern for every remaining phase: SparkApplication CRs for Spark, StarRocksCluster CRs for StarRocks, etc.</p><h3>Install Strimzi</h3><p>One script, installed into the data-pipeline namespace with a watch scope of that namespace (<a href="https://medium.com/days/day-1/k8s/02-kafka/install-strimzi.sh">k8s/02-kafka/install-strimzi.sh</a>):</p><pre>STRIMZI_VERSION=&quot;0.51.0&quot;<br>curl -fsSL &quot;https://github.com/strimzi/strimzi-kafka-operator/releases/download/${STRIMZI_VERSION}/strimzi-cluster-operator-${STRIMZI_VERSION}.yaml&quot; \<br>  | sed &quot;s|namespace: myproject|namespace: data-pipeline|g&quot; \<br>  | kubectl -n data-pipeline apply -f -</pre><p>The upstream manifest hardcodes myproject as the watch namespace. One sed rewrites it. This is the crude version of what Helm or Kustomize would do more elegantly, but it&#39;s one line and doesn&#39;t require new tooling.</p><h3>The Strimzi version lesson (the war story)</h3><p>My first attempt used Strimzi 0.43.0. The operator pod immediately went into CrashLoopBackOff. Digging through the logs:</p><pre>io.fabric8.kubernetes.client.KubernetesClientException: An error has occurred.<br>Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:<br>  Unrecognized field &quot;emulationMajor&quot; (class io.fabric8.kubernetes.client.VersionInfo),<br>  not marked as ignorable</pre><p>Kubernetes 1.33 added emulationMajor/emulationMinor fields to its /version endpoint (part of the version-emulation feature). Strimzi 0.43 ships a fabric8 Kubernetes client old enough to reject unknown fields. Dead on startup.</p><p><strong>Fix:</strong> bump to Strimzi 0.51.0, which uses a newer fabric8 that tolerates the new fields.</p><p>This is a lesson you only learn by touching running systems. Version compatibility between operators, their embedded clients, and the underlying Kubernetes version is a real source of friction. When something crashes on startup with a Java stack trace full of serialization exceptions, 9 times out of 10 it’s this.</p><h3>KRaft — why no Zookeeper?</h3><p>Kafka used to depend on Apache Zookeeper for controller quorum, broker membership, and partition leadership election. Zookeeper was always awkward — a second distributed system to operate, with its own failure modes, configuration language, and operational playbook.</p><p>KRaft (Kafka Raft) replaces Zookeeper with an internal Raft implementation running on a subset of Kafka brokers called <strong>controllers</strong>. The controllers are the metadata quorum; the other brokers are the data plane. One system, one config language, one set of logs.</p><p>As of Kafka 4.0, Zookeeper mode is removed entirely. KRaft is the only option. Learn it now.</p><h3>NodePools — brokers vs controllers separated</h3><p>Strimzi’s newer API models each role as a separate KafkaNodePool CR (<a href="https://medium.com/days/day-1/k8s/02-kafka/kafka-cluster.yaml">k8s/02-kafka/kafka-cluster.yaml</a>):</p><pre>apiVersion: kafka.strimzi.io/v1beta2<br>kind: KafkaNodePool<br>metadata: { name: controller, labels: { strimzi.io/cluster: data-pipeline } }<br>spec:<br>  replicas: 3<br>  roles: [controller]<br>  storage: { type: persistent-claim, size: 10Gi }<br>---<br>apiVersion: kafka.strimzi.io/v1beta2<br>kind: KafkaNodePool<br>metadata: { name: broker, labels: { strimzi.io/cluster: data-pipeline } }<br>spec:<br>  replicas: 3<br>  roles: [broker]<br>  storage: { type: persistent-claim, size: 20Gi }</pre><p>Two separate fleets — 3 controllers (for the Raft quorum) and 3 brokers (for the data plane). In production you’d scale these independently: more brokers when throughput goes up, more controllers only if metadata churn becomes a bottleneck (rare). Keeping them separate is also a blast-radius play: a misbehaving broker can’t destabilize the metadata quorum because it’s not part of it.</p><h3>The Kafka CR itself</h3><pre>apiVersion: kafka.strimzi.io/v1beta2<br>kind: Kafka<br>metadata:<br>  name: data-pipeline<br>  annotations:<br>    strimzi.io/node-pools: enabled<br>    strimzi.io/kraft: enabled<br>spec:<br>  kafka:<br>    version: 4.1.0<br>    metadataVersion: 4.1-IV1<br>    listeners:<br>      - { name: plain, port: 9092, type: internal, tls: false }<br>    config:<br>      default.replication.factor: 3<br>      min.insync.replicas: 2<br>      offsets.topic.replication.factor: 3<br>      transaction.state.log.replication.factor: 3<br>      transaction.state.log.min.isr: 2<br>  entityOperator:<br>    topicOperator: {}<br>    userOperator: {}</pre><p>Two configs worth remembering from this block:</p><p><strong>default.replication.factor: 3, min.insync.replicas: 2</strong>. This is the sane default for any Kafka cluster. Replication factor 3 means three copies of every partition, on three different brokers. min.insync.replicas=2 means a producer using acks=all only gets acknowledged after at least 2 of those 3 replicas have the data. That guarantees the cluster survives one broker loss without losing data.</p><p><strong>The </strong><strong>entityOperator block</strong>. This runs two additional controllers inside an entity-operator pod: the <strong>Topic Operator</strong> (watches KafkaTopic CRs and creates Kafka topics) and the <strong>User Operator</strong> (watches KafkaUser CRs for SCRAM/mTLS credentials). Without these, KafkaTopic CRs are just inert YAML.</p><h3>Topics as CRs</h3><p>The topics are declared in <a href="https://medium.com/days/day-1/k8s/02-kafka/kafka-topics.yaml">k8s/02-kafka/kafka-topics.yaml</a>:</p><pre>apiVersion: kafka.strimzi.io/v1beta2<br>kind: KafkaTopic<br>metadata:<br>  name: analytics<br>  labels: { strimzi.io/cluster: data-pipeline }<br>spec:<br>  partitions: 3<br>  replicas: 3<br>  config:<br>    retention.ms: 604800000          # 7 days<br>    min.insync.replicas: 2<br>---<br># ... engagement-topic, webrtc-analytics, same shape ...<br>---<br>apiVersion: kafka.strimzi.io/v1beta2<br>kind: KafkaTopic<br>metadata:<br>  name: schemas-registry<br>  labels: { strimzi.io/cluster: data-pipeline }<br>spec:<br>  topicName: _schemas             # real Kafka topic name<br>  partitions: 1<br>  replicas: 3<br>  config:<br>    cleanup.policy: compact<br>    min.insync.replicas: 2</pre><p><strong>The </strong><strong>_schemas name trick.</strong> Schema Registry hardcodes its storage topic as _schemas (the underscore is intentional). But Kubernetes CR metadata.name must be a DNS-1123 subdomain — no leading underscores allowed. Strimzi solves this with spec.topicName, which decouples the Kubernetes resource name from the Kafka topic name. The CR is called schemas-registry (valid DNS-1123); the underlying Kafka topic is _schemas (what Schema Registry expects).</p><p><strong>Why this topic is different.</strong> Every other topic has 3 partitions. _schemas has 1. Ordering of schema commits must be global — if subject analytics-value gets two near-simultaneous version-2 registrations, exactly one must win, and the other must see a compatibility error. That&#39;s only possible if there&#39;s one partition ordering the commits. cleanup.policy: compact (vs. the default delete) means only the latest value per key is retained forever, not trimmed after 7 days. For Schema Registry&#39;s WAL, you want both — one partition and compaction.</p><h3>Deploy and verify</h3><pre>make kafka                  # operator + cluster + topics, ~3-5 minutes<br>make verify-kafka           # cluster Ready, topics Ready, produce+consume</pre><p>The verify script (<a href="https://medium.com/days/day-1/scripts/verify-kafka.sh">scripts/verify-kafka.sh</a>) does four things:</p><ol><li>Waits for the Kafka/data-pipeline CR to report condition=Ready. This is the operator&#39;s signal that brokers + controllers are all up and the cluster is operational. Stronger than pod=Running because pods can be up before they&#39;ve joined the quorum.</li><li>Waits for each KafkaTopic to report Ready. That means the Topic Operator has reconciled the CR into an actual Kafka topic with the requested partitions/RF/configs.</li><li>Lists the broker pods (expect 3: data-pipeline-broker-{0,1,2}).</li><li><strong>The actual wire test</strong> — spawns a throwaway pod, produces one message to analytics, consumes it back.</li></ol><p>You can reproduce step 4 manually:</p><pre>kubectl --context=data-pipeline -n data-pipeline run kafka-rt-$RANDOM \<br>  --rm --restart=Never --attach=true --stdin=false \<br>  --image=quay.io/strimzi/kafka:0.51.0-kafka-4.1.0 \<br>  --command -- /bin/sh -c &#39;<br>    echo &quot;hello-from-day-1-$(date +%s)&quot; | bin/kafka-console-producer.sh \<br>      --bootstrap-server data-pipeline-kafka-bootstrap:9092 --topic analytics<br>    echo &quot;--- consumed: ---&quot;<br>    bin/kafka-console-consumer.sh \<br>      --bootstrap-server data-pipeline-kafka-bootstrap:9092 --topic analytics \<br>      --from-beginning --max-messages 1 --timeout-ms 15000<br>  &#39;</pre><p>Notice the image — quay.io/strimzi/kafka:0.51.0-kafka-4.1.0. It bundles the full Kafka distribution, including bin/kafka-console-producer.sh and bin/kafka-console-consumer.sh. Running that image with --command is how you get a transient Kafka CLI environment without installing anything locally.</p><h3>The Kafka version trap (second war story)</h3><p>When I bumped Strimzi to 0.51.0, I left the Kafka CR on version 3.9.0. Reconciliation failed:</p><pre>io.strimzi.operator.cluster.model.KafkaVersion$UnsupportedKafkaVersionException:<br>Unsupported Kafka.spec.kafka.version: 3.9.0.<br>Supported versions are: [4.1.0, 4.1.1, 4.2.0]</pre><p>Strimzi 0.51 dropped support for Kafka 3.x. The fix was a two-line edit — version: 4.1.0 and metadataVersion: 4.1-IV1. The lesson: <strong>operator version and component version are coupled</strong>, and the coupling is hard to discover until you read the operator&#39;s release notes. Make a habit of checking the compatibility matrix before bumping either side.</p><h3>Phase 1c — Confluent Schema Registry</h3><h3>What Schema Registry is for</h3><p>Kafka stores bytes. It has no opinion on what those bytes mean. If your producer sends AnalyticsEvent bytes and your consumer decodes them as BillingEvent, Kafka will not help you. This is the single largest class of data-pipeline bug: <strong>schema drift</strong>.</p><p>Schema Registry is a service that holds a catalog of versioned schemas and enforces a compatibility policy when schemas change. Producers look up the schema ID before sending; consumers look it up to decode. Every Avro-encoded message on the wire has this format</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXYlBTMMvuNM8tsJtPnutw.png" /><figcaption>Avro-encoded message</figcaption></figure><p>The schema ID is how the decoder knows which schema to use. That ID is <strong>per-message</strong>, not per-topic. Version 1 and version 3 messages can sit side-by-side in the same partition and both be decoded correctly.</p><h3>Subject, version, ID — three separate things</h3><p>The most common Schema Registry misunderstanding is collapsing these three concepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6O5OqfHIEe7jVAZhY2QYQ.png" /><figcaption>Subject, version, ID — three separate things</figcaption></figure><p>A subject is typically named `&lt;topic&gt;-key` or `&lt;topic&gt;-value`. It represents the evolution history of schemas attached to that facet of that topic. Versions are per-subject (`analytics-value` v1, v2, v3).</p><p>IDs are generated and tracked by Schema Registry, not by Kafka. The ID space is scoped to the `_schemas` topic that Schema Registry is backed by. In the common setup — one Kafka cluster with one Schema Registry in front of it, which is what this lab runs — the first schema ever registered gets ID 1, the second gets ID 2, and so on, across every subject. Two different Schema Registries pointed at different `_schemas` topics would have independent ID counters (their ID 1 means different things).</p><h3>The deployment and the enableServiceLinks bug (third war story)</h3><p>The Schema Registry Deployment (<a href="https://medium.com/days/day-1/k8s/02-kafka/schema-registry.yaml">k8s/02-kafka/schema-registry.yaml</a>) looks straightforward — a single pod, confluentinc/cp-schema-registry:7.7.1, pointed at Kafka, listening on :8081.</p><p>On first deploy, it crashed immediately with exit code 1. No useful stack trace in the logs — just:</p><pre>===&gt; Configuring ...<br>PORT is deprecated. Please use SCHEMA_REGISTRY_LISTENERS instead.</pre><p>And then death.</p><p>The cause took a while to find. Kubernetes, by default, injects service-discovery environment variables into every pod in the namespace. If you have a Service named schema-registry on port 8081, every pod in that namespace gets:</p><pre>SCHEMA_REGISTRY_SERVICE_HOST=10.x.x.x<br>SCHEMA_REGISTRY_SERVICE_PORT=8081<br>SCHEMA_REGISTRY_PORT=tcp://10.x.x.x:8081<br>SCHEMA_REGISTRY_PORT_8081_TCP=tcp://10.x.x.x:8081<br>...</pre><p>The Schema Registry container’s entrypoint script treats any env var starting with SCHEMA_REGISTRY_ as a configuration property — that&#39;s how it accepts settings like SCHEMA_REGISTRY_LISTENERS, SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS, etc. So the auto-injected SCHEMA_REGISTRY_PORT=tcp://10.x.x.x:8081 gets interpreted as a config property port=tcp://10.x.x.x:8081, which is invalid. The container immediately dies with a config parse error — silently, because the parse error goes to stderr and the container shell only streams the earlier &quot;Configuring...&quot; line.</p><p><strong>The fix is one line:</strong></p><pre>spec:<br>  template:<br>    spec:<br>      enableServiceLinks: false   # disable auto env var injection<br>      containers: ...</pre><p>This is a trap specifically for containers whose configuration language is “environment variables with the same prefix as their Kubernetes Service name.” Kafka, Redis, Elasticsearch, and anything else from the Confluent Platform family can hit it. Setting enableServiceLinks: false is a reasonable default for most pods you author — the auto-injected vars are a legacy Kubernetes feature from before DNS-based service discovery existed. You almost never need them.</p><h3>Verify the Schema Registry</h3><pre>make schema-registry<br>make verify-schema-registry</pre><p>The verify script (<a href="https://medium.com/days/day-1/scripts/verify-schema-registry.sh">scripts/verify-schema-registry.sh</a>) runs four HTTP calls from a transient curlimages/curl pod:</p><ol><li>POST /subjects/analytics-value/versions — register an Avro schema.</li><li>GET /schemas/ids/1 — fetch that schema back by its global ID.</li><li>GET /subjects — list all subjects.</li><li>GET /subjects/analytics-value/versions — list versions of one subject.</li></ol><h3>Try the registry manually</h3><p>To get a terminal-level feel for it, port-forward and use your laptop’s curl:</p><pre># Terminal 1 — leave running<br>kubectl --context=data-pipeline -n data-pipeline port-forward svc/schema-registry 8081:8081</pre><pre># Terminal 2 — register an initial schema<br>curl -sS -X POST \<br>  -H &#39;Content-Type: application/vnd.schemaregistry.v1+json&#39; \<br>  --data &#39;{&quot;schema&quot;:&quot;{\&quot;type\&quot;:\&quot;record\&quot;,\&quot;name\&quot;:\&quot;AnalyticsEvent\&quot;,\&quot;fields\&quot;:[{\&quot;name\&quot;:\&quot;meetingId\&quot;,\&quot;type\&quot;:\&quot;string\&quot;},{\&quot;name\&quot;:\&quot;zoneId\&quot;,\&quot;type\&quot;:\&quot;int\&quot;},{\&quot;name\&quot;:\&quot;ts\&quot;,\&quot;type\&quot;:\&quot;long\&quot;}]}&quot;}&#39; \<br>  http://localhost:8081/subjects/analytics-value/versions<br># → {&quot;id&quot;:1}</pre><pre># Fetch by ID<br>curl -sS http://localhost:8081/schemas/ids/1<br># List subjects<br>curl -sS http://localhost:8081/subjects<br># → [&quot;analytics-value&quot;]<br># Evolve: add an optional field (backward-compatible)<br>curl -sS -X POST \<br>  -H &#39;Content-Type: application/vnd.schemaregistry.v1+json&#39; \<br>  --data &#39;{&quot;schema&quot;:&quot;{\&quot;type\&quot;:\&quot;record\&quot;,\&quot;name\&quot;:\&quot;AnalyticsEvent\&quot;,\&quot;fields\&quot;:[{\&quot;name\&quot;:\&quot;meetingId\&quot;,\&quot;type\&quot;:\&quot;string\&quot;},{\&quot;name\&quot;:\&quot;zoneId\&quot;,\&quot;type\&quot;:\&quot;int\&quot;},{\&quot;name\&quot;:\&quot;ts\&quot;,\&quot;type\&quot;:\&quot;long\&quot;},{\&quot;name\&quot;:\&quot;userId\&quot;,\&quot;type\&quot;:[\&quot;null\&quot;,\&quot;string\&quot;],\&quot;default\&quot;:null}]}&quot;}&#39; \<br>  http://localhost:8081/subjects/analytics-value/versions<br># → {&quot;id&quot;:2}   (new global ID; becomes version 2 of the subject)<br>curl -sS http://localhost:8081/subjects/analytics-value/versions<br># → [1,2]<br># Try an incompatible change: change meetingId from string to int<br>curl -sS -X POST \<br>  -H &#39;Content-Type: application/vnd.schemaregistry.v1+json&#39; \<br>  --data &#39;{&quot;schema&quot;:&quot;{\&quot;type\&quot;:\&quot;record\&quot;,\&quot;name\&quot;:\&quot;AnalyticsEvent\&quot;,\&quot;fields\&quot;:[{\&quot;name\&quot;:\&quot;meetingId\&quot;,\&quot;type\&quot;:\&quot;int\&quot;}]}&quot;}&#39; \<br>  http://localhost:8081/subjects/analytics-value/versions<br># → HTTP 409 Conflict<br># → {&quot;error_code&quot;:409,&quot;message&quot;:&quot;Schema being registered is incompatible with an earlier schema...&quot;}</pre><p>That 409 is the <em>point</em>. The whole value of Schema Registry shows up here: a breaking change gets refused before any producer can write incompatible data into the topic. No matter how confident the developer making the change is, their code literally cannot ship an incompatible schema into this pipeline.</p><h3>Can one topic carry different schemas?</h3><p>Short answer: Kafka doesn’t care, Schema Registry does.</p><p>By default (TopicNameStrategy), Schema Registry maps topic=analytics to subject=analytics-value, and that subject is an evolution history — one conceptual event type, growing over time. It will not let you mix AnalyticsEvent and BillingEvent in the same topic, because both would try to register as versions of analytics-value and fail the compatibility check.</p><p>Other strategies (RecordNameStrategy, TopicRecordNameStrategy) do allow multiple unrelated record types per topic. Those are used for event-sourced systems where all events about one entity belong together. For conventional analytics pipelines, stay with the default and treat &quot;one topic = one conceptual event type&quot; as a design principle, not just a Schema Registry quirk.</p><h3>Mental model to lock in</h3><blockquote><em>Schema Registry is a </em><strong><em>cache in front of a Kafka log</em></strong><em>. The log (</em><em>_schemas) is the source of truth — compacted, single partition, durable. The REST API on </em><em>:8081 is the interface everyone uses, but if it goes down, all schema data survives. Restart it and it replays </em><em>_schemas from offset 0 to rebuild its in-memory cache.</em></blockquote><h3>What Broke (and the Lessons)</h3><p>In the course of getting Day 1 working end-to-end, I hit four distinct failures. Every one of them teaches something that’ll come up again. Here they are, condensed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTL4lbpn_5LNlsiRuDZ6BQ.png" /><figcaption>issues encountered during setup</figcaption></figure><p>Every one of these is the kind of bug a senior engineer has seen fifteen times and a new engineer has never seen. Writing them down is how you move from one camp to the other.</p><h3>Deploy the Whole Day in One Command</h3><p>If you want to skip the explanation and just stand the whole thing up, the <a href="https://medium.com/days/day-1/Makefile">days/day-1/Makefile</a> has a convenience target:</p><pre>cd days/day-1<br>make up<br># runs: minikube-up → phase0 → minio → kafka → schema-registry</pre><p>Individual steps and their verifiers, for when you want to step through:</p><pre>make minikube-up         # start minikube profile data-pipeline (10 CPU / 24 GB)<br>make phase0              # namespace + resource quota + limit range<br>make verify-phase0       # includes intentional over-quota rejection test<br></pre><pre>make minio               # secret + service + statefulset + bucket-init job<br>make verify-minio        # pod + bucket layout + round-trip read/write<br>make kafka               # strimzi operator + kafka cluster + 4 topic CRs<br>make verify-kafka        # cluster Ready + topics Ready + produce/consume<br>make schema-registry     # confluent schema-registry deployment + service<br>make verify-schema-registry   # register + fetch-by-id + list subjects<br>make status              # show everything in the data-pipeline namespace</pre><p>Tear-down at end of day (state preserved, cluster restartable):</p><pre>make minikube-stop</pre><p>Wipe everything (start completely fresh tomorrow):</p><pre>make minikube-destroy</pre><h3>Checkpoints — Can You Answer These?</h3><p>If yes, Day 2 will land cleanly. If no, go back and read this blog again</p><ol><li>What’s the difference between a <strong>namespace</strong> and a <strong>ResourceQuota</strong>? Why does a ResourceQuota <em>force</em> you to also have a <strong>LimitRange</strong>?</li><li>What does <strong>min.insync.replicas=2</strong> actually guarantee? What happens to writes if two of three brokers are down?</li><li>What does a <strong>Kafka consumer group</strong> do? How is this different from a message queue’s concept of a consumer?</li><li>Why is the <strong>_schemas</strong> topic compacted and single-partition, while the other topics are 3-partition and time-retained?</li><li>What’s the <strong>wire format</strong> of a Confluent-encoded Avro message? What’s in each byte?</li><li>A team wants to add an optional field to an Avro schema. What compatibility mode do they need, and what’s the REST call they make? What would make Schema Registry refuse the change?</li><li>Why is <strong>S3 not a filesystem</strong>? What’s the one atomic primitive it <em>does</em> offer that makes Delta Lake possible?</li><li>What’s the difference between a <strong>Subject</strong>, a <strong>Version</strong>, and a <strong>Schema ID</strong> in Schema Registry?</li></ol><h3>What’s Next — Day 2</h3><p>Today we built the substrate. Nothing is producing traffic yet. Tomorrow we fix that.</p><p><strong>Day 2 — Event Source: Mock GAP and the Classroom Simulator.</strong> A FastAPI service (Mock GAP) accepts JSON over HTTP, validates it, serializes to Confluent-wire-format Avro using the schema we registered today, and produces to the analytics topic. A second service (Classroom Simulator) generates realistic traffic — 3000 simulated meetings across 5 geographic zones, with Poisson-distributed event arrivals, meeting lifecycle events, and intentional late-arriving data to stress later watermark handling.</p><p>By the end of Day 2 you’ll understand producer semantics, idempotent delivery, partition keys, and the difference between at-least-once and exactly-once in the context of a real client library.</p><p>See you then.</p><p><em>This is part of a 7-day series building a full analytics pipeline from scratch on Minikube. </em><a href="https://medium.com/@akash94thakur/building-a-production-grade-analytics-pipeline-on-your-laptop-a-7-day-learning-journey-976e0032119f"><em>Day 0 — Kickoff.</em></a><em> </em><a href="https://github.com/thinkingmonster/data-pipeline"><em>All posts and source code.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc15508a5faa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Production-Grade Analytics Pipeline on Your Laptop: A 7-Day Learning Journey]]></title>
            <link>https://medium.com/@akash94thakur/building-a-production-grade-analytics-pipeline-on-your-laptop-a-7-day-learning-journey-976e0032119f?source=rss-36df1949e96a------2</link>
            <guid isPermaLink="false">https://medium.com/p/976e0032119f</guid>
            <category><![CDATA[delta-lake]]></category>
            <category><![CDATA[starrocks]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[lambda-architecture]]></category>
            <dc:creator><![CDATA[Thinking monster]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 04:02:55 GMT</pubDate>
            <atom:updated>2026-04-13T04:02:55.360Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Day 0 — Kickoff. The problem we’re solving, what we’re building, and how.</em></p><h3>The Problem We’re Going to Solve</h3><p>Imagine you’re the platform engineer at a growing virtual-classroom company. At peak hours, a few thousand live sessions are happening simultaneously. Teachers are streaming lessons. Students across five geographic zones are joining, leaving, raising hands, speaking, losing connection, reconnecting. Every mic toggle, every network dip, every “student joined” event is a potential data point.</p><p>The product team shows up at your desk with questions nobody can answer well right now:</p><ul><li><em>“How many meetings are live in zone 3 this minute? Is it trending up or down?”</em></li><li><em>“Which zones had the most connection drops in the last hour? We’d like a dashboard that refreshes in real time.”</em></li><li><em>“For yesterday’s session with class ID X, how long did each student actually speak? What was the average attention score? When did engagement drop off?”</em></li><li><em>“We shipped a new WebRTC build last Tuesday. Did it change the overall connection quality? Compare the week before and after.”</em></li><li><em>“An incident happened at 14:32 UTC three days ago. Pull every event around that timestamp so we can reconstruct what went wrong.”</em></li></ul><p>These aren’t exotic questions. They’re the bread-and-butter asks of any product team running a real-time service. But answering them <em>well</em> requires infrastructure that the application itself doesn’t provide:</p><ul><li>Events need to be captured reliably, with a schema the team can trust — application logs won’t cut it.</li><li>They need to land somewhere durable and queryable, at scale, without losing any.</li><li>Real-time questions (“what’s happening right now?”) need a streaming path that responds in seconds.</li><li>Historical questions (“what changed last week?”) need a batch path that can reprocess months of data.</li><li>Analysts need a SQL interface — they don’t want to write Spark jobs.</li><li>Product managers want dashboards they can open without asking you.</li></ul><p>This is the classic <strong>Lambda architecture</strong> shape: a streaming lane for low-latency insight, a batch lane for correctness and reprocessing, a shared durable storage layer underneath it all, and a SQL engine up front so humans can ask questions.</p><p>Over the next seven days, we’re going to build exactly that pipeline. End to end. On one laptop. With the same tools that real platforms run in production.</p><h3>What We’re Building</h3><p>Seven days. One Minikube cluster. A complete Lambda-style analytics pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RXZDoo6qtqMadwRciZG8AA.png" /><figcaption>Typical data pipeline flow</figcaption></figure><p>Every box in that diagram is something you’ll deploy, configure, feed with simulated traffic, deliberately break, and recover.</p><p>Nine components. All open-source. All production-calibre.</p><ul><li><strong>Strimzi Kafka</strong> in KRaft mode (no Zookeeper) — the ingest log.</li><li><strong>Confluent Schema Registry</strong> with Avro — the schema contract.</li><li><strong>MinIO</strong> as an S3-compatible object store — the durable storage layer.</li><li><strong>PostgreSQL + Hive Metastore</strong> — the data catalog.</li><li><strong>Spark Operator</strong> running Structured Streaming on Kubernetes — the streaming compute engine.</li><li><strong>Delta Lake</strong> on object storage — ACID transactions and time travel.</li><li><strong>Apache Airflow</strong> — batch orchestration.</li><li><strong>StarRocks</strong> as the MPP query engine — sub-second SQL over Delta.</li><li><strong>Grafana</strong> — visualization.</li></ul><p>Each one maps directly onto a managed cloud equivalent — the shape is what matters, the specific tool is interchangeable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgoyWR5zDOfhHtDMWW-dgw.png" /><figcaption>Swapable technology stack for each lab component on cloud provider.</figcaption></figure><p>Build the pattern once, at the primitives layer, and everything above slots in.</p><h3>Why This Particular Stack</h3><p>I’ve spent the last decade and a half in SRE and platform engineering roles, and I’ve watched this architecture emerge and stabilise across every company I’ve worked with that has nontrivial event data. The specific tools change — some shops prefer Pulsar over Kafka, or Iceberg over Delta, or Trino over StarRocks — but the <em>shape</em> is remarkably stable:</p><ol><li>A schema-enforced ingest log.</li><li>A streaming compute layer that decodes, enriches, and lands events durably.</li><li>An object store is the system of record.</li><li>A batch orchestrator that periodically refines and aggregates.</li><li>A catalogue that lets multiple engines read the same data.</li><li>An MPP engine for interactive SQL.</li><li>A dashboarding layer on top.</li></ol><p>Every one of our fictional product team’s questions maps to a specific layer of this stack:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnMQW42gSq-M23pmvhpFLg.png" /><figcaption>Importance of each layer</figcaption></figure><p>None of these requires magic. Each requires knowing which layer owns the answer and how to wire them together.</p><h3>The 7-Day Plan</h3><p>Each day, one concrete slice of the pipeline targets a specific mental model. You can follow along live or batch a day’s worth of work into a weekend session — whichever fits your rhythm.</p><h3>Day 1 — Foundation: Kafka, Schema Registry, and Object Storage</h3><p>We start with the substrate. A Minikube profile sized for a heavy data stack (10 CPU, 24 GB), a dedicated namespace with resource quotas, and the three services everything else depends on: <strong>Strimzi Kafka</strong> (brokers as Kafka CRs, topics as KafkaTopic CRs), <strong>Confluent Schema Registry</strong> (wire format, subject naming, compatibility modes), and <strong>MinIO</strong> (S3-compatible but not quite — we&#39;ll see why Delta Lake works on it at all).</p><p>By the end of Day 1, you’ll own: the concept of Kafka as a <em>replicated log</em> (not a queue), the exact wire format Confluent producers emit, and why “S3 is not a filesystem” is more than pedantry.</p><h3>Day 2 — Event Source: Mock GAP and the Classroom Simulator</h3><p>A pipeline is only as interesting as its traffic. We build two things: a <strong>Mock GAP service</strong> — GAP stands for <em>Global Analytics Platform</em>, the HTTP ingest gateway that sits in front of Kafka in any real platform, handling auth, schema enforcement, and topic routing. Ours is a FastAPI app that accepts JSON events, registers and caches Avro schemas with the Registry, and produces to Kafka in Confluent wire format. Alongside it, a <strong>Classroom Simulator</strong> models teachers and students joining virtual meetings across five zones, generating engagement events, and emitting meeting_end signals that later drive orchestration.</p><p>By the end of Day 2, you’ll own: producer semantics (acks, idempotency, partitioners, linger.ms), why GAP is a <em>translation boundary</em> where validation must happen, and how bursty-versus-uniform traffic patterns affect backpressure downstream.</p><h3>Day 3 — Catalog: PostgreSQL and Hive Metastore</h3><p>Data without metadata is unusable. We deploy PostgreSQL as the Hive Metastore backend, bootstrap the HMS schema, and stand up the Thrift endpoint on port 9083. Then we wire it so both Spark writes and StarRocks reads consult it as the single source of truth for table → path mappings.</p><p>By the end of Day 3, you’ll own: the <strong>catalogue-versus-storage separation</strong> — one of the most important conceptual splits in modern lakehouse architecture. Why MSCK REPAIR TABLE is a command that exists? What an external catalogue actually is.</p><h3>Day 4 — Streaming: Spark Operator, Structured Streaming, Delta Lake</h3><p>The heart of the pipeline. Spark Operator installs the SparkApplication CRD. We deploy a single SparkApplication that runs four concurrent Structured Streaming queries in one Spark context, all writing to Delta Lake on MinIO. We set up checkpoints so restarts are safe, and we verify exactly-once semantics end-to-end.</p><p>By the end of Day 4, you’ll own: Structured Streaming’s micro-batch model, the three places streaming state lives (Kafka offsets, Spark checkpoints, Delta _delta_log), Delta&#39;s optimistic concurrency control, and time travel. This is the longest day because it&#39;s where the most production incidents actually happen.</p><h3>Day 5 — Orchestration: Airflow and Silver DAGs</h3><p>Streaming gives you real-time bronze tables. Batch gives you correctness and the ability to reprocess. We deploy Airflow (LocalExecutor, DAGs via ConfigMap), write three DAGs — streams_job_runner (bronze → silver), speech_time (engagement aggregation), vacuum_bronze (Delta cleanup) — and wire the streaming-to-batch handoff: a An meeting_end event in Kafka triggers a Spark stream that triggers a REST call to Airflow that triggers a silver-table computation.</p><p>By the end of Day 5, you’ll own: orchestration as a <em>state machine over DAG runs</em>, not a job runner. Why is idempotency non-negotiable? The difference between execution_date and wall-clock time.</p><h3>Day 6 — Query and Visualisation: StarRocks and Grafana</h3><p>Spark is great for ETL and terrible for interactive queries. StarRocks is the other end of the trade-off — an MPP engine with sub-second response on columnar data, speaking MySQL wire protocol so any SQL client can connect. We register it as an external catalogue pointing at Hive Metastore and MinIO; it reads Delta files in place with zero data movement. Grafana connects on top for dashboards.</p><p>By the end of Day 6, you’ll know: when to reach for a query engine versus a compute engine. What “MPP” actually means mechanically. Why the <strong>lakehouse pattern</strong> (decoupled storage, multiple readers, shared catalogue) is eating the data-warehouse market. This is also the day we finally answer the product team’s five questions — the pipeline stops being a lab exercise and becomes a tool.</p><h3>Day 7 — Break and Fix: Ten Experiments</h3><p>The final day is the most important. We deliberately break the pipeline in ten different ways — schema evolution, consumer lag, checkpoint loss, partition-key mismatch, HMS drift, catalogue staleness, vacuum-breaks-time-travel — observe what happens, then recover.</p><p>Every experiment isolates one failure mode. After all ten, you can answer:</p><ul><li>“Rows are missing in the dashboard — where do I start looking?”</li><li>“A Spark job crashed mid-batch — how do I verify no duplicates?”</li><li>“We’re rolling out a schema change — what’s the upgrade order?”</li><li>“The catalogue shows a table, but queries return empty — what’s wrong?”</li></ul><p>This is the day that converts knowledge into instinct.</p><h3>What You’ll Walk Away With</h3><p>By the end of Day 7, you’ll have:</p><ul><li><strong>A running, working pipeline</strong> on your laptop — end to end, every layer — that you can restart, rebuild, and experiment on whenever you want. It will answer every one of the product team’s five questions from the opening of this post.</li><li><strong>Mental models for every tool in the stack.</strong> Not “I’ve heard of Airflow” — <em>I can draw this on a whiteboard and defend every choice,</em> understanding.</li><li><strong>Operator intuition</strong> for the failure modes that actually happen in production. You’ll know where data pipelines break, because you’ll have broken yours in every relevant way.</li><li><strong>A reusable lab architecture.</strong> Want to swap Kafka for Pulsar? Delta for Iceberg? StarRocks for Trino? The scaffolding is there. Change one layer at a time.</li><li><strong>A reference implementation</strong> you can point to the next time someone at your company says “we need event analytics.” You won’t be starting from slideware.</li></ul><h3>Who This Series Is For</h3><ul><li><strong>SREs and platform engineers</strong> responsible for (or adjacent to) data infrastructure, who want to understand it deeply enough to operate it instead of only read about it.</li><li><strong>Data engineers</strong> who’ve worked primarily with managed services (Databricks, BigQuery, Snowflake) and want to see the primitives underneath the UI.</li><li><strong>Software engineers</strong> who find themselves being pulled into data-pipeline design or debugging, and realise the abstractions are leakier than expected.</li><li><strong>Anyone tired of “here’s a managed-service notebook, plug in the credentials” tutorials?</strong> Those teach you the UI. This teaches you the machine.</li></ul><h3>Who it’s probably not for</h3><ul><li>Complete beginners. You should already be comfortable with Kubernetes (pods, services, manifests, kubectl), Docker, and at least one of Python or Java. If it kubectl get pods -n foo isn&#39;t muscle memory, do a Kubernetes fundamentals course first and come back.</li><li>People are looking for a quick tutorial. This is seven days because it takes seven days. Shorter tutorials exist. None of them builds the mental models.</li></ul><h3>What You’ll Need</h3><h3>Hardware</h3><p>This is a heavy stack. Plan for:</p><ul><li><strong>CPU</strong>: 8+ cores (more is better; I’ll be running on 32 cores and 128 GB RAM, but 8 cores / 16 GB is the floor).</li><li><strong>Memory</strong>: 24 GB available to Minikube (so 32 GB system minimum, comfortable at 64 GB+).</li><li><strong>Disk</strong>: 100 GB free.</li></ul><p>If your machine is tight on resources, Day 4 (Spark) and Day 6 (StarRocks) are where you’ll feel it. Running just Days 1–3 is still valuable on a modest laptop.</p><h3>Software</h3><ul><li>Minikube</li><li>kubectl</li><li>Docker</li><li>Helm</li><li>Make</li><li>Python 3.11+</li></ul><p>On macOS with Homebrew, one command gets all six:</p><pre>brew install minikube kubectl docker helm make python@3.11</pre><h3>Mindset</h3><p>The hardest prerequisite to quantify, and the most important.</p><ol><li><strong>Don’t copy-paste and pray.</strong> Every command in this series has a reason. If you don’t know why you’re running it, stop and figure it out before continuing. Google unfamiliar flags. Read the official docs for whatever you’re deploying.</li><li><strong>Break things on purpose.</strong> Day 7 is a structured version of this, but do it throughout. Kill a pod mid-batch and see what happens. Delete a checkpoint. Send a malformed payload. Your intuition grows from watching the system fail.</li><li><strong>Write a paragraph after each day.</strong> Not a TODO list — prose. <em>“Today I learned X, which I didn’t know before. The thing that surprised me was Y. I’m still fuzzy on Z.”</em> If you can’t fill half a page, either the day was too shallow (go deeper) or too familiar (skip next time).</li><li><strong>Don’t skip the concept sections for the code sections.</strong> It’s tempting, because copying manifests feels productive. It isn’t. The manifests are public and forgettable. The concepts are what you’re here for.</li></ol><h3>What’s Next</h3><p>Day 1 lands tomorrow. We’ll start with the Minikube profile and build up through Strimzi Kafka and Schema Registry, ending with MinIO and our first end-to-end round trip: a byte produced to Kafka, consumed by a trivial client, proving the substrate works.</p><p>In the meantime:</p><ol><li><strong>Verify your prereqs.</strong> Run the install line above and make sure all six tools print a version.</li><li><strong>Clone the companion repository</strong> (link coming with Day 1) — the full source tree, manifests, and experiments will be there.</li><li><strong>Re-read the problem statement once.</strong> Keep the product team’s five questions in your head as you read Day 1 onward — every deployment decision maps back to one of them.</li></ol><p>See you tomorrow.</p><p><em>This is Day 0 of a 7-day series on building a production-grade analytics pipeline locally. Next up: Day 1 — Foundation: Kafka, Schema Registry, and Object Storage.</em></p><p><em>If you want to follow along, give this a clap so Medium shows you the rest of the series.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=976e0032119f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The On-Call Alert That Investigates Itself]]></title>
            <link>https://medium.com/@akash94thakur/the-on-call-alert-that-investigates-itself-f4de3b2263b5?source=rss-36df1949e96a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4de3b2263b5</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[aiops]]></category>
            <dc:creator><![CDATA[Thinking monster]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 12:49:43 GMT</pubDate>
            <atom:updated>2026-04-12T17:46:00.027Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Building a self-learning SRE agent with LLMs, MCP, and a vector store that gets smarter every time it gets paged.</strong></p><p>It is 3:07 AM. PagerDuty screams. Your phone lights the ceiling. You reach for the laptop, open a dashboard you have seen a hundred times, and start doing what you have done a hundred times before: grep Splunk for the service name, kubectl-describe the pod, glance at Grafana to see if anything is actually on fire or if it is just <em>that</em> flappy check again.</p><p>After fifteen minutes you type “acknowledged, transient DNS, self-resolved” into the incident. Go back to bed. Get paged at 4:42 AM for the same thing.</p><p>A large fraction of every on-call shift is a machine-readable task done by a sleepy human. The raw work — fetch logs, check pod state, correlate with known runbooks, decide if this is real — is mechanical. The hard part is judgment. Monitoring tools show you a dashboard. They never actually <em>investigate</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*naycCyHydRv4dAnY5znMSw.png" /><figcaption>Investigation REport</figcaption></figure><p>So I built one that does.</p><p>This post walks through <strong>sre-agent</strong>: a platform where an LLM-driven agent picks up alerts, queries live infrastructure through a pluggable protocol, writes a structured root-cause report, and — the part I care about most — <strong>updates its own runbook store after every genuine investigation</strong> so the next similar alert gets resolved faster. It runs end-to-end on a laptop with Ollama, or scales out with a queue broker and multiple workers in production.</p><p>GitHub: <a href="https://github.com/akash94thakur/sre-agent">github.com/akash94thakur/sre-agent</a> <em>(placeholder — update with your actual repo URL)</em></p><h3>What it actually does</h3><p>When an alert fires, sre-agent runs something like this in the background:</p><ol><li><strong>Dedup</strong> the alert so a flapping service does not generate fifty investigations.</li><li><strong>Route</strong> the alert to relevant MCP tool servers based on the service label.</li><li>Hand the LLM the alert metadata plus the available tools, then let it <strong>iteratively decide</strong> which tools to call — search a runbook, fetch service logs, check pod state — until it has enough evidence.</li><li><strong>Correlate</strong> the findings across sources (Splunk + Kubernetes + runbooks) and ask the LLM to produce a structured JSON verdict: genuine | noise | unclear, with a confidence score, root cause, and recommended action.</li><li>If the verdict is “genuine with confidence ≥ 0.5”, <strong>generate a new runbook entry</strong> and feed it back into the vector store, so the next similar incident benefits.</li></ol><p>Here is a real investigation from the test harness (qwen2.5:7b running locally):</p><pre>#8 NodeDiskPressure (logging-service)<br>  status: done<br>  classification: genuine (95%)<br>  urgency: immediate<br>  rounds: 5 rounds, 9 tool calls in 22s<br>  root_cause: &quot;logging-service pods experiencing write failures<br>               due to high disk usage on the node&quot;<br>  learning_applied: true<br>  runbook_generated: 3106 chars of actionable markdown</pre><p>Five rounds of tool calls. Cross-source evidence. A defensible root cause. A new runbook in the knowledge store. All without a human touching the keyboard.</p><p>The next time a NodeDiskPressure fires on a different logging node, Round 1 of the agentic loop now hits search_runbook and pulls the auto-generated entry as context before even querying logs. The system is literally teaching itself.</p><h3>Architecture at a glance</h3><p>Five layers, each doing one thing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHkYn9gd2XFOeBBjm05gSw.png" /><figcaption>Architecture</figcaption></figure><ul><li><strong>Backend (FastAPI on :8080)</strong> exposes REST endpoints for ingest, investigation, and learning; owns the investigation engine and SSE streaming.</li><li><strong>Valkey (Redis-compatible)</strong> is the queue broker. LPUSH enqueues, BRPOP dequeues. Status and results live in TTL keys alongside.</li><li><strong>The worker process</strong> runs the same InvestigationEngine class as the backend, just driven by a blocking queue loop instead of an HTTP request.</li><li><strong>MCP servers</strong> are how the agent actually touches data. More on this in the “tool choices” section.</li><li><strong>Postgres</strong> stores investigation rows (25+ columns — alert metadata, full evidence JSON, report fields, learning state).</li></ul><p>The interesting thing is the <em>tool plane</em>. Everything above it is plumbing. Everything below it is external. The tool plane is where the design decisions live.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MW4OubcRIXNEbpxqfH16_Q.png" /><figcaption>Data flow</figcaption></figure><h3>Tool choices, and why</h3><h3>LLM: pluggable, Ollama-first</h3><p>Three providers implement BaseLLMProvider: Ollama, OpenAI, Anthropic. Switching between them is a single config line:</p><pre>llm:<br>  provider: &quot;ollama&quot;<br>  model: &quot;qwen2.5:7b&quot;<br>  base_url: &quot;http://localhost:11434&quot;</pre><p>I wrote the local dev loop around <strong>Ollama + qwen2.5:7b</strong>. Here is why:</p><ul><li><strong>No API cost during the tight feedback loop of prompt iteration.</strong> When you are iterating on the system prompt for the hundredth time, a paid API turns into a tax.</li><li><strong>Realistic “small model” behaviour.</strong> A lot of real SRE deployments will run on self-hosted Llama or Qwen for data governance reasons. If your prompts only work on GPT-4, you have not built something that can ship.</li><li><strong>Function-calling support.</strong> qwen2.5:7b handles Ollama’s function-calling API well enough for a 5-round investigation loop. You feel the model’s limits (it will occasionally wrap JSON in markdown or add commentary) but it is honest about its weaknesses, which forces you to build a robust parser instead of trusting the model.</li></ul><p>For production, the Anthropic provider is wired in and ready. Swap the config line, set the API key, done.</p><h3>Protocol: MCP, not REST</h3><p>Every data source is a separate <strong>Model Context Protocol</strong> server. The backend never talks to Splunk or Kubernetes directly — it talks to MCP servers, and each MCP server owns its own adapter to the underlying system.</p><p>This matters for a boring, practical reason: <strong>you can add a new data source by writing one Python file and one YAML entry.</strong> No backend code changes. No redeploy of the engine. The LLM discovers the new tools via tools/list, the router starts sending relevant alerts that way, and you are done.</p><p>MCP has two transports:</p><ul><li><strong>stdio</strong> — the MCP server is launched as a subprocess per backend process. JSON-RPC flows over stdin/stdout. Cheap, isolated, no extra port.</li><li><strong>sse (HTTP POST JSON-RPC)</strong> — the MCP server is a long-running HTTP service; multiple clients connect to the same instance.</li></ul><p>In sre-agent I use <strong>stdio for the stateless servers</strong> (splunk-investigator, incident-reader) and <strong>sse for the stateful one</strong> (runbook-rag). I will explain why this matters in the &quot;The mistake that taught me about shared state&quot; section below.</p><h3>Queue: Valkey, not Kafka</h3><p>I went back and forth on this for an evening. Kafka is the obvious choice if you think of a “distributed event-driven system”. But:</p><ul><li><strong>This is a work queue, not an event stream.</strong> There is one consumer per job (the worker pool fairly splits via BRPOP). No replay requirements. No fan-out. No ordering guarantees beyond &quot;oldest job first&quot;.</li><li><strong>Valkey/Redis has a 30-second install curve.</strong> Kafka has a 30-minute-to-30-day install curve depending on whether you are running it properly.</li><li><strong>Graceful degradation is trivial.</strong> If Valkey is unreachable, the backend falls back to FastAPI BackgroundTasks — the investigation still happens, just inside the backend process. With Kafka, &quot;what if the broker is down&quot; is a first-class design problem.</li></ul><p>The rule I apply: <strong>if a Redis-shaped data structure is enough, use Redis.</strong> You can always promote to Kafka later.</p><h3>Database: Postgres + SQLite (dev)</h3><p>Nothing exotic. Investigation is a 25-column SQLAlchemy model. The queue worker uses NullPool for fork-safety. heal_stuck_rows() runs on worker startup to reset any rows stuck in running from a previous crash.</p><p>The one opinionated call: <strong>every phase of the investigation writes back to the DB immediately.</strong> pending → running → done | failed. If the process dies between phases, you can always reconstruct what happened. No in-memory investigation state that vanishes on crash.</p><h3>Frontend: vanilla JS, deliberately</h3><p>Four-tab SPA. ~400 lines of JavaScript, no build step, no framework. Live SSE streaming, dark monospace theme, card-based layout.</p><p>Why no React? Because this is an SRE tool. The audience is engineers who will look at it once, clone it, rip out the dashboard, and bolt on their own. A no-build-step frontend is easier to fork than one that assumes npm, Vite, and a specific Node version. Friction matters.</p><h3>Deep dive 1: Why an agentic loop</h3><p>The single most important architectural decision in the whole project is that the LLM is <strong>not called once per alert.</strong> It is called in a loop, where each round the LLM sees:</p><ul><li>The alert metadata</li><li>The set of available tool definitions (filtered by the MCP router)</li><li>The full conversation history so far, including all prior tool results</li></ul><p>And decides: <strong>call another tool, or conclude?</strong></p><pre># Simplified — real code in backend/src/core/investigation/engine.py</pre><pre>for round_num in range(1, self.max_rounds + 1):<br>    response = await self.llm.chat(<br>        messages=messages,<br>        tools=tool_defs if round_num &lt; self.max_rounds else None,<br>    )<br>    if not response.has_tool_calls:<br>        break  # LLM has enough, conclude<br>    for tc in response.tool_calls:<br>        result = await self.registry.call_tool_by_name(tc.name, tc.arguments)<br>        messages.append(self.llm.format_tool_result(tc.id, tc.name, result))</pre><p>Two things to notice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ajp-kVZx-RoYyMSFfCvCsw.png" /></figure><p><strong>1. The final round has </strong><strong>tools=None.</strong> This is a small trick that matters. If the LLM keeps calling tools forever and never concludes, the last round removes tool access entirely, forcing a text conclusion. Without this, you get runaway loops on edge cases.</p><p><strong>2. The finalize step is a <em>separate</em> LLM call.</strong> After the loop, there is a different prompt that says “here is all the evidence, produce a structured JSON verdict.” I tried mixing investigation and verdict in one prompt. The output was a mess. Separating the two objectives — <em>fetch evidence</em> vs <em>classify</em> — dramatically improved quality.</p><p>Why not a single LLM call? Because at alert time, the LLM literally does not have the data to answer the question. The alert says “PodCrashLooping on payment-service.” The actual evidence — OOM in logs, exit code 137 in K8s events, memory at the limit in Prometheus — lives elsewhere. The LLM has to go fetch it first, then reason.</p><p>A single call would be the LLM confidently guessing without evidence. Which is exactly what we are trying to avoid.</p><h3>Deep dive 2: The self-learning loop</h3><p>This is the part that makes the system interesting rather than just impressive.</p><p>After the investigation produces a verdict, a gate checks two conditions:</p><pre>if report.classification == &quot;noise&quot; or report.confidence &lt; 0.5:<br>    return None  # do not learn from this</pre><p>If the verdict passes the gate, a <strong>second LLM call</strong> generates a markdown runbook entry from the findings — symptoms, root cause, diagnostic steps, remediation, and prevention. That entry is ingested back into the runbook-rag vector store under a namespaced source key: auto-learning:&lt;alertname&gt;:&lt;service&gt;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vyy4xTwLeQJu02d0zc47A.png" /></figure><p>On the next similar alert, Round 1 of the agentic loop hits search_runbook. The vector search returns both:</p><ul><li>The human-written runbook (if one exists under the filename key)</li><li>The auto-generated runbook from prior investigations</li></ul><p>The LLM has context <em>before</em> it touches logs. It can jump straight to the diagnostic steps that worked last time. Fewer rounds. Faster resolution. Lower LLM cost.</p><p>And the real power compounds: every genuine investigation adds to the store. If NodeDiskPressure fires three times in a month, by the third time, the store has three accumulated chunks of learning, and the agent can triage it in a single round.</p><p>There is a subtlety here. If you write new content blindly on every recurrence, you either (a) lose information by overwriting, or (b) bloat the store by append-only. Neither is great. So the update_runbook tool concatenates old-plus-new with a --- separator, re-chunks the combined text, and replaces the old chunks. You get the accumulated knowledge without duplication. Chunks never shrink, but they also do not blow up proportionally to alert volume.</p><h3>Deep dive 3: The noise classification problem</h3><p>This one humbled me.</p><p>The dataset includes a “noise” scenario: a notification service logs an ERROR about a DNS lookup failing for smtp.provider.com, then 5 seconds later a WARN about retrying, then an INFO confirming DNS resolved, email sent successfully. Zero pod restarts. 0 5xx errors. 5420 successful 2xx requests in the same window. A human reads this and says &quot;that is noise&quot; in three seconds.</p><p>My first pass, the agent classified it as <strong>genuine with 90% confidence.</strong> Root cause: “DNS resolution failure for smtp.provider.com caused repeated ERROR logs.” Recommended action: “Investigate DNS configuration.”</p><p>No. The DNS failure has recovered. There was no problem. The agent was wrong.</p><p>The data was fine. The model was fine. The bug was in the prompts. Specifically:</p><ul><li><strong>The system prompt framed the job as “find the root cause.”</strong> It never told the LLM that “no problem here, this was transient” was a valid answer.</li><li><strong>The finalize prompt defined the JSON schema with three possible classifications</strong> — genuine, noise, unclear — <strong>but the rules section gave two examples for genuine and zero for noise.</strong> So the LLM learned from the examples, not from the schema.</li></ul><p>Two surgical prompt edits fixed it:</p><p><strong>In the system prompt</strong>, a new step: <em>“Look for resolution signals. If errors are followed by success logs — retry succeeded, traffic normal, no pod restarts — the alert may be noise. Not every alert indicates a real problem.”</em></p><p><strong>In the finalize prompt</strong>, explicit noise indicators: <em>“Recovery evidence outweighs prior errors. If you see an INFO/success log after an ERROR with no recurrence, classify as noise with HIGH confidence (≥0.8).”</em></p><p>After the fix, the exact same scenario on the exact same model classifies as <strong>noise at 95% confidence.</strong> The learning gate correctly skips — no polluting the RAG store with a fake “runbook” for a non-problem.</p><p>The lesson: <strong>when an LLM is wrong, check if your prompt told it how to be right.</strong> Most “the model is dumb” complaints are actually “the prompt under-specified the desired behaviour.”</p><h3>The mistake that taught me about shared state</h3><p>Here is a bug I hit that only shows up once you have a queue worker running:</p><p>Each process (backend and worker) spawned its <em>own</em> runbook-rag subprocess. Each subprocess had its own in-memory vector store. When the worker ran an investigation and the self-learning pipeline wrote a new runbook entry, it went into the <em>worker&#39;s</em> store. The backend&#39;s /api/learning/runbooks endpoint, which queries the <em>backend&#39;s</em> store, could not see it. The frontend Learning tab looked perpetually stale.</p><p>Two processes. Two stores. No sharing possible.</p><p>I considered three fixes:</p><ol><li><strong>Shared-file SQLite vector table.</strong> Quick, minimal new infra, but two MCP processes hammering one SQLite file with writes is ugly.</li><li><strong>Full vector DB (Qdrant, pgvector).</strong> Correct long-term answer. Too much scope for this project.</li><li><strong>Single </strong><strong>runbook-rag HTTP service.</strong> Extract it into its own process, use MCP&#39;s SSE transport, both backend and worker connect to the same instance.</li></ol><p>I went with option 3. It took ~90 minutes:</p><ul><li>A new file mcp-servers/runbook-rag/http_server.py that imports the same TOOLS and handlers from server.py and wraps them in a FastAPI app exposing /tools/list and /tools/call.</li><li>Flip the config: transport: sse, url: <a href="http://localhost:5001.">http://localhost:5001.</a></li><li>Restart everything.</li></ul><p>Now both backend and worker go through the same HTTP service. One store. One source of truth. The frontend Learning tab sees auto-generated runbooks regardless of which process ran the investigation.</p><p>The pattern is worth internalizing: <strong>stateless MCP → stdio; stateful MCP → sse.</strong> If the server holds state that clients need to share, it must be a singleton. Otherwise, each caller sees its own siloed copy. This is not an MCP quirk — it is true of any sidecar pattern where you forget that “sidecar per process” means “state per process.”</p><h3>Things that surprised me</h3><p>Collected in no particular order, the non-obvious bugs and gotchas from building this:</p><ul><li><strong>FastAPI </strong><strong>BackgroundTasks run <em>after</em> the response is sent.</strong> If you want an alert ingest to kick off an investigation, you need to wire background_tasks.add_task(...) <em>explicitly</em>. Just having the parameter declared does nothing. I shipped a silently broken version of this for a while.</li><li><strong>Zsh reserves </strong><strong>$status as a read-only variable.</strong> My first debugging script broke on s=$(curl ...) because I named the variable status. Fun 20-minute detour.</li><li><strong>The dedup cache lives in the backend process memory.</strong> Restart the backend and the cache resets. Fine for dev; in prod, push the cache into Valkey or Postgres if you actually need durable dedup.</li><li><strong>SQLAlchemy does not auto-migrate columns.</strong> Added learning_applied and learning_content to the model, restarted the backend, everything worked — until the worker (which had a stale SQLite file from earlier) crashed with no such column. The fix was to align cwd between the backend and worker so they hit the same file. Lesson: one db file path, configured once, resolved absolutely.</li><li><strong>Ollama’s function calling is real but quirky.</strong> qwen2.5:7b occasionally returns a tool call inside a markdown code fence with commentary wrapped around it. The parser has four fallback strategies to rescue these: direct JSON, fenced block, regex, and raw-text pass-through. Without them, you lose ~10% of investigations to parsing failures.</li></ul><h3>What I would do differently if I started over</h3><p>Three things:</p><ol><li><strong>Use Qdrant or pgvector from day one.</strong> The in-memory vector store was fine for single-process dev, but I should have known I would hit the multi-process sharing problem and started with a real vector DB. The SHA256-based hash embedding is also a dev shortcut that I would replace with sentence-transformers earlier.</li><li><strong>Make the queue required, not optional.</strong> The FastAPI BackgroundTasks fallback was useful during bring-up, but it is a risk in prod — if a backend instance crashes mid-investigation, the alert goes into a black hole. A queue-required design is simpler and more durable.</li><li><strong>Write integration tests before chasing features.</strong> I have 41 unit and integration tests, but most of them came after I had already shipped the bug they would have caught. Test-first on the bits that cross process boundaries (queue, MCP, DB migrations) would have saved me a full day of debugging.</li></ol><h3>What’s next</h3><ul><li><strong>Swap the in-memory vector store for Qdrant.</strong> It is a one-file change, deferred because the demo works fine in-memory.</li><li><strong>Add metrics.</strong> sre-agent should expose its own Prometheus metrics: investigations per minute, noise ratio, learning rate, MCP call latency, and LLM token usage per investigation.</li><li><strong>Integrate with incident management.</strong> Today, the agent produces a report; the on-call still has to paste it somewhere. A PagerDuty / Jira / Slack integration closes the loop.</li><li><strong>Agent-to-agent escalation.</strong> If the primary agent gets unclear or low confidence, escalate to a larger model or a human-with-context loop. Not every alert deserves the same compute budget.</li></ul><h3>Closing thought</h3><p>Most AI-for-ops demos stop at “look, the LLM wrote a plausible-sounding root cause.” That is the easy part. The LLM is not the hard part.</p><p>The hard parts are the ones nobody tweets about:</p><ul><li>Making the control plane durable when a broker disappears.</li><li>Designing the MCP transport so state is shared where it needs to be.</li><li>Writing prompts that can say “this is not a problem” as confidently as they say “this is a problem.”</li><li>Building a learning loop that accumulates knowledge without polluting it.</li><li>Testing the bits that cross process boundaries.</li></ul><p>Those are the parts that determine whether this ship&#39;s scales, and actually pays back the on-call hours it promised to save.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9t6k2D_0vY2vS-5wXxl1A.png" /><figcaption>ALerts</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gm5lh8LWTQ7wv2-Lkqkjow.png" /><figcaption>Self learning pipeline dashboard</figcaption></figure><p>If you want to dig in, the code is on <a href="https://github.com/thinkingmonster/sre-agent">GitHub</a>. Clone it. Run it against your own stack. Fork the MCP servers. Rip out the frontend. Tell me what breaks.</p><p><strong>Links:</strong></p><ul><li>GitHub: <a href="https://github.com/thinkingmonster/sre-agent">https://github.com/thinkingmonster/sre-agent</a></li><li>Architecture deep-dive: docs/architecture.md</li><li>Full README with setup instructions: README.md</li></ul><p><strong>Stack:</strong> Python 3.12 · FastAPI · SQLAlchemy · Valkey · MCP (Model Context Protocol) · Ollama / OpenAI / Anthropic · Docker Compose · Vanilla JS.</p><p><em>If you found this useful, follow me on Medium and GitHub. I write about SRE, platform engineering, and building production systems with LLMs.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4de3b2263b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Plugin-Based Prometheus Exporter Framework in Python (With FastAPI)]]></title>
            <link>https://medium.com/@akash94thakur/building-a-plugin-based-prometheus-exporter-framework-in-python-with-fastapi-68d85032d372?source=rss-36df1949e96a------2</link>
            <guid isPermaLink="false">https://medium.com/p/68d85032d372</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[prometheus-exporter]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Thinking monster]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 02:14:33 GMT</pubDate>
            <atom:updated>2026-04-12T02:36:22.110Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I stopped writing one-off metric scripts and built a framework that lets any team add new </em><a href="https://github.com/thinkingmonster/prometheus-exporter"><em>Prometheus metrics</em></a><em> by dropping a folder — with zero changes to existing code.</em></p><p>Every SRE team I’ve worked with eventually hits the same problem.</p><p>You start with a quick Python script that exposes a few Prometheus gauges. Maybe it monitors an API rate limit. Maybe it checks if a few endpoints are healthy. It works. You deploy it. Life is good.</p><p>Then another team needs to monitor something else. They write their own script. Then another. And another. Before long you have 8 separate exporter processes, each with its own HTTP server, its own caching logic (or none), its own error handling (or none), and its own deployment pipeline.</p><p>I’ve seen this pattern at both Paytm and Adobe. At some point, someone asks: “Can’t we just have <em>one</em> exporter that handles all of these?”</p><p>This article walks through exactly that — a modular <a href="https://github.com/thinkingmonster/prometheus-exporter">Prometheus exporter framework</a> in Python where adding a new metric source means creating a folder with two files. No framework code changes. No merge conflicts. No coordination meetings.</p><p>The full <a href="https://github.com/thinkingmonster/prometheus-exporter">source code</a> is available at the end. Let’s build it.</p><h3>What We’re Building</h3><p>A single <a href="https://github.com/thinkingmonster/prometheus-exporter">FastAPI application</a> that:</p><ul><li>Serves Prometheus metrics at /metrics/{module_name} (one path per source)</li><li>Auto-discovers metric “modules” at startup using Python’s importlib</li><li>Provides per-module TTL caching so Prometheus scrapes don’t hammer upstream APIs</li><li>Ships with 3 sample modules demonstrating 3 different metric patterns</li></ul><p>The architecture looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cILmX89mRJKahHqLC9tDCQ.png" /></figure><p>A request to GET /metrics/system_stats hits FastAPI, which looks up the system_stats module, calls its data collection method (with caching), and returns Prometheus-formatted text.</p><h3>The Core Idea: BaseModule</h3><p>The entire framework rests on one abstract class. Every module inherits from it and implements exactly two methods:</p><pre>from abc import ABC, abstractmethod</pre><pre>class BaseModule(ABC):<br>    def __init__(self, config):<br>        self.enabled = config.get(&quot;enabled&quot;, True)<br>        self.cache_ttl = config.get(&quot;cache_ttl&quot;, 300)<br>        self.timeout = config.get(&quot;timeout&quot;, 30)<br>        self._cached_metrics = None<br>        self._cache_timestamp = None<br>    @classmethod<br>    @abstractmethod<br>    def module_name(cls) -&gt; str:<br>        &quot;&quot;&quot;Unique identifier - becomes the URL path segment.&quot;&quot;&quot;<br>        ...<br>    @abstractmethod<br>    async def collect_data(self) -&gt; dict:<br>        &quot;&quot;&quot;Fetch raw data from the source. Raise DataCollectionError on failure.&quot;&quot;&quot;<br>        ...<br>    @abstractmethod<br>    def format_metrics(self, data: dict) -&gt; str:<br>        &quot;&quot;&quot;Convert raw data to Prometheus text exposition format.&quot;&quot;&quot;<br>        ...</pre><p>Notice two deliberate design choices here:</p><p><strong>collect_data() is async, </strong><strong>format_metrics() is sync.</strong> Data collection typically involves I/O — HTTP calls to APIs, database queries, file reads. Making it async lets multiple scrape requests be handled concurrently without blocking. Formatting, on the other hand, is pure CPU work on an in-memory dict. Adding async to it would just add overhead for no benefit.</p><p><strong>module_name() is a </strong><strong>@classmethod, not an instance method.</strong> The module loader needs to know the name <em>before</em> creating an instance — it uses the name to look up per-module config. A regular method would require instantiation first, creating a chicken-and-egg problem.</p><h3>The Smart Caching Layer</h3><p>This is the part I’m most proud of in the design.</p><p>Prometheus scrapes endpoints on a fixed interval — typically every 15 to 60 seconds. If you have 3 Prometheus replicas scraping every 15 seconds, that’s 12 requests per minute hitting your data source. For something like the GitHub API with strict rate limits, that’s a problem.</p><p>The caching logic lives in BaseModule.get_metrics() — a concrete method that modules <strong>cannot override</strong>:</p><pre>async def get_metrics(self, use_cache=True):<br>    if use_cache and self._is_cache_valid():<br>        return self._cached_metrics          # instant, no I/O</pre><pre>data = await self.collect_data()          # the expensive part<br>    metrics = self.format_metrics(data)       # CPU-only<br>    self._cached_metrics = metrics<br>    self._cache_timestamp = time.time()<br>    return metrics<br>def _is_cache_valid(self):<br>    if self._cached_metrics is None:<br>        return False<br>    return (time.time() - self._cache_timestamp) &lt; self.cache_ttl</pre><p>There are five things I like about this approach:</p><p><strong>1. Cache TTL is per-module, set via config.</strong></p><pre>modules:<br>  github_rate_limit:<br>    cache_ttl: 60      # rate limits reset hourly, 60s is plenty<br>  system_stats:<br>    cache_ttl: 15      # CPU/memory changes fast<br>  http_health:<br>    cache_ttl: 30      # health checks are cheap but not free</pre><p>Each data source has different freshness requirements. A GitHub rate limit doesn’t change every second. CPU usage does. Per-module TTL lets you tune that trade-off without writing any caching code.</p><p><strong>2. It caches the formatted string, not the raw data.</strong></p><p>A cache hit skips <em>both</em> the I/O call <em>and</em> the formatting step. The response is just returning a pre-built string — effectively O(1).</p><p><strong>3. Module authors literally cannot forget to add caching.</strong></p><p>get_metrics() is a concrete method in the base class. Module authors implement collect_data() and format_metrics(). They never touch the caching logic. You can&#39;t ship an uncached module even if you try.</p><p><strong>4. There’s a bypass for debugging.</strong></p><pre># Normal request (uses cache)<br>curl http://localhost:9099/metrics/github_rate_limit</pre><pre># Force a fresh collection<br>curl &quot;http://localhost:9099/metrics/github_rate_limit?nocache=true&quot;<br># Nuke the cache entirely<br>curl -X POST &quot;http://localhost:9099/cache/clear?module_name=github_rate_limit&quot;</pre><p><strong>5. The health endpoint exposes cache state.</strong></p><pre>{<br>  &quot;modules&quot;: {<br>    &quot;system_stats&quot;: {<br>      &quot;cache_ttl&quot;: 15,<br>      &quot;cache_age&quot;: 8.2,<br>      &quot;cache_valid&quot;: true<br>    }<br>  }<br>}</pre><p>You can see at a glance whether a module is serving fresh or stale data, which is the first thing you check when debugging metric gaps in Grafana.</p><h3>Plugin Discovery: How Modules Get Loaded</h3><p>This is the extensibility engine. The framework never imports module code directly. Instead, ModuleLoader walks the src/modules/ directory at startup and loads whatever it finds:</p><pre>import importlib, inspect, os</pre><pre>class ModuleLoader:<br>    def discover_modules(self, modules_dir):<br>        discovered = {}<br>        for folder in os.listdir(modules_dir):<br>            collector_path = os.path.join(modules_dir, folder, &quot;collector.py&quot;)<br>            if not os.path.isfile(collector_path):<br>                continue<br>            mod = importlib.import_module(f&quot;src.modules.{folder}.collector&quot;)<br>            for _, cls in inspect.getmembers(mod, inspect.isclass):<br>                if issubclass(cls, BaseModule) and cls is not BaseModule:<br>                    discovered[cls.module_name()] = cls<br>        return discovered</pre><p>The key insight: main.py has zero knowledge of which modules exist. module_loader.py has zero knowledge of what modules <em>do</em>. This means:</p><ul><li>Adding a module = create a folder + restart. No existing file is touched.</li><li>Removing a module = delete the folder + restart.</li><li>A broken module logs an error at startup but <strong>does not crash the exporter</strong>.</li></ul><p>This last point matters in production. If someone deploys a module with a syntax error, it shouldn’t take down the 4 other modules that are working fine.</p><h3>Three Modules, Three Patterns</h3><p>I deliberately chose three different approaches to Prometheus metric formatting across the sample modules. In production, you’ll encounter all three, and each has trade-offs worth understanding.</p><h3>Pattern 1: Custom CollectorRegistry (github_rate_limit)</h3><pre>from prometheus_client import CollectorRegistry, Gauge</pre><pre>registry = CollectorRegistry()<br>github_rate_limit_remaining = Gauge(<br>    &#39;github_rate_limit_remaining&#39;,<br>    &#39;Requests remaining in current window&#39;,<br>    [&#39;resource&#39;],<br>    registry=registry,<br>)<br># In format_metrics():<br>return generate_latest(registry).decode(&quot;utf-8&quot;)</pre><p><strong>When to use:</strong> When multiple teams develop modules independently. Custom registries guarantee zero metric name collisions.</p><p><strong>Trade-off:</strong> More boilerplate. You have to pass registry=registry to every metric and generate_latest(registry) instead of just generate_latest().</p><h3>Pattern 2: Manual String Formatting (system_stats)</h3><pre># No prometheus_client at all<br>def format_metrics(self, data):<br>    lines = [<br>        &quot;# HELP system_cpu_usage_percent Current CPU usage&quot;,<br>        &quot;# TYPE system_cpu_usage_percent gauge&quot;,<br>        f&quot;system_cpu_usage_percent {data[&#39;cpu&#39;][&#39;percent&#39;]}&quot;,<br>    ]<br>    return &quot;\n&quot;.join(lines) + &quot;\n&quot;</pre><p><strong>When to use:</strong> When you want full control, zero library dependency, and a pure function (dict in, string out). Great for debugging because there’s no hidden state.</p><p><strong>Trade-off:</strong> You’re responsible for getting the Prometheus text format exactly right — the # HELP and # TYPE comments, the label escaping, the trailing newline.</p><h3>Pattern 3: Global Registry (http_health)</h3><pre>from prometheus_client import Gauge</pre><pre>http_endpoint_up = Gauge(<br>    &#39;http_endpoint_up&#39;,<br>    &#39;Endpoint reachable (1=up, 0=down)&#39;,<br>    [&#39;endpoint_name&#39;, &#39;url&#39;],<br>)<br># In format_metrics():<br>return generate_latest().decode(&quot;utf-8&quot;)</pre><p><strong>When to use:</strong> Small teams, solo projects, or when you’re sure metric names are unique.</p><p><strong>Trade-off (and gotcha):</strong> generate_latest() with no argument dumps the <em>entire</em> global registry. If another module also uses the global registry, its metrics will leak into your output. In production, I&#39;ve seen this cause confusing duplicate metrics in Grafana.</p><h3>Adding a New Module: A 5-Minute Walkthrough</h3><p>Let’s say you want to monitor Redis. Here’s every step.</p><p><strong>Step 1: Create the directory.</strong></p><pre>mkdir -p src/modules/redis_stats<br>touch src/modules/redis_stats/__init__.py</pre><p><strong>Step 2: Write the collector.</strong></p><pre># src/modules/redis_stats/collector.py<br>import redis<br>from src.core.base_module import BaseModule<br>from src.core.exceptions import DataCollectionError, MetricFormattingError</pre><pre>class RedisStatsCollector(BaseModule):<br>    @classmethod<br>    def module_name(cls):<br>        return &quot;redis_stats&quot;<br>    def __init__(self, config):<br>        super().__init__(config)<br>        self.redis_url = config.get(&quot;redis_url&quot;, &quot;redis://localhost:6379&quot;)<br>    async def collect_data(self):<br>        try:<br>            r = redis.from_url(https://medium.com/self.redis_url)<br>            info = r.info(&quot;clients&quot;)<br>            return {<br>                &quot;connected&quot;: info[&quot;connected_clients&quot;],<br>                &quot;blocked&quot;: info[&quot;blocked_clients&quot;],<br>            }<br>        except Exception as e:<br>            raise DataCollectionError(f&quot;Redis unreachable: {e}&quot;)<br>    def format_metrics(self, data):<br>        try:<br>            return (<br>                &quot;# HELP redis_connected_clients Connected Redis clients\n&quot;<br>                &quot;# TYPE redis_connected_clients gauge\n&quot;<br>                f&quot;redis_connected_clients {data[&#39;connected&#39;]}\n&quot;<br>                &quot;# HELP redis_blocked_clients Blocked Redis clients\n&quot;<br>                &quot;# TYPE redis_blocked_clients gauge\n&quot;<br>                f&quot;redis_blocked_clients {data[&#39;blocked&#39;]}\n&quot;<br>            )<br>        except Exception as e:<br>            raise MetricFormattingError(f&quot;Format failed: {e}&quot;)</pre><p><strong>Step 3: Add config (optional).</strong></p><pre># config/exporter_config.yaml<br>modules:<br>  redis_stats:<br>    enabled: true<br>    cache_ttl: 10<br>    redis_url: &quot;redis://localhost:6379&quot;</pre><p><strong>Step 4: Restart and test.</strong></p><pre>curl http://localhost:9099/metrics/redis_stats</pre><p>That’s it. You created two files. You touched zero existing code. The module loader discovered your class at startup, the config loader injected your settings, and the base class gave you TTL caching, health reporting, and error handling for free.</p><h3>The FastAPI Layer</h3><p>The HTTP layer is intentionally thin. FastAPI handles routing, and exception handlers map typed errors to HTTP status codes:</p><pre>@app.get(&quot;/metrics/{module_name}&quot;)<br>async def get_metrics(module_name: str, nocache: bool = False):<br>    if module_name not in modules:<br>        raise ModuleNotFoundError(f&quot;Module &#39;{module_name}&#39; not found&quot;)<br>    mod = modules[module_name]<br>    if not mod.enabled:<br>        raise ModuleDisabledError(f&quot;Module &#39;{module_name}&#39; is disabled&quot;)<br>    metrics = await mod.get_metrics(use_cache=not nocache)<br>    return Response(content=metrics, media_type=&quot;text/plain; version=0.0.4&quot;)</pre><p>The exception hierarchy maps cleanly to HTTP semantics:</p><p>ExceptionHTTP StatusMeaningModuleNotFoundError404Bad URL — no such moduleModuleDisabledError503Module exists but turned offDataCollectionError503Upstream is downMetricFormattingError500Bug in module code</p><p>Why FastAPI over Flask? Three reasons:</p><ol><li><strong>Native async</strong> — collectors do async HTTP calls (httpx.AsyncClient). Flask would need threading or gevent.</li><li><strong>Auto-generated OpenAPI docs</strong> — hit /docs and you get a full interactive API reference for free.</li><li><strong>Pydantic integration</strong> — config validation and request parsing use the same library.</li></ol><h3>Running the Full Stack</h3><p>The project includes a docker-compose.yml that spins up the exporter alongside Prometheus and Grafana:</p><pre>docker-compose up --build</pre><ul><li>ServiceURLExporter: <a href="http://localhost:9099/">http://localhost:9099</a></li><li>Prometheus: <a href="http://localhost:9091/">http://localhost:9091</a></li><li>Grafana: <a href="http://localhost:3000/">http://localhost:3000</a> (admin/admin)</li></ul><p>Prometheus is pre-configured to scrape each module at an appropriate interval — 15s for system stats, 30s for health checks, 60s for GitHub rate limits. Open Grafana, add Prometheus as a data source, and you can immediately build dashboards on top of any module’s metrics.</p><h3>What I’d Add in Production</h3><p>This framework is intentionally kept clean for learning and extensibility. In a real production deployment, I’d layer on:</p><ul><li><strong>Async locking on cache miss</strong> — right now, if 3 requests hit a cache miss simultaneously, all 3 call collect_data(). A simple asyncio.Lock per module would ensure only one does the work while others wait.</li><li><strong>Metric for the exporter itself</strong> — collection duration, cache hit/miss ratio, error counts per module. Eating your own dog food.</li><li><strong>Graceful degradation</strong> — if collect_data() fails, optionally serve stale cache with a stale=true label instead of returning 503.</li><li><strong>Module hot-reloading</strong> — watch the modules/ directory for changes and reload without restarting the process. watchdog library makes this straightforward.</li><li><strong>Authentication</strong> — API key or mTLS for production endpoints, especially if the exporter serves internal-only metrics.</li></ul><h3>Key Takeaways</h3><ol><li><strong>Plugin architectures separate concerns.</strong> The framework handles HTTP, caching, and discovery. Modules handle data collection. Neither knows about the other.</li><li><strong>Cache at the framework level, not the module level.</strong> If caching is optional, someone will forget it. If it’s in the base class, everyone gets it.</li><li><strong>importlib + </strong><strong>inspect is Python&#39;s underrated plugin system.</strong> No entry points, no registry files, no decorators. Just &quot;does this directory contain a collector.py with a BaseModule subclass?&quot; Simple and robust.</li><li><strong>Three metric formatting patterns exist for a reason.</strong> Custom registries for isolation, global registries for simplicity, manual strings for control. Know the trade-offs and pick based on your team’s structure.</li><li><strong>Design your exceptions around your HTTP API.</strong> If you know your framework serves HTTP, design your exception hierarchy to map cleanly to status codes. It makes error handling declarative instead of imperative.</li></ol><p><em>The complete source code, including the Dockerfile, test suite, and docker-compose stack, is available on </em><a href="https://github.com/thinkingmonster/prometheus-exporter"><em>GitHub</em></a><em>. If you build your own module on top of this framework, I’d love to hear about it.</em></p><p><em>Akashdeep Thakur is a Staff SRE with 15+ years of experience building observability and infrastructure platforms at scale.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68d85032d372" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Operator in Python]]></title>
            <link>https://medium.com/@akash94thakur/kubernetes-operator-in-python-6e986b0aabd3?source=rss-36df1949e96a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e986b0aabd3</guid>
            <category><![CDATA[python-operator]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kubernetes-operator]]></category>
            <dc:creator><![CDATA[Thinking monster]]></dc:creator>
            <pubDate>Sat, 08 Jun 2024 16:22:56 GMT</pubDate>
            <atom:updated>2024-06-08T16:34:02.453Z</atom:updated>
            <content:encoded><![CDATA[<p>This <a href="https://github.com/thinkingmonster/kubernetes/tree/master/operators"><strong><em>project</em></strong></a> demonstrates how to create a Kubernetes operator in Python using the <a href="https://kopf.readthedocs.io/en/stable/">kopf</a> library. The operator listens for the creation of custom resources of kind MyResource and performs specific actions (creating a Kubernetes Deployment).</p><h3>Prerequisites</h3><ul><li>Python 3.6+</li><li>Kubernetes cluster</li><li>kubectl configured to access your cluster</li><li>Docker (for building and pushing the operator image)</li></ul><h3>Setup</h3><h3>1. Create a Virtual Environment</h3><p>Set up a virtual environment for your project:</p><pre>python3 -m venv venv<br>source venv/bin/activate<br>pip install --upgrade pip</pre><h3>2. Install Required Libraries</h3><p>Install kopf and the Kubernetes client library:</p><pre>pip install kopf kubernetes</pre><h3>3. Create the Operator Code</h3><p>Create a new Python file named my_operator.py and add the following code:</p><pre>import kopf<br>import kubernetes.client<br>from kubernetes.client.rest import ApiException</pre><pre>@kopf.on.create(&#39;example.com&#39;, &#39;v1&#39;, &#39;myresources&#39;)<br>def create_fn(spec, name, namespace, logger, **kwargs):<br>    logger.info(f&quot;Handling create event for MyResource: {name} in namespace: {namespace}&quot;)<br>    <br>    api = kubernetes.client.AppsV1Api()<br>    deployment = kubernetes.client.V1Deployment(<br>        api_version=&quot;apps/v1&quot;,<br>        kind=&quot;Deployment&quot;,<br>        metadata=kubernetes.client.V1ObjectMeta(name=name),<br>        spec=kubernetes.client.V1DeploymentSpec(<br>            replicas=1,<br>            selector=kubernetes.client.V1LabelSelector(<br>                match_labels={&quot;app&quot;: name}<br>            ),<br>            template=kubernetes.client.V1PodTemplateSpec(<br>                metadata=kubernetes.client.V1ObjectMeta(labels={&quot;app&quot;: name}),<br>                spec=kubernetes.client.V1PodSpec(<br>                    containers=[kubernetes.client.V1Container(<br>                        name=name,<br>                        image=spec.get(&#39;image&#39;, &#39;nginx&#39;)<br>                    )]<br>                )<br>            )<br>        )<br>    )<br>    try:<br>        api.create_namespaced_deployment(namespace=namespace, body=deployment)<br>        logger.info(f&quot;Deployment {name} created&quot;)<br>    except ApiException as e:<br>        logger.error(f&quot;Exception when creating deployment: {e}&quot;)</pre><h3>4. Define the Custom Resource Definition (CRD)</h3><p>Create a file named myresource-crd.yaml with the following content:</p><pre>apiVersion: apiextensions.k8s.io/v1<br>kind: CustomResourceDefinition<br>metadata:<br>  name: myresources.example.com<br>spec:<br>  group: example.com<br>  versions:<br>    - name: v1<br>      served: true<br>      storage: true<br>      schema:<br>        openAPIV3Schema:<br>          type: object<br>          properties:<br>            spec:<br>              type: object<br>              properties:<br>                image:<br>                  type: string<br>  scope: Namespaced<br>  names:<br>    plural: myresources<br>    singular: myresource<br>    kind: MyResource<br>    shortNames:<br>    - mr</pre><p>Apply the CRD to your Kubernetes cluster:</p><pre>kubectl apply -f myresource-crd.yaml</pre><h3>5. Run the Operator Locally</h3><p>Run the operator locally to test it:</p><pre>kopf run my_operator.py</pre><h3>6. Create a Custom Resource</h3><p>Create a custom resource YAML file named myresource.yaml:</p><pre>apiVersion: example.com/v1<br>kind: MyResource<br>metadata:<br>  name: my-app<br>spec:<br>  image: nginx:latest</pre><p>Apply the custom resource to your cluster:</p><pre>kubectl apply -f myresource.yaml</pre><h3>7. Verify the Deployment</h3><p>Check if the deployment has been created:</p><pre>kubectl get deployments</pre><p>Inspect the deployment details:</p><pre>kubectl describe deployment my-app</pre><h3>8. Deploy the Operator in Kubernetes</h3><p>Create a Dockerfile for the operator:</p><pre>FROM python:3.8-slim<br>COPY . /app<br>WORKDIR /app<br>RUN pip install --no-cache-dir kopf kubernetes<br>CMD [&quot;kopf&quot;, &quot;run&quot;, &quot;/app/my_operator.py&quot;]</pre><p>Build and push the Docker image:</p><pre>docker build -t thinkingmonster/my-operator:latest .<br>docker push thinkingmonster/my-operator:latest</pre><pre>docker build -t your-dockerhub-username/my-operator:latest .<br>docker push your-dockerhub-username/my-operator:latest</pre><h3>9. Create ServiceAccount, ClusterRole, and ClusterRoleBinding</h3><p>Create a file named operator-serviceaccount.yaml with the following content:</p><pre>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: my-operator<br>  namespace: default</pre><h4>Role</h4><p>Create a file named operator-role.yaml with the following content:</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRole<br>metadata:<br>  namespace: default<br>  name: my-operator<br>rules:<br>- apiGroups: [&quot;&quot;]<br>  resources: [&quot;pods&quot;, &quot;services&quot;, &quot;endpoints&quot;, &quot;persistentvolumeclaims&quot;]<br>  verbs: [&quot;get&quot;, &quot;list&quot;, &quot;watch&quot;, &quot;create&quot;, &quot;delete&quot;, &quot;patch&quot;, &quot;update&quot;]<br>- apiGroups: [&quot;apps&quot;]<br>  resources: [&quot;deployments&quot;, &quot;replicasets&quot;]<br>  verbs: [&quot;get&quot;, &quot;list&quot;, &quot;watch&quot;, &quot;create&quot;, &quot;delete&quot;, &quot;patch&quot;, &quot;update&quot;]<br>- apiGroups: [&quot;example.com&quot;]<br>  resources: [&quot;myresources&quot;]<br>  verbs: [&quot;get&quot;, &quot;list&quot;, &quot;watch&quot;, &quot;create&quot;, &quot;delete&quot;, &quot;patch&quot;, &quot;update&quot;]</pre><h4>RoleBinding</h4><p>Create a file named operator-rolebinding.yaml with the following content:</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRoleBinding<br>metadata:<br>  name: my-operator<br>  namespace: default<br>roleRef:<br>  apiGroup: rbac.authorization.k8s.io<br>  kind: ClusterRole<br>  name: my-operator<br>subjects:<br>- kind: ServiceAccount<br>  name: my-operator<br>  namespace: default</pre><h3>10. Kubernetes Deployment</h3><p>Create a deployment YAML file named operator-deployment.yaml:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: my-operator<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: my-operator<br>  template:<br>    metadata:<br>      labels:<br>        app: my-operator<br>    spec:<br>      serviceAccountName: my-operator<br>      containers:<br>        - name: my-operator<br>          image: thinkingmonster/my-operator:latest<br>          imagePullPolicy: Always</pre><p>Deploy the operator to Kubernetes:</p><pre>kubectl apply -f operator-deployment.yaml</pre><p>If done properly you would see following logs inside operator container</p><pre>akashthakur@Akashs-Mac-Studio  ~/Documents/code/kubernetes/operators   master ● ? ↑1  k logs my-operator-885664c76-dgpv4                                                                        ✔  1749  21:45:22<br>/usr/local/lib/python3.8/site-packages/kopf/_core/reactor/running.py:179: FutureWarning: Absence of either namespaces or cluster-wide flag will become an error soon. For now, switching to the cluster-wide mode for backward compatibility.<br>  warnings.warn(&quot;Absence of either namespaces or cluster-wide flag will become an error soon.&quot;<br>[2024-06-08 16:15:15,117] kopf._core.engines.a [INFO    ] Initial authentication has been initiated.<br>[2024-06-08 16:15:15,118] kopf.activities.auth [INFO    ] Activity &#39;login_via_client&#39; succeeded.<br>[2024-06-08 16:15:15,118] kopf._core.engines.a [INFO    ] Initial authentication has finished.<br>[2024-06-08 16:15:15,127] kopf._core.reactor.o [WARNING ] Not enough permissions to watch for resources: changes (creation/deletion/updates) will not be noticed; the resources are only refreshed on operator restarts.<br> akashthakur@Akashs-Mac-Studio  ~/Documents/code/kubernetes/operators   master ● ? ↑1 </pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e986b0aabd3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building first application in Go]]></title>
            <link>https://medium.com/@akash94thakur/building-first-application-in-go-829d879a5430?source=rss-36df1949e96a------2</link>
            <guid isPermaLink="false">https://medium.com/p/829d879a5430</guid>
            <dc:creator><![CDATA[Thinking monster]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 09:34:12 GMT</pubDate>
            <atom:updated>2023-01-29T09:34:12.656Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building the first application in Go</h3><p>Checking medium</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=829d879a5430" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>