<?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 Kaustav Chaudhury on Medium]]></title>
        <description><![CDATA[Stories by Kaustav Chaudhury on Medium]]></description>
        <link>https://medium.com/@chaudhuryk89?source=rss-f9f6ec1592d6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mv0G1vzedRBvEQhYg0nyqw.jpeg</url>
            <title>Stories by Kaustav Chaudhury on Medium</title>
            <link>https://medium.com/@chaudhuryk89?source=rss-f9f6ec1592d6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:08:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chaudhuryk89/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[Tracking London’s Pulse: A Real-Time TfL Map with Apache Flink, PostGIS & Grafana]]></title>
            <link>https://medium.com/@chaudhuryk89/tracking-londons-pulse-a-real-time-tfl-map-with-apache-flink-postgis-grafana-2aa0c65e714c?source=rss-f9f6ec1592d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2aa0c65e714c</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[postgis]]></category>
            <category><![CDATA[apache-flink]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Kaustav Chaudhury]]></dc:creator>
            <pubDate>Wed, 13 May 2026 02:05:17 GMT</pubDate>
            <atom:updated>2026-05-13T02:20:18.315Z</atom:updated>
            <content:encoded><![CDATA[<p>London’s red buses are iconic, but their digital footprints are often a game of “now you see me, now you don’t.” While the <strong>TfL Unified API</strong> provides precise arrival predictions, the actual live coordinates of the vehicles are often hidden between the lines of data — and needs a stack that handles <strong>spatial-temporal data</strong> without breaking a sweat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TLGaZdRdPqiSAUtDb0PxPw.jpeg" /></figure><h3>The Stack</h3><p><a href="https://github.com/chaudhuryk89/london_transport_unified_grafana">End-to-end pipeline</a> that ingests every London bus stop’s arrival predictions from the <strong>TfL</strong> <strong>Unified API</strong>, interpolates “<em>ghost</em>” vehicle positions between stops, persists them in DB, and visualizes the live fleet — <strong>Apache Flink, PostGIS, and Grafana — all on docker.</strong> <a href="https://github.com/chaudhuryk89/london_transport_unified_grafana">Everything runs as a Docker Compose stack</a>.</p><ul><li><strong>Stream Processor:</strong> Apache Flink 1.18.1 (Java 11)</li><li><strong>Storage:</strong> PostgreSQL 16 + PostGIS 3.4</li><li><strong>Visualization:</strong> Grafana 11 (Geomap Panel)</li><li><strong>Source:</strong> A Python-based TCP “tick” service triggering polls every 30 seconds.</li></ul><pre>                         +------------------+<br>                         |   tick-feed      |  python TCP :9999, &quot;tick\n&quot; every 30s<br>                         +---------+--------+<br>                                   |<br>                                   v<br>+-----------+    +-----------+    +------------------+    +-------------+<br>| postgres  |&lt;--&gt;| jobmanager|&lt;--&gt;| taskmanager (x1) |---&gt;| postgres    |<br>| (postgis) |    | (Flink)   |    |  Flink workers   |    |  bus_positions<br>+-----------+    +-----+-----+    +------------------+    +-------------+<br>       ^               |<br>       |               v<br>       |         +-----+------+<br>       |         | submit-job | runs `flink run -c TflBusStreamingJob`<br>       |         +------------+<br>       |<br>       |       +-----------+<br>       +-----&gt; |  grafana  | provisioned PostGIS datasource + TfL dashboard<br>               +-----------+</pre><p>Start by registering an account at <a href="https://api-portal.tfl.gov.uk/">https://api-portal.tfl.gov.uk/</a> and generate your own key. We will have to create a <strong>Subscription first to generate key </strong>for our API requests which allows 500 requests/min. Now, before we can track a bus, we have to know where it’s going. The pipeline begins with <strong>HubSync</strong>. It pages through the TfL canonical endpoint (/StopPoint/Mode/bus), ingesting only major 52 hub stations for our initial test. We will later scale up the sync for all possible stops to evaluate Flink’s compute power.</p><h3>Phase 1: The Flink Streaming Job</h3><p>Using a 30-second tick as a trigger, the PollArrivalsFlatMap executes concurrent /Arrivals calls. With a parallelism of 48, we hit a throughput of ~633 RPS. This allows us to sweep the entire city&#39;s arrival predictions within our 30-second budget without exceeding TfL rate limits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*va5ICdcrlY31dPxUdYheug.gif" /></figure><p>We initialize our postGIS DB with appropriate schema and index to prepare for geo attributes:</p><pre>CREATE TABLE IF NOT EXISTS hub_stops (<br>    naptan_id       TEXT PRIMARY KEY,<br>    common_name     TEXT,<br>    stop_type       TEXT,<br>    lat             DOUBLE PRECISION NOT NULL,<br>    lon             DOUBLE PRECISION NOT NULL,<br>    hub_naptan_code TEXT,<br>    updated_at      TIMESTAMPTZ NOT NULL DEFAULT now()<br>);<br><br>CREATE INDEX IF NOT EXISTS idx_hub_stops_stop_type ON hub_stops (stop_type);<br><br>CREATE TABLE IF NOT EXISTS bus_positions (<br>    time                 TIMESTAMPTZ NOT NULL DEFAULT now(),<br>    vehicle_id           TEXT NOT NULL,<br>    route                TEXT NOT NULL,<br>    location             geometry(Point, 4326) NOT NULL,<br>    bearing              REAL,<br>    next_naptan_id       TEXT,<br>    prev_naptan_id       TEXT,<br>    raw_time_to_station  INTEGER,<br>    ghost_fraction       REAL<br>);<br><br>CREATE INDEX IF NOT EXISTS idx_bus_positions_time ON bus_positions (time DESC);<br>CREATE INDEX IF NOT EXISTS idx_bus_positions_vehicle_time ON bus_positions (vehicle_id, time DESC);<br>CREATE INDEX IF NOT EXISTS idx_bus_positions_location ON bus_positions USING GIST (location);</pre><h3>Phase 2: The Ghost in the Machine (Stateful Interpolation)</h3><p>This is where it gets technical. Using Flink’s KeyedProcessFunction (GhostEnrichFunction), we track each vehicle_id.</p><ul><li><strong>State:</strong> We store the previous stop, the next stop, and the time of the last update.</li><li><strong>Interpolation:</strong> We calculate a “Linear Relationship” (lerp) between two points. If a bus is 60 seconds away from a stop on a 300-second leg, Flink calculates its likely spatial coordinate in real-time.</li></ul><h3>The Spatial Sink</h3><p>The enriched BusPosition POJOs are sent to a PostgisSink. Instead of raw strings, we use ST_MakePoint to transform coordinates into active geometry, indexed via <strong>GIST</strong> for lightning-fast spatial queries. In terms of <strong>Idempotency</strong>: hub_stops upsert uses ON CONFLICT (naptan_id) DO UPDATE, so re-running the sync is safe.</p><h3>Phase 3: Visualizing the Fleet</h3><p>In Grafana, we use the <strong>Geomap</strong> panel. By running a DISTINCT ON (vehicle_id) query against our PostGIS table, we pull the most recent &quot;interpolated&quot; position for every bus in the city.</p><blockquote><strong><em>Pro Tip:</em></strong><em> We set the Grafana refresh rate to 10s and the time window to the last 15 minutes to keep the map fluid and responsive.</em></blockquote><blockquote><em>Accessible via </em>UI: http://localhost:3000 (admin/admin)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFIyaymsMz-cf1PHfziKOA.gif" /><figcaption>Grafana vehicle live location tracker</figcaption></figure><p>Just for fun, I later included all possible bus stop locations — and of course Flink and Grafana was easily able to populate them without a hiccup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Qj72Mu84aL0vFh9ZNWbBQ.gif" /><figcaption>All vehicle locations</figcaption></figure><h3>Summary</h3><p>By combining the stateful processing power of <strong>Apache Flink</strong> with the spatial intelligence of <strong>PostGIS + Grafana</strong>, we’ve turned a simple arrival API into a living, breathing digital twin of London’s bus network.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2aa0c65e714c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pipes, Routes and Processors: Apache Camel vs Apache NiFi]]></title>
            <link>https://medium.com/@chaudhuryk89/pipes-routes-and-processors-apache-camel-vs-apache-nifi-d6918d8debf2?source=rss-f9f6ec1592d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6918d8debf2</guid>
            <category><![CDATA[apache-camel]]></category>
            <category><![CDATA[open-source-software]]></category>
            <category><![CDATA[apache-nifi]]></category>
            <category><![CDATA[enterprise-integration]]></category>
            <category><![CDATA[apache]]></category>
            <dc:creator><![CDATA[Kaustav Chaudhury]]></dc:creator>
            <pubDate>Tue, 21 Apr 2026 00:28:42 GMT</pubDate>
            <atom:updated>2026-04-21T00:28:42.143Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8cQktcmPqOl2DY6gwIgWnA.jpeg" /></figure><h3>What is Apache Camel?</h3><p>Apache Camel is an open-source integration framework that turns the classic <a href="https://www.enterpriseintegrationpatterns.com/"><strong>Enterprise Integration Patterns</strong></a> (EIP) book into runnable code. Where other frameworks give you a toolbox of generic plumbing, Camel gives you a vocabulary — from(...), to(...), split(), aggregate(), filter(), choice(), enrich() — that reads almost like the diagrams in <strong>Hohpe </strong>and <strong>Woolf&#39;s </strong>textbook.</p><p>Under the hood, Camel is a routing engine. You declare a <em>route</em>: where messages come from, what happens to them in the middle, and where they go next. Each route is stitched together from two kinds of parts:</p><ol><li>Components — 350+ adapters for talking to the outside world: <em>files, Kafka, HTTP, JDBC, SFTP, S3, MQTT, gRPC, Salesforce, Kubernetes,</em> and so on. A component exposes endpoints you reference by URI, e.g. file:/data/input?move=.done.</li><li>Processors and EIPs — the in-memory logic that transforms, splits, aggregates, routes, retries, throttles, and otherwise manipulates the messages flowing between endpoints.</li></ol><p>Crucially, Camel is a <strong>library</strong>, <strong><em>not a server</em></strong>. It runs <strong><em>inside</em> </strong>your application — typically a Spring Boot or Quarkus service — so the <strong>integration logic lives in the same repo</strong>, the same build pipeline, and the same container as the rest of your code. You version it in git, unit-test it, and ship it like any other module.</p><p>That “integration-as-code” posture is what separates Camel from the other big name in the Apache dataflow world: <em>Apache NiFi</em>.</p><h3>Apache NiFi: “Flow-Based” Routing</h3><p>In NiFi, routing is <strong>visual and explicit</strong>. You draw “connections” between processors on a web-based canvas.</p><ul><li><strong>Relationship-Based:</strong> Every processor has defined “Relationships” (e.g., success, failure, unmatched). You physically drag an arrow from one processor to another to decide where data goes based on those outcomes.</li><li><strong>Dynamic Prioritization:</strong> NiFi allows you to configure load balancing and prioritization directly on the connection (the “wire”) between processors.</li><li><strong>Content-Based Routing:</strong> Typically handled by specific processors like RouteOnAttribute or RouteOnContent, where you define rules (using NiFi Expression Language) to send data to different output ports.</li></ul><h3>Apache Camel: “Pattern-Based” Routing</h3><p>Camel is a code-first framework based on <strong>Enterprise Integration Patterns (EIP)</strong>. You define routes using a Domain Specific Language (DSL) in Java, XML, or YAML.</p><ul><li><strong>EIP-Centric:</strong> Routing is built around established patterns like <em>Content-Based Router</em>, <em>Splitter</em>, <em>Aggregator</em>, or <em>Recipient List</em>.</li><li><strong>Logic-Heavy:</strong> Because it’s code, routing can be incredibly complex and embedded within the application logic.</li><li><strong>Non-Visual:</strong> While there are some designers (like Karavan), the “source of truth” is the code. You don’t “see” the data moving through the pipes in real-time like you do in NiFi.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*BC-TVVXSyf1uVCX5Nbkq7g.png" /><figcaption>Comparison</figcaption></figure><h3>The Test : A Thin Slice of Camel</h3><p>Ok, so how does one try out what camel can do? Easy. To put Camel through its paces, we built a minimal but realistic “<a href="https://github.com/chaudhuryk89/camel_test"><strong>enterprise drop-folder</strong>” pipeline, fully containerized</a>. The scenario is one every integration developer has seen a hundred times: <em>a partner drops a CSV on a shared path; your system must ingest it, split it into individual records, translate each record to JSON, and hand it off downstream.</em></p><pre>CsvDataFormat csv = new CsvDataFormat();<br>csv.setUseMaps(true);        // first row becomes keys -&gt; List&lt;Map&lt;String,String&gt;&gt;<br>csv.setLazyLoad(true);       // stream rows for larger files<br><br>from(&quot;file:/data/input?move=.done&amp;moveFailed=.error&amp;delay=2000&amp;readLock=changed&quot;)<br>    .routeId(&quot;csv-to-json&quot;)<br>    .log(&quot;Picked up file ${header.CamelFileName}&quot;)<br>    .unmarshal(csv)                                 // Message Translator #1: CSV -&gt; List&lt;Map&gt;<br>    .split(body()).streaming()                      // Splitter: one exchange per row<br>        .marshal().json(JsonLibrary.Jackson)        // Message Translator #2: Map -&gt; JSON<br>        .log(&quot;Row ${exchangeProperty.CamelSplitIndex}: ${body}&quot;)<br>    .end()<br>    .log(&quot;Done with ${header.CamelFileName}&quot;);</pre><p>What this exercises:</p><ul><li>File consumer — polls /data/input every 2 seconds, uses readLock=changed so half-written files are not slurped mid-copy, and auto-archives to .done/ (or .error/ on failure).</li><li>Splitter EIP — .split(body()).streaming() turns the list of CSV rows into N individual in-flight messages, streamed rather than loaded whole.</li><li>Message Translator EIP, twice — first unmarshal(csv) with useMaps=true so the header row becomes keys (Customer Id, First Name, etc.); then marshal().json(Jackson) to emit one JSON object per row.</li><li>Containerization — a multi-stage Dockerfile compiles the jar inside the builder image and copies it onto a slim Temurin JRE; the docker-compose.yml bind-mounts the host’s ./data/input into the container, so CSVs you drop on Windows are picked up by the JVM inside Linux.</li></ul><pre>FROM maven:3.9-eclipse-temurin-17 AS build<br>WORKDIR /build<br>COPY pom.xml .<br>RUN mvn -q -e -B -DskipTests dependency:go-offline<br>COPY src ./src<br>RUN mvn -q -e -B -DskipTests package<br><br>FROM eclipse-temurin:17-jre<br>WORKDIR /app<br>COPY --from=build /build/target/*.jar /app/app.jar<br>RUN mkdir -p /data/input<br>VOLUME [&quot;/data/input&quot;]<br>ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;,&quot;/app/app.jar&quot;]</pre><p>The test fixture is <strong>data/input/customers-100.csv</strong> — 100 rows, 12 columns, with quoted fields containing embedded commas (a real-world CSV gotcha). A single docker compose up --build produces a hundred JSON-shaped log lines, proving the whole pipeline — poll, parse, split, translate, log — <strong>works end-to-end</strong>.</p><pre>services:<br>  camel:<br>    build: .<br>    container_name: camel-test<br>    volumes:<br>      - ./data/input:/data/input<br>    environment:<br>      - LOGGING_LEVEL_ORG_APACHE_CAMEL=INFO<br>    restart: unless-stopped</pre><p>That <a href="https://github.com/chaudhuryk89/camel_test">entire stack</a>, dependencies and all, is a jar on top of a JRE. No separate server to stand up, no UI to log into, no database to provision. That’s what <strong><em>“Camel-style”</em></strong> integration looks like.</p><pre>PS E:\camel_test&gt; docker compose up --build<br>...<br>#18 resolving provenance for metadata file<br>#18 DONE 0.0s<br>[+] up 3/3<br> ✔ Image camel_test-camel     Built                                                                                                                                                                                                                                                        143.6s<br> ✔ Network camel_test_default Created                                                                                                                                                                                                                                                      0.4s  <br> ✔ Container camel-test       Created                                                                                                                                                                                                                                                      3.6s<br>Attaching to camel-test<br>camel-test  |<br>camel-test  |   .   ____          _            __ _ _<br>camel-test  |  /\\ / ___&#39;_ __ _ _(_)_ __  __ _ \ \ \ \                                                                                                                                                                                                                                           <br>camel-test  | ( ( )\___ | &#39;_ | &#39;_| | &#39;_ \/ _` | \ \ \ \                                                                                                                                                                                                                                          <br>camel-test  |  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )                                                                                                                                                                                                                                         <br>camel-test  |   &#39;  |____| .__|_| |_|_| |_\__, | / / / /                                                                                                                                                                                                                                          <br>camel-test  |  =========|_|==============|___/=/_/_/_/<br>camel-test  |                                                                                                                                                                                                                                                                                    <br>camel-test  |  :: Spring Boot ::                (v3.3.5)                                                                                                                                                                                                                                         <br>camel-test  |                                                                                                                                                                                                                                                                                    <br>camel-test  | 23:52:25.487 INFO  [main] c.example.camel.CamelTestApplication - Starting CamelTestApplication v1.0.0 using Java 17.0.18 with PID 1 (/app/app.jar started by root in /app)<br>camel-test  | 23:52:25.489 INFO  [main] c.example.camel.CamelTestApplication - No active profile set, falling back to 1 default profile: &quot;default&quot;                                                                                                                                               <br>camel-test  | 23:52:26.900 INFO  [main] o.a.c.i.engine.AbstractCamelContext - Apache Camel 4.8.1 (camel-1) is starting                                                                                                                                                                           <br>camel-test  | 23:52:27.040 INFO  [main] o.a.c.s.b.CamelSpringBootApplicationListener - Starting CamelMainRunController to ensure the main thread keeps running<br>camel-test  | 23:52:27.041 INFO  [CamelMainRunController] org.apache.camel.main.MainSupport - Apache Camel (Main) 4.8.1 is starting<br>camel-test  | 23:52:27.047 INFO  [main] o.a.c.i.engine.AbstractCamelContext - Routes startup (total:1)                                                                                                                                                                                           <br>camel-test  | 23:52:27.047 INFO  [main] o.a.c.i.engine.AbstractCamelContext -     Started csv-to-json (file:///data/input)                                                                                                                                                                       <br>camel-test  | 23:52:27.047 INFO  [main] o.a.c.i.engine.AbstractCamelContext - Apache Camel 4.8.1 (camel-1) started in 145ms (build:0ms init:0ms start:145ms)<br>camel-test  | 23:52:27.055 INFO  [main] c.example.camel.CamelTestApplication - Started CamelTestApplication in 1.885 seconds (process running for 2.26)                                                                                                                                          <br>camel-test  | 23:52:29.070 INFO  [Camel (camel-1) thread #1 - file:///data/input] csv-to-json - Picked up file customers-100.csv                                                                                                                                                                 <br>camel-test  | 23:52:29.097 INFO  [Camel (camel-1) thread #1 - file:///data/input] csv-to-json - Row 0: {&quot;Index&quot;:&quot;1&quot;,&quot;Customer Id&quot;:&quot;DD37Cf93aecA6Dc&quot;,&quot;First Name&quot;:&quot;Sheryl&quot;,&quot;Last Name&quot;:&quot;Baxter&quot;,&quot;Company&quot;:&quot;Rasmussen Group&quot;,&quot;City&quot;:&quot;East Leonard&quot;,&quot;Country&quot;:&quot;Chile&quot;,&quot;Phone 1&quot;:&quot;229.077.5154&quot;,&quot;Phone 2&quot;:&quot;397.884.0519x718&quot;,&quot;Email&quot;:&quot;zunigavanessa@smith.info&quot;,&quot;Subscription Date&quot;:&quot;2020-08-24&quot;,&quot;Website&quot;:&quot;http://www.stephenson.com/&quot;}<br>camel-test  | 23:52:29.099 INFO  [Camel (camel-1) thread #1 - file:///data/input] csv-to-json - Row 1: {&quot;Index&quot;:&quot;2&quot;,&quot;Customer Id&quot;:&quot;1Ef7b82A4CAAD10&quot;,&quot;First Name&quot;:&quot;Preston&quot;,&quot;Last Name&quot;:&quot;Lozano&quot;,&quot;Company&quot;:&quot;Vega-Gentry&quot;,&quot;City&quot;:&quot;East Jimmychester&quot;,&quot;Country&quot;:&quot;Djibouti&quot;,&quot;Phone 1&quot;:&quot;5153435776&quot;,&quot;Phone 2&quot;:&quot;686-620-1820x944&quot;,&quot;Email&quot;:&quot;vmata@colon.com&quot;,&quot;Subscription Date&quot;:&quot;2021-04-23&quot;,&quot;Website&quot;:&quot;http://www.hobbs.com/&quot;}                                                                                                                                                                         <br>camel-test  | 23:52:29.099 INFO  [Camel (camel-1) thread #1 - file:///data/input] csv-to-json - Row 2: {&quot;Index&quot;:&quot;3&quot;,&quot;Customer Id&quot;:&quot;6F94879bDAfE5a6&quot;,&quot;First Name&quot;:&quot;Roy&quot;,&quot;Last Name&quot;:&quot;Berry&quot;,&quot;Company&quot;:&quot;Murillo-Perry&quot;,&quot;City&quot;:&quot;Isabelborough&quot;,&quot;Country&quot;:&quot;Antigua and Barbuda&quot;,&quot;Phone 1&quot;:&quot;+1-539-402-0259&quot;,&quot;Phone 2&quot;:&quot;(496)978-3969x58947&quot;,&quot;Email&quot;:&quot;beckycarr@hogan.com&quot;,&quot;Subscription Date&quot;:&quot;2020-03-25&quot;,&quot;Website&quot;:&quot;http://www.lawrence.com/&quot;} <br>...</pre><h3>Conclusion</h3><p><em>Apache Camel</em> and <em>Apache NiFi</em> are both, loosely, “<strong><em>things that move data between systems</em></strong>” — but once you look past that surface, they solve genuinely different problems and live in genuinely different places in an architecture. Camel is a library for building integrations. It is small, fast, developer-centric, and lives <em>inside</em> your services.</p><p>NiFi is a platform for operating dataflows. It is large, clustered, operator-centric, and lives <em>next to</em> your services as its own tier. You get a visual design surface, persistent queues, built-in provenance, and out-of-the-box back-pressure — at the cost of a heavier footprint and a UI-driven workflow that sits outside your application’s source tree.</p><p>The choice is rarely about which tool is “better” — it is about which seam of your architecture needs the work done:</p><ul><li>If the integration belongs inside a <strong>microservice</strong>, alongside its domain logic, shipped by its development team —<strong> reach for Camel</strong>.</li><li>If the integration belongs in a <strong>shared data-movement platform</strong>, operated by a separate team, auditable by regulators, and designed without writing code —<strong> reach for NiFi</strong>.</li></ul><p>In practice, mature organizations often run both: Camel for the fine-grained, API-level integrations embedded in each service, and NiFi for the coarse-grained, high-volume dataflows that feed the data lake.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6918d8debf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Opensky telemetry using Nifi, Apache Iceberg, Trino and Grafana]]></title>
            <link>https://medium.com/@chaudhuryk89/opensky-telemetry-using-nifi-apache-iceberg-trino-and-grafana-59a6d527f1b6?source=rss-f9f6ec1592d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/59a6d527f1b6</guid>
            <category><![CDATA[open-skies]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[trinos]]></category>
            <category><![CDATA[apache-iceberg]]></category>
            <category><![CDATA[apache-nifi]]></category>
            <dc:creator><![CDATA[Kaustav Chaudhury]]></dc:creator>
            <pubDate>Thu, 16 Apr 2026 20:03:19 GMT</pubDate>
            <atom:updated>2026-04-16T20:03:43.058Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-u3Z5oOeXMTEaRW20X4SA.png" /></figure><p>I was always fascinated how <strong>Opensky Network </strong>keeps providing such robust, community-driven stream of global air traffic surveillance data, primarily sourced through <strong>ADS-B</strong> (Automatic Dependent Surveillance-Broadcast) and <strong>Mode S</strong> signals. For data engineers and researchers, this telemetry represents a high-velocity firehose of aircraft state vectors — including <em>latitude</em>, <em>longitude</em>, <em>barometric altitude</em>, and <em>velocity</em> — emitted by thousands of transponders every second.</p><p>Their API is freely available for analysis and as of today, they are also using Trino for historical data. So, what would it need to reverse engineer their API data into a home made pipeline ? Here is my story building geospatial map with Grafana using Nifi, Trino &amp; Apache Iceberg for historical data on MinIO as a warehouse.</p><ul><li>Source — OpenSky REST + OpenSky Keycloak (OAuth2)</li><li><a href="https://github.com/chaudhuryk89/opensky_geomap/blob/main/nifi/Dockerfile">NiFi 1.27</a> — OpenSkyTick (180 sec) → <a href="https://github.com/chaudhuryk89/opensky_geomap/blob/main/nifi/scripts/opensky_ingest.groovy">ExecuteScript</a>(Groovy, token cache, 429 fail-fast) → PutSQL (batch 50) + DeadLetter PutFile</li><li>Lakehouse — Trino 453 (4G heap), Iceberg REST 1.6, MinIO (s3://warehouse), table iceberg.aviation.flight_positions partitioned by day(event_ts)</li><li>Viz — Grafana 11.3 (Geomap + trino-datasource)</li><li>Edges: Bearer token to OpenSky, <strong>JDBC to Trino</strong>, catalog API to Iceberg REST, S3 to MinIO, SQL from Grafana.</li></ul><p>Before we begin we need to create a <strong>free</strong> account on <a href="https://opensky-network.org/my-opensky/account">https://opensky-network.org/my-opensky/account</a>. Once created and verified we use the client id and secret and keep it somewhere safe. We need to plug it in the .env file for our projecct. (Daily limit 4000 credits)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*2TDs7BHXISbwk6a6a725yg.png" /></figure><h3>Our Implementation Scope</h3><ul><li>Stand up all services with Docker Compose: NiFi, MinIO, Iceberg REST Catalog, Trino, Grafana, and one bootstrap/init container for initialization</li><li>Ingest <strong><em>OpenSky </em></strong>states (icao24, callsign, time_position, last_contact, longitude, latitude, baro_altitude, velocity, true_track, vertical_rate, geo_altitude, origin_country, on_ground, spi, position_source) via NiFi</li><li>Persist to Iceberg table on MinIO with append-only records and event-time column for temporal replay using JDBC</li><li>Query Iceberg through Trino; <strong>Grafana uses Trino datasource</strong></li><li>Current flight location panel (latest position per aircraft)</li><li>For our simulation keep everything containerized and reproducible with one startup command (Bootstrap)</li></ul><h3>NiFi Flow Design</h3><p>The flow is four processors:</p><ul><li>OpenSkyTick (GenerateFlowFile, every 90 sec) — ticks the pipeline on a schedule that fits the 4k/day credit budget</li><li>ExecuteScript (Groovy) — gets/refreshes the Bearer token, fetches states, on 429 fails fast and logs remaining credits, on 200 builds Trino INSERT statements</li><li>PutSQLToIceberg — commits batches of 50 rows over JDBC (small Iceberg commits = small heap spikes). Since we are using local MinIO catalog we will use custom JDBC</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*0LhlNFALspYf-CGpr1u77g.png" /></figure><ul><li>DeadLetterPutFile — anything that fails lands as a flowfile on disk for inspection/debugging</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oNkMqTaAumeYfWzD2uMgeg.png" /><figcaption>Nifi Flow</figcaption></figure><h3>Data Model and Query Strategy</h3><ul><li>Iceberg table: aviation.flight_positions</li><li>ingestion/event metadata: event_ts, ingest_ts, source</li><li>Partitioned by day(event_ts) for query pruning and historical scans</li></ul><h3>Trino to The Rescue</h3><p><strong>Trino </strong>helps with our INSERT INTO iceberg.aviation.flight_positions VALUES (...) and turns it into <strong>Parquet files + Iceberg metadata</strong> in <strong>MinIO</strong>. Same engine handles Grafana’s analytical queries. One SQL surface for write and read. <strong>Why Trino?</strong> Because we want SQL everywhere (NiFi PutSQL, Grafana panels, ad-hoc trino-cli) without shipping a second engine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QFvmf9dRrFYxCFerKAHcWQ.png" /><figcaption>Trino Status</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iHFAkeeq1g-rtk5SJGx5tQ.png" /><figcaption>Trino Query status</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YwkAkMGTnh_g_WybuK8GEQ.png" /><figcaption>Queries</figcaption></figure><h3>Iceberg + MinIO — the local lakehouse</h3><p>MinIO is an S3 in a box! Iceberg turns that bucket into a table with <em>ACID</em> semantics, <em>schema evolution</em>, and <em>time-travel</em>. The catalog is served by tabulario/iceberg-rest, so Trino just points at http://iceberg-rest:8181 and speaks a standard REST API — no Hive Metastore, no Glue! Plus it gives us append-only inserts from NiFi today and leaves the door open for MERGE, DELETE FROM, snapshots, and time travel tomorrow — all without rewriting the ingester! Isn’t that awesome?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*-G98Mul6MLTnhvXUd4lNHg.png" /><figcaption>MinIO local object store catalog</figcaption></figure><pre>-- Iceberg table queried by Trino catalog &quot;iceberg&quot; (see trino/etc/catalog/iceberg.properties).<br>-- Partitioned by calendar day of event_ts for time-range pruning in Grafana.<br><br>CREATE SCHEMA IF NOT EXISTS iceberg.aviation;<br><br>CREATE TABLE IF NOT EXISTS iceberg.aviation.flight_positions (<br>    icao24 VARCHAR,<br>    callsign VARCHAR,<br>    origin_country VARCHAR,<br>    time_position BIGINT,<br>    last_contact BIGINT,<br>    longitude DOUBLE,<br>    latitude DOUBLE,<br>    baro_altitude DOUBLE,<br>    on_ground BOOLEAN,<br>    velocity DOUBLE,<br>    true_track DOUBLE,<br>    vertical_rate DOUBLE,<br>    geo_altitude DOUBLE,<br>    squawk VARCHAR,<br>    spi BOOLEAN,<br>    position_source INTEGER,<br>    event_ts TIMESTAMP(3) WITH TIME ZONE,<br>    ingest_ts TIMESTAMP(3) WITH TIME ZONE,<br>    source VARCHAR<br>)<br>WITH (<br>    format = &#39;PARQUET&#39;,<br>    partitioning = ARRAY[&#39;day(event_ts)&#39;]<br>);</pre><h3>Grafana — the map (and the time machine)</h3><p>Finally the end outcome of our pipeline — <a href="https://github.com/chaudhuryk89/opensky_geomap/blob/main/grafana/dashboards/flights_geomap.json">Grafana</a> to visualize flight patterns with custom time windows as per need. Dont worry, everything is still running on <a href="https://github.com/chaudhuryk89/opensky_geomap/blob/main/docker-compose.yml">containers</a> locally via bootstrap entry point. All containers live on the opensky_net Docker network; Trino talks to minio / iceberg-rest by name. <strong>Trino</strong> can also be called via docker container exec as :</p><pre>E:\opensky_geomap&gt;docker compose exec trino trino --catalog iceberg --schema aviation<br>trino:aviation&gt; SELECT count(*), max(event_ts)<br>             -&gt; FROM iceberg.aviation.flight_positions;<br> _col0 |             _col1<br>-------+--------------------------------<br> 48838 | 2026-04-16 19:17:39.000000 UTC <br>(1 row)<br><br>Query 20260416_192515_01504_xjnwn, FINISHED, 1 node<br>Splits: 833 total, 833 done (100.00%)<br>0.89 [48.8K rows, 5.29MB] [54.7K rows/s, 5.92MB/s]</pre><p>To bring up everything in one go:</p><pre>cp .env.example .env<br># paste your OpenSky client_id / client_secret into .env<br>docker compose up -d --build</pre><ul><li>Grafana → http://localhost:3000 (dashboard: <em>OpenSky flights (Iceberg via Trino)</em>)</li><li>NiFi → <a href="http://localhost:8088/">http://localhost:8088</a></li><li>Trino → <a href="http://localhost:8082/">http://localhost:8082</a></li><li>MinIO console → <a href="http://localhost:9001/">http://localhost:9001</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FpVwA5iG2uiaV3mi-v8_Pw.png" /><figcaption>Grafana dashboard</figcaption></figure><h3>Ending Notes</h3><ul><li>Credit-aware polling. Global /states/all is 4 credits per call. A standard account gets about 4,000 per day. A 90 sec tick keeps average usage under budget; that means our nifi tickrate is also set to 180s to avoid any HTTP 429 rate limit errors</li><li>Small Iceberg commits. batchSize = 50 keeps every INSERT small, so Trino doesn’t build a giant in-memory result before commit. We hit Heap memory error with 2G but increasing to 4G resolved it</li><li>Iceberg catalog definitions can be fussy, but choosing the right propery helps alleviate any configuration issues</li></ul><p>Please check <a href="https://github.com/chaudhuryk89/opensky_geomap">github</a> for all files and scripts. The set of <strong>init </strong>containers are only for initializing the core components to support bootstrapping.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59a6d527f1b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes cluster simulation at home without cloud bill : MicroKube]]></title>
            <link>https://medium.com/@chaudhuryk89/kubernetes-cluster-simulation-at-home-without-cloud-bill-microkube-7c59dd099954?source=rss-f9f6ec1592d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c59dd099954</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[kind]]></category>
            <category><![CDATA[kubernetes-operator]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[Kaustav Chaudhury]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 01:10:31 GMT</pubDate>
            <atom:updated>2026-04-15T01:18:43.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8qbRNfvy5I8RNZ3AYHvjA.jpeg" /></figure><p>Simulating a <strong>Kubernetes</strong> environment doesn’t require a hefty cloud bill. By leveraging <strong><em>KinD </em>(Kubernetes in Docker)</strong> on <strong>Windows Subsystem for Linux (WSL2)</strong>, you can create a high-fidelity, multi-node cluster that mirrors production behavior — right on your laptop.</p><p>Do you want to simulate production kubernetes cluster without the overhead of cloud cost &amp; infrastructure ? Say Hello to <a href="https://github.com/chaudhuryk89/microkube/tree/main"><strong>MicroKube</strong></a><strong> </strong>with <strong>KinD —<em> Running KinD on Windows involves a nested layers strategy. Your Windows host provides the resources, WSL2 provides the Linux kernel, Docker manages the “node” containers, and KinD orchestrates them into a cluster.</em></strong></p><p><strong>Prerequisites:</strong></p><ul><li><strong>Host:</strong> Windows 10/11 with WSL2 enabled.</li><li><strong>Distro:</strong> Ubuntu (latest LTS recommended).</li><li><strong>Runtime:</strong> Docker Desktop (with WSL integration) OR Native Docker Engine installed inside WSL2.</li><li><strong>Tools:</strong> kubectl and kind CLI installed within your WSL terminal.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5WQQfB11asbuBbeUqTL1nA.png" /><figcaption>Simulation Overview</figcaption></figure><h3>Part 1: Preparation</h3><p>To simulate scheduling and node pressure, a single-node cluster isn’t enough. We need a multi-node <a href="https://github.com/chaudhuryk89/microkube/blob/main/kind/kind-config.yaml">configuration </a>to see how pods move when a “node” gets crowded.</p><pre># KinD multi-node cluster with ingress-ready control plane.<br># Host ports 8080/8443 map to node 80/443 so you do not need elevated ports on Windows.<br># https://kind.sigs.k8s.io/docs/user/ingress/<br>kind: Cluster<br>apiVersion: kind.x-k8s.io/v1alpha4<br>name: dev<br>nodes:<br>  - role: control-plane<br>    kubeadmConfigPatches:<br>      - |<br>        kind: InitConfiguration<br>        nodeRegistration:<br>          kubeletExtraArgs:<br>            node-labels: &quot;ingress-ready=true&quot;<br>    extraPortMappings:<br>      - containerPort: 80<br>        hostPort: 8080<br>        protocol: TCP<br>      - containerPort: 443<br>        hostPort: 8443<br>        protocol: TCP<br>  - role: worker<br>  - role: worker</pre><p>On WSL we will need <strong>KinD </strong>installed along with <strong>Docker</strong>. Use <a href="https://github.com/chaudhuryk89/microkube/blob/main/scripts/install-kind-wsl.sh"><em>scripts/install-kind-wsl.sh</em></a> from repository.</p><pre>wsl -e bash -lc &quot;cd /mnt/e/cursor_projects/microkube &amp;&amp; sed -i &#39;s/\r$//&#39; scripts/install-kind-wsl.sh &amp;&amp; KIND_VERSION=v0.31.0 bash scripts/install-kind-wsl.sh&quot;<br>Downloading https://kind.sigs.k8s.io/dl/v0.31.0/kind-linux-amd64<br>Installed:<br>kind v0.31.0 go1.25.5 linux/amd64</pre><p>This <a href="https://github.com/chaudhuryk89/microkube/tree/main"><strong>github</strong></a><strong> </strong>link has all required scripts and yaml files. We will use the <a href="https://github.com/chaudhuryk89/microkube/blob/main/scripts/verify-prereqs.sh"><em>scripts/verify-prereqs.sh</em></a> file to make sure we have tools we need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*AGm6d66siz3dmODYxF_1lw.png" /><figcaption>verify prerequisites</figcaption></figure><h3>Part 2: Baseline for “real-time” metrics inside Kubernetes</h3><p>KinD does not ship full observability by default. For CPU/memory <strong>per pod/node</strong> in near real time:</p><ol><li><strong>Install metrics-server</strong> (enables kubectl top pods/nodes). For KinD, you typically need <strong>insecure TLS</strong> or <strong>kubelet address flags</strong> tweaks—use the documented KinD patch pattern (e.g. components patch in a Kind cluster config or the metrics-server install args from KinD’s user guide / common recipes).</li><li><strong>Sanity check</strong>: kubectl top nodes and kubectl top pods -A after metrics-server becomes ready.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*Dw6-K5_eMoGQl4m1lkaQIw.png" /><figcaption>kubectl status</figcaption></figure><h3>Part 3: Horizontal scaling with a “sensitive” CPU target (20%)</h3><p><strong>How:</strong> <strong>HPA v2</strong> on <strong>demo-web</strong> uses <strong>CPU utilization</strong> with <strong>averageUtilization: 20</strong> relative to each pod’s <strong>CPU request</strong>. That is <strong>lower than a typical 50–70%</strong> target, so the controller <strong>scales out sooner</strong> under the same HTTP stress—useful for demos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*MyTNf9Wm0FdmqacYUicttQ.png" /></figure><p><strong>How load reaches the app:</strong> Job <strong>http-load</strong> in <strong>loadtest</strong> runs ~<strong>three minutes</strong> of parallel <strong>curl</strong> to <strong>http://demo-web.demo.svc.cluster.local</strong>, raising <strong>demo</strong> pod CPU.</p><p><strong>Verify in real time:</strong> kubectl get hpa -n demo -w and kubectl get pods -n demo -l app=demo-web -w; optional kubectl top pods -n demo</p><pre>Load test HTTP:<br>kubectl config use-context kind-dev<br>cd /mnt/e/cursor_projects/microkube<br>kubectl delete job http-load -n loadtest --ignore-not-found<br>kubectl apply -f k8s/load/http-load-job.yaml<br>kubectl get hpa -n demo -w<br><br>Load test CPU — stronger steady load:<br>kubectl scale deployment cpu-burn -n loadtest --replicas=3<br>kubectl top pods -n loadtest<br><br>Load test CPU — one spike now (without waiting 5 minutes):<br>kubectl create job -n loadtest --from=cronjob/cpu-spike cpu-spike-manual-$(date +%s)</pre><h3>Part 4: Extra CPU / memory simulation (loadtest)</h3><p><strong>How:</strong></p><ul><li><strong>cpu-burn</strong>: <strong>Deployment</strong> (busybox) infinite shell busy-loop with <strong>CPU limits</strong> → steady, throttled CPU for <strong>kubectl top</strong>.</li><li><strong>cpu-spike</strong>: <strong>CronJob</strong> → short <strong>busybox</strong> busy-loop Jobs (replaced <strong>polinux/stress</strong> after <strong>StartError</strong> on modern containerd).</li><li><strong>memory-spike</strong>: optional <strong>Job</strong> using <strong>python:3.12-alpine</strong> holding a <strong>bytearray</strong> within <strong>memory limits</strong> (no stress image).</li><li><strong>http-load</strong>: optional <strong>Job</strong> as above (also re-runnable after <strong>kubectl delete job http-load</strong>).</li></ul><p><strong>Note:</strong> <strong>loadtest</strong> CPU workloads do <strong>not</strong> scale <strong>demo-web</strong>; only <strong>HTTP load to </strong><strong>demo-web</strong> drives the <strong>HPA</strong>.</p><h3>End-to-end operator flow</h3><ol><li><strong>WSL</strong> + <strong>Docker</strong> + <strong>kubectl</strong> + <strong>kind</strong> → bash scripts/verify-prereqs.sh.</li><li><strong>bash scripts/bootstrap.sh</strong> → cluster <strong>dev</strong>, addons, <strong>demo</strong>, <strong>loadtest</strong>.</li><li>Browser → <strong>demo</strong> page; optional <strong>kubectl apply -f k8s/load/http-load-job.yaml</strong> → watch <strong>HPA</strong> / pods.</li><li><strong>Re-simulate:</strong> delete and rerun jobs<br>What — KinD lab, demo-web, metrics-server, HPA on CPU with averageUtilization: 20 (relative to each pod’s CPU request, not the whole node).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*u_ZcL4IH87EeX3fQb_xqKw.png" /></figure><p><strong>Why 20% </strong>— lower target than a typical default so the HPA is more likely to scale out under the same HTTP stress (good for demos). How stress is produced — the http-load Job runs ~3 minutes of parallel curl to demo-web inside the cluster. How to validate in real time — ordered kubectl steps: get hpa -w, get pods -w, top pods / top nodes, optional load logs, optional Lens/Headlamp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*G8gztkMTY62Q2RByP8VrRQ.png" /></figure><h3>It Pays to Be Kind!</h3><p>The most compelling feature of this setup isn’t just the technical depth — it’s the accessibility. By bridging <strong>Windows WSL2</strong> with <strong>KinD</strong>, you’ve effectively built a sophisticated Site Reliability Engineering (SRE) laboratory without spending a single cent on cloud provider fees.</p><p>In a traditional cloud environment, spinning up a multi-node cluster with managed services, load balancers, and monitoring storage can easily rack up a significant monthly bill. Here, the only investment required is your hardware’s spare cycles. You have the freedom to:</p><ul><li><strong>Fail Safely:</strong> Trigger OOMKills, simulate CPU throttling, and crash nodes without worrying about “hidden” egress or API costs.</li><li><strong>Iterate Rapidly:</strong> Tear down and rebuild your entire infrastructure in seconds, ensuring your deployment scripts are truly idempotent.</li><li><strong>Master Observability:</strong> Learn the nuances of metrics-server and resource scheduling in a controlled, local environment.</li></ul><p>Whether you are prepping for a Kubernetes certification or testing the resilience of a new microservice, this zero-cost simulation provides a high-fidelity playground that proves you don’t need a corporate budget to master the cloud-native stack. You’ve turned your local machine into a powerful development powerhouse — now go forth and break things!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c59dd099954" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Binlog to Breakthrough: Real-Time Change Data Capture Pipeline with PyFlink and MySQL]]></title>
            <link>https://medium.com/@chaudhuryk89/from-binlog-to-breakthrough-real-time-change-data-capture-pipeline-with-pyflink-and-mysql-dfa81efd3e36?source=rss-f9f6ec1592d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfa81efd3e36</guid>
            <category><![CDATA[apache-flink]]></category>
            <category><![CDATA[mysql-binlog]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[flink]]></category>
            <category><![CDATA[change-data-capture]]></category>
            <dc:creator><![CDATA[Kaustav Chaudhury]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 15:55:17 GMT</pubDate>
            <atom:updated>2026-04-13T15:55:17.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*dMhSMS-QbiBbc-A-eGupvQ.jpeg" /></figure><p>Apache Flink has emerged as the gold standard for stateful stream processing, and with the rise of <strong>PyFlink</strong>, we can now harness this power without diving deep into Java. Today, we’re walking through a lightweight prototype that bridges MySQL 8 and PyFlink to create a real-time data tap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FXfhCOgHpy5ojdoW4OhuLw.png" /><figcaption>containerized mysql8 &amp; pyflink instance</figcaption></figure><h3>The Concept: Streaming via Binlogs</h3><p>Traditional data extraction usually involves “<em>polling</em>” a database with expensive SELECT queries. CDC flips this on its head. By tailing the <strong>MySQL Binlog</strong> (binary log), we can stream every INSERT, UPDATE, and DELETE as an event.</p><p>For this prototype, we’ve built a containerized environment using a test_db.products table as our source. Any change made to a product’s price or name in MySQL is instantly &quot;pushed&quot; to our Flink application.</p><h3>The Blueprint: Dockerized CDC</h3><p>To keep the experiment clean and reproducible, we use a two-container setup via Docker Compose:</p><blockquote><strong>MySQL 8 Instance</strong>: Configured specifically for CDC with ROW level binlogging and GTID mode enabled.</blockquote><blockquote><strong>flink_cdc_app</strong>: A python:3.11-slim container pre-loaded with the OpenJDK JRE and the necessary Flink-MySQL connectors.</blockquote><h3>The Configuration Secret Sauce</h3><p>To make this work, the MySQL container isn’t just a standard database. We ensure the following flags are set in our docker-compose.yml:</p><ul><li>--server-id=223345: A unique ID for the Flink &quot;replica.&quot;</li><li>--log-bin=mysql-bin: Enables the binary log.</li><li>--binlog_format=ROW: Essential for CDC to capture the actual data changes.</li></ul><pre>services:<br>  mysql:<br>    image: mysql:8.0<br>    container_name: flink-cdc-mysql<br>    command:<br>      - --server-id=223345<br>      - --log-bin=mysql-bin<br>      - --binlog_format=ROW<br>      - --binlog_row_image=FULL<br>      - --gtid_mode=ON<br>      - --enforce_gtid_consistency=ON<br>    environment:<br>      MYSQL_ROOT_PASSWORD: 123456<br>      MYSQL_DATABASE: test_db<br>    ports:<br>      - &quot;3306:3306&quot;<br>    volumes:<br>      - ./docker/mysql/init:/docker-entrypoint-initdb.d<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;mysqladmin&quot;, &quot;ping&quot;, &quot;-h&quot;, &quot;localhost&quot;, &quot;-p123456&quot;]<br>      interval: 5s<br>      timeout: 5s<br>      start_period: 180s<br>      retries: 60<br><br>  pyflink-cdc:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    container_name: pyflink-cdc-app<br>    depends_on:<br>      mysql:<br>        condition: service_healthy<br>    environment:<br>      MYSQL_HOST: mysql<br>      MYSQL_PORT: &quot;3306&quot;<br>      MYSQL_USER: root<br>      MYSQL_PASSWORD: 123456<br>      MYSQL_DATABASE: test_db<br>      MYSQL_TABLE: products<br>      CDC_CONNECTOR_JAR: file:///opt/flink/connectors/flink-sql-connector-mysql-cdc-3.4.0.jar<br>      MYSQL_JDBC_JAR: file:///opt/flink/connectors/mysql-connector-j-8.4.0.jar</pre><p>The bind mount ./docker/mysql/init/01-init.sql → /docker-entrypoint-initdb.d initializes the dummy data for our test.</p><pre>CREATE DATABASE IF NOT EXISTS test_db;<br>USE test_db;<br><br>CREATE TABLE IF NOT EXISTS products (<br>    id INT PRIMARY KEY,<br>    name VARCHAR(255) NOT NULL,<br>    price DECIMAL(10, 2) NOT NULL<br>);<br><br>INSERT INTO products (id, name, price) VALUES<br>    (1, &#39;keyboard&#39;, 49.99),<br>    (2, &#39;mouse&#39;, 19.99),<br>    (3, &#39;monitor&#39;, 199.99)<br>ON DUPLICATE KEY UPDATE<br>    name = VALUES(name),<br>    price = VALUES(price);</pre><h3>The Heart of the App: flink_cdc_app.py</h3><p>The logic of our streaming pipeline is surprisingly concise. It performs four critical operations:</p><ol><li><strong>Environment Setup</strong>: Initializes a Streaming Table Environment.</li><li><strong>Fault Tolerance</strong>: Enables checkpointing every 3 seconds, ensuring that if the app crashes, it knows exactly where it left off in the binlog.</li><li><strong>Jar Integration</strong>: Dynamically links the flink-sql-connector-mysql-cdc and the mysql-connector-j drivers.</li><li><strong>The CDC Source</strong>: Defines a virtual table that points to our physical MySQL table.</li></ol><pre>import os<br><br>from pyflink.table import EnvironmentSettings, TableEnvironment<br><br>env_settings = EnvironmentSettings.in_streaming_mode()<br>t_env = TableEnvironment.create(env_settings)<br><br>t_env.get_config().set(&quot;execution.checkpointing.interval&quot;, &quot;3000ms&quot;)<br>cdc_connector_jar = os.getenv(<br>    &quot;CDC_CONNECTOR_JAR&quot;,<br>    &quot;file:///opt/flink/connectors/flink-sql-connector-mysql-cdc-3.4.0.jar&quot;,<br>)<br>mysql_jdbc_jar = os.getenv(<br>    &quot;MYSQL_JDBC_JAR&quot;,<br>    &quot;file:///opt/flink/connectors/mysql-connector-j-8.4.0.jar&quot;,<br>)<br>t_env.get_config().set(&quot;pipeline.jars&quot;, &quot;;&quot;.join([cdc_connector_jar, mysql_jdbc_jar]))<br><br>mysql_host = os.getenv(&quot;MYSQL_HOST&quot;, &quot;mysql&quot;)<br>mysql_port = os.getenv(&quot;MYSQL_PORT&quot;, &quot;3306&quot;)<br>mysql_user = os.getenv(&quot;MYSQL_USER&quot;, &quot;root&quot;)<br>mysql_password = os.getenv(&quot;MYSQL_PASSWORD&quot;, &quot;123456&quot;)<br>mysql_database = os.getenv(&quot;MYSQL_DATABASE&quot;, &quot;test_db&quot;)<br>mysql_table = os.getenv(&quot;MYSQL_TABLE&quot;, &quot;products&quot;)<br><br>t_env.execute_sql(&quot;&quot;&quot;<br>    CREATE TABLE mysql_cdc_source (<br>        id INT,<br>        name STRING,<br>        price DECIMAL(10, 2),<br>        PRIMARY KEY (id) NOT ENFORCED<br>    ) WITH (<br>        &#39;connector&#39; = &#39;mysql-cdc&#39;,<br>        &#39;hostname&#39; = &#39;{hostname}&#39;,<br>        &#39;port&#39; = &#39;{port}&#39;,<br>        &#39;username&#39; = &#39;{username}&#39;,<br>        &#39;password&#39; = &#39;{password}&#39;,<br>        &#39;database-name&#39; = &#39;{database}&#39;,<br>        &#39;table-name&#39; = &#39;{table}&#39;,<br>        &#39;scan.startup.mode&#39; = &#39;initial&#39;<br>    )<br>&quot;&quot;&quot;.format(<br>    hostname=mysql_host,<br>    port=mysql_port,<br>    username=mysql_user,<br>    password=mysql_password,<br>    database=mysql_database,<br>    table=mysql_table,<br>))<br><br>t_env.execute_sql(&quot;SELECT * FROM mysql_cdc_source&quot;).print()</pre><p>By setting scan.startup.mode to initial, the app performs a snapshot of the existing data first, then transitions seamlessly into &quot;tailing&quot; new changes. We need both the flink sql connector mysql cdc jar and mysql native connectivity jar for our prototype. Prepare the <strong>Dockerfile </strong>accordingly:</p><pre>FROM python:3.11-slim<br><br>ENV PYTHONUNBUFFERED=1<br>WORKDIR /app<br><br>RUN apt-get update \<br>    &amp;&amp; apt-get install -y --no-install-recommends curl ca-certificates openjdk-21-jre \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br><br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br><br>RUN mkdir -p /opt/flink/connectors \<br>    &amp;&amp; curl -fsSL \<br>        -o /opt/flink/connectors/flink-sql-connector-mysql-cdc-3.4.0.jar \<br>        https://repo1.maven.org/maven2/org/apache/flink/flink-sql-connector-mysql-cdc/3.4.0/flink-sql-connector-mysql-cdc-3.4.0.jar \<br>    &amp;&amp; curl -fsSL \<br>        -o /opt/flink/connectors/mysql-connector-j-8.4.0.jar \<br>        https://repo1.maven.org/maven2/com/mysql/mysql-connector-j/8.4.0/mysql-connector-j-8.4.0.jar<br><br>COPY flink_cdc_app.py /app/flink_cdc_app.py<br><br>CMD [&quot;python&quot;, &quot;/app/flink_cdc_app.py&quot;]</pre><h3>Observations from the Lab</h3><p>When we launch the stack, the magic happens in the logs. On startup, <strong>PyFlink </strong>reads our initial inventory (Keyboards, Mice, Monitors).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*zMTYgm25KmvUbnb5u7-flQ.png" /><figcaption>initial test_db.products contents</figcaption></figure><p>The moment we run an <strong>update</strong> in MySQL: UINSERT INTO products (id, name, price) VALUES (10, &#39;webcam&#39;, 89.99); UPDATE products SET price = 79.99 WHERE id = 10;The <strong>PyFlink </strong>console immediately prints the change event. It doesn’t wait for a cron job or a refresh; the event is pushed through the pipeline in milliseconds. Notice how flink captures the different operations under <strong><em>op </em></strong>column: INSERT, UPDATE, DELETE etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*EtRKu9YwUr0pFu0boS5kpQ.png" /><figcaption>change data captures</figcaption></figure><h3>Lessons Learned</h3><ul><li><strong>The Good</strong>: The setup is incredibly reactive. Using Checkpointing makes the pipeline resilient, and the Table API makes SQL-like operations on streams very intuitive.</li><li><strong>The Basic</strong>: For this prototype, we printed to stdout. In a production scenario, you would swap .print() for a Sink—writing the changes to <strong>Kafka</strong>, an <strong>S3 Data Lake</strong>, or an <strong>Elasticsearch index</strong>.</li></ul><h3>Conclusion</h3><p>Building a real-time CDC pipeline no longer requires a massive infrastructure team and thousands of lines of Java. With Apache Flink we can build robust, “always-on” data feeds that keep downstream systems in perfect sync with the source of truth.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfa81efd3e36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Dream Duo: Building a simple Real-Time Data Pipeline with Kafka and Spark Streaming]]></title>
            <link>https://medium.com/@chaudhuryk89/the-dream-duo-building-a-simple-real-time-data-pipeline-with-kafka-and-spark-streaming-a99e2a4f01e4?source=rss-f9f6ec1592d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a99e2a4f01e4</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[kafka-streams]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[spark-streaming]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Kaustav Chaudhury]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 15:54:11 GMT</pubDate>
            <atom:updated>2026-04-12T15:59:41.616Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of big data, speed is no longer a luxury — it’s a requirement. Whether it’s detecting credit card fraud as it happens or updating a live leaderboard for a global gaming app, “batch processing” once a day just doesn’t cut it.</p><p>Enter the power couple of data engineering: <strong>Apache Kafka</strong> and <strong>Apache Spark Streaming</strong>. Kafka acts as the high-speed nervous system, capturing streams of events, while Spark acts as the brain, processing that data in real-time. If you’re looking to move from static datasets to living, breathing data pipelines, this integration is the gold standard. By using <strong>psutil</strong> (a cross-platform library for process and system utilities) to feed <strong>Apache Kafka</strong>, you create a living, breathing data pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*Lq65tkHAEJzlmoSr5s0rVQ.png" /><figcaption>sparkafka project structure</figcaption></figure><p><strong><em>Sparkafka </em></strong>is a small, Docker-based pipeline that publishes live machine metrics (CPU, memory, disk via <strong><em>psutil</em></strong>) to Kafka and consumes them with Spark Structured Streaming, writing both raw JSONL and windowed aggregates to CSV on a shared folder (Can be redirected to hive or other targets). It gives you a realistic produce → broker → consume → stateful processing → durable output loop without building a large application. Because Kafka and Spark run in containers with sensible defaults, you can focus on topics, offsets, checkpoints, and stream semantics instead of fighting local installs. The setup is ideal for hands-on practice: you can change publish intervals, inspect messages in the topic indirectly via files, and see how Spark’s <strong>watermarking</strong>, <strong>windows</strong>, and <strong>checkpoints </strong>behave over time. In short, it is a self-contained sandbox for learning how streaming data moves through Kafka and how Spark turns that stream into queryable, time-bounded results you can verify on disk.</p><p>Start with the <strong>docker-compose YML</strong> file with dedicated zookeeper, kafka core broker, the publisher and the spark streaming job definitions. Add dedicated driver network ‘<strong>sparkafka</strong>’ for simplification.</p><pre>services:<br>  zookeeper:<br>    image: zookeeper:3.9<br>    ports:<br>      - &quot;2181:2181&quot;<br>    networks:<br>      - sparkafka<br><br>  kafka:<br>    image: confluentinc/cp-kafka:7.5.0<br>    depends_on:<br>      - zookeeper<br>    environment:<br>      KAFKA_BROKER_ID: 1<br>      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT<br>      KAFKA_LISTENERS: PLAINTEXT://:9092<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>      KAFKA_AUTO_CREATE_TOPICS_ENABLE: &quot;true&quot;<br>    ports:<br>      - &quot;9092:9092&quot;<br>    networks:<br>      - sparkafka<br><br>  publisher:<br>    build: ./publisher<br>    depends_on:<br>      - kafka<br>    environment:<br>      KAFKA_BOOTSTRAP_SERVERS: kafka:9092<br>      KAFKA_TOPIC: psutil-stats<br>      PUBLISH_INTERVAL_SECONDS: &quot;3&quot;<br>      RAW_OUTPUT_DIR: /data/raw<br>    volumes:<br>      - ./output:/data<br>    networks:<br>      - sparkafka<br><br>  spark:<br>    build: ./spark-job<br>    depends_on:<br>      - kafka<br>    environment:<br>      KAFKA_BOOTSTRAP_SERVERS: kafka:9092<br>      KAFKA_TOPIC: psutil-stats<br>      STREAMING_OUTPUT_PATH: /data/streaming_output<br>      CHECKPOINT_PATH: /data/checkpoint<br>    volumes:<br>      - ./output:/data<br>    command:<br>      - --packages<br>      - org.apache.spark:spark-sql-kafka-0-10_2.12:3.4.0<br>      - --master<br>      - &quot;local[*]&quot;<br>      - /app/streaming_job.py<br>    networks:<br>      - sparkafka<br><br>networks:<br>  sparkafka:<br>    driver: bridge</pre><p>Next, build the <strong>Dockerfile </strong>for spark-submit job:</p><pre># Use official Spark image with Python; Kafka connector added via --packages at runtime<br>FROM apache/spark-py:v3.4.0<br><br>USER root<br>RUN mkdir -p /app<br>COPY streaming_job.py /app/<br>WORKDIR /app<br><br># /data is provided by volume mount at runtime; run as root so Spark can write there<br>ENTRYPOINT [&quot;/opt/spark/bin/spark-submit&quot;]</pre><p>Now we prepare the <strong>streaming python job</strong> that will be running on the container environment ingesting data from Kafka topic and writing output as csv files. Notice how tumbling window and frequency of data is controlled using the <strong>withWatermark </strong>with <strong>event_time </strong>parameters. To avoid writing empty datafiles we add a check for one file per minute when the batch has rows (1-min aggregated data).</p><pre>&quot;&quot;&quot;<br>Spark Structured Streaming job: read psutil stats from Kafka,<br>apply 2-minute tumbling window, write one CSV per minute to shared FS.<br>&quot;&quot;&quot;<br>import os<br>import sys<br><br>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import avg, col, from_json, max, window<br>from pyspark.sql.types import DoubleType, StringType, StructField, StructType<br><br># Kafka and paths from environment<br>KAFKA_BOOTSTRAP = os.environ.get(&quot;KAFKA_BOOTSTRAP_SERVERS&quot;, &quot;localhost:9092&quot;)<br>TOPIC = os.environ.get(&quot;KAFKA_TOPIC&quot;, &quot;psutil-stats&quot;)<br>OUTPUT_PATH = os.environ.get(&quot;STREAMING_OUTPUT_PATH&quot;, &quot;/data/streaming_output&quot;)<br>CHECKPOINT_PATH = os.environ.get(&quot;CHECKPOINT_PATH&quot;, &quot;/data/checkpoint&quot;)<br><br># Schema for publisher JSON (value from Kafka)<br>STATS_SCHEMA = StructType(<br>    [<br>        StructField(&quot;ts&quot;, StringType(), False),<br>        StructField(&quot;host&quot;, StringType(), True),<br>        StructField(&quot;cpu_percent&quot;, DoubleType(), True),<br>        StructField(&quot;memory_percent&quot;, DoubleType(), True),<br>        StructField(&quot;memory_used_mb&quot;, DoubleType(), True),<br>        StructField(&quot;memory_available_mb&quot;, DoubleType(), True),<br>        StructField(&quot;disk_percent&quot;, DoubleType(), True),<br>        StructField(&quot;disk_used_gb&quot;, DoubleType(), True),<br>        StructField(&quot;disk_free_gb&quot;, DoubleType(), True),<br>        StructField(&quot;cpu_mhz&quot;, DoubleType(), True),<br>    ]<br>)<br><br><br>def main() -&gt; None:<br>    spark = (<br>        SparkSession.builder.appName(&quot;psutil-kafka-streaming&quot;)<br>        .config(&quot;spark.sql.streaming.checkpointLocation&quot;, CHECKPOINT_PATH)<br>        .getOrCreate()<br>    )<br>    spark.sparkContext.setLogLevel(&quot;WARN&quot;)<br><br>    # Stream from Kafka<br>    kafka_df = (<br>        spark.readStream.format(&quot;kafka&quot;)<br>        .option(&quot;kafka.bootstrap.servers&quot;, KAFKA_BOOTSTRAP)<br>        .option(&quot;subscribe&quot;, TOPIC)<br>        .option(&quot;startingOffsets&quot;, &quot;latest&quot;)<br>        .load()<br>    )<br><br>    # Parse JSON value and extract event time<br>    parsed = kafka_df.select(<br>        from_json(col(&quot;value&quot;).cast(&quot;string&quot;), STATS_SCHEMA).alias(&quot;data&quot;)<br>    ).select(&quot;data.*&quot;)<br><br>    with_ts = parsed.withColumn(<br>        &quot;event_time&quot;, col(&quot;ts&quot;).cast(&quot;timestamp&quot;)<br>    )<br><br>    # 1-minute tumbling window; 2-minute watermark for late data<br>    windowed = (<br>        with_ts.withWatermark(&quot;event_time&quot;, &quot;2 minutes&quot;)<br>        .groupBy(window(col(&quot;event_time&quot;), &quot;1 minute&quot;).alias(&quot;w&quot;))<br>        .agg(<br>            avg(&quot;cpu_percent&quot;).alias(&quot;avg_cpu_percent&quot;),<br>            max(&quot;cpu_percent&quot;).alias(&quot;max_cpu_percent&quot;),<br>            avg(&quot;memory_percent&quot;).alias(&quot;avg_memory_percent&quot;),<br>            max(&quot;memory_percent&quot;).alias(&quot;max_memory_percent&quot;),<br>            avg(&quot;disk_percent&quot;).alias(&quot;avg_disk_percent&quot;),<br>            max(&quot;disk_percent&quot;).alias(&quot;max_disk_percent&quot;),<br>        )<br>    )<br><br>    out = windowed.select(<br>        col(&quot;w.start&quot;).alias(&quot;window_start&quot;),<br>        col(&quot;w.end&quot;).alias(&quot;window_end&quot;),<br>        &quot;avg_cpu_percent&quot;,<br>        &quot;max_cpu_percent&quot;,<br>        &quot;avg_memory_percent&quot;,<br>        &quot;max_memory_percent&quot;,<br>        &quot;avg_disk_percent&quot;,<br>        &quot;max_disk_percent&quot;,<br>    )<br><br>    def write_non_empty_batch(batch_df, batch_id):<br>        &quot;&quot;&quot;Write one file per minute when the batch has rows (1-min aggregated data).&quot;&quot;&quot;<br>        if not batch_df.isEmpty():<br>            batch_df.coalesce(1).write.mode(&quot;append&quot;).option(&quot;header&quot;, &quot;true&quot;).csv(<br>                OUTPUT_PATH<br>            )<br><br>    query = (<br>        out.writeStream.outputMode(&quot;append&quot;)<br>        .foreachBatch(write_non_empty_batch)<br>        .option(&quot;checkpointLocation&quot;, CHECKPOINT_PATH)<br>        .trigger(processingTime=&quot;1 minute&quot;)<br>        .start()<br>    )<br>    query.awaitTermination()<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()<br>    sys.exit(0)</pre><p>Project outputs structured as:</p><ul><li>Raw: output/raw/stats.jsonl</li><li>Aggregated CSV: output/streaming_output/</li><li>Spark checkpoint: output/checkpoint/ (leave it alone while the job runs)</li></ul><blockquote><strong><em>prepare the publisher container and its requirements file:</em></strong><br><em>psutil&gt;=5.9.0<br>kafka-python&gt;=2.0.2</em><br><em>We only need above 2 modules for our tiny test!</em></blockquote><pre>FROM python:3.11-slim<br><br>WORKDIR /app<br><br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br><br>COPY main.py .<br><br>CMD [&quot;python&quot;, &quot;-u&quot;, &quot;main.py&quot;]</pre><p>Main <strong>entry point </strong>for publisher:</p><pre>&quot;&quot;&quot;<br>Psutil stats publisher: collects PC stats and produces to Kafka.<br>Also appends raw JSON lines to shared mount for debugging.<br>&quot;&quot;&quot;<br>import json<br>import os<br>import socket<br>import time<br>from datetime import datetime, timezone<br><br>import psutil<br>from kafka import KafkaProducer<br>from kafka.errors import KafkaError<br><br><br>def collect_stats() -&gt; dict:<br>    &quot;&quot;&quot;Collect CPU, memory, disk stats via psutil.&quot;&quot;&quot;<br>    mem = psutil.virtual_memory()<br>    disk = psutil.disk_usage(&quot;/&quot;)<br>    cpu_percent = psutil.cpu_percent(interval=None)<br>    try:<br>        cpu_freq = psutil.cpu_freq()<br>        cpu_mhz = cpu_freq.current if cpu_freq else None<br>    except Exception:<br>        cpu_mhz = None<br>    return {<br>        &quot;ts&quot;: datetime.now(timezone.utc).isoformat(),<br>        &quot;host&quot;: socket.gethostname(),<br>        &quot;cpu_percent&quot;: cpu_percent,<br>        &quot;memory_percent&quot;: mem.percent,<br>        &quot;memory_used_mb&quot;: round(mem.used / (1024 * 1024), 2),<br>        &quot;memory_available_mb&quot;: round(mem.available / (1024 * 1024), 2),<br>        &quot;disk_percent&quot;: disk.percent,<br>        &quot;disk_used_gb&quot;: round(disk.used / (1024**3), 2),<br>        &quot;disk_free_gb&quot;: round(disk.free / (1024**3), 2),<br>        &quot;cpu_mhz&quot;: cpu_mhz,<br>    }<br><br><br>def _to_bytes(value):<br>    &quot;&quot;&quot;Serialize key or value to bytes; never call .encode() on already bytes.&quot;&quot;&quot;<br>    if value is None:<br>        return b&quot;&quot;<br>    if isinstance(value, bytes):<br>        return value<br>    if isinstance(value, str):<br>        return value.encode(&quot;utf-8&quot;)<br>    return json.dumps(value).encode(&quot;utf-8&quot;)<br><br><br>def main() -&gt; None:<br>    bootstrap = os.environ.get(&quot;KAFKA_BOOTSTRAP_SERVERS&quot;, &quot;localhost:9092&quot;)<br>    topic = os.environ.get(&quot;KAFKA_TOPIC&quot;, &quot;psutil-stats&quot;)<br>    interval = int(os.environ.get(&quot;PUBLISH_INTERVAL_SECONDS&quot;, &quot;3&quot;))<br>    raw_dir = os.environ.get(&quot;RAW_OUTPUT_DIR&quot;, &quot;/data/raw&quot;)<br><br>    producer = None<br>    raw_path = None<br>    raw_file = None<br><br>    # Optional: write raw JSONL to shared mount<br>    try:<br>        os.makedirs(raw_dir, exist_ok=True)<br>        raw_path = os.path.join(raw_dir, &quot;stats.jsonl&quot;)<br>        raw_file = open(raw_path, &quot;a&quot;, encoding=&quot;utf-8&quot;)<br>    except OSError as e:<br>        print(f&quot;Warning: could not open raw output {raw_path}: {e}&quot;)<br><br>    while True:<br>        try:<br>            if producer is None:<br>                producer = KafkaProducer(<br>                    bootstrap_servers=bootstrap.split(&quot;,&quot;),<br>                    value_serializer=_to_bytes,<br>                    key_serializer=_to_bytes,<br>                )<br>            stats = collect_stats()<br>            payload = json.dumps(stats)<br>            # Pass str/dict so serializers handle conversion; they accept bytes too<br>            producer.send(topic, value=stats, key=stats.get(&quot;host&quot;) or &quot;&quot;)<br>            if raw_file:<br>                raw_file.write(payload + &quot;\n&quot;)<br>                raw_file.flush()<br>        except KafkaError as e:<br>            print(f&quot;Kafka error: {e}&quot;)<br>            producer = None<br>        except Exception as e:<br>            print(f&quot;Error: {e}&quot;)<br>        time.sleep(interval)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>And that is all you need to kick it off! Build and start all the containers and everything should be up. Notice how the <strong>stats.json</strong> starts populating with sensor data which then gets transmitted to spark for writing on streaming output path (/data/streaming_output).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*E1ss769Qd3NRIRrBNjCyeA.png" /><figcaption>Docker containers</figcaption></figure><figure><img alt="stats.json raw sensor data" src="https://cdn-images-1.medium.com/max/1024/1*b7pNgHg7a4X9KgfOW7hJhA.png" /><figcaption>stats.jsonl</figcaption></figure><p>Example <strong>Streaming </strong>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0moqcqftPYQs6jwtxxpTOQ.png" /><figcaption>streaming_output .part csv data files with sensor information</figcaption></figure><h3>Conclusion</h3><p>Integrating <strong>psutil </strong>with <strong>Kafka</strong> and <strong>Spark </strong>turns an abstract coding exercise into a practical tool. You aren&#39;t just moving data; you&#39;re building a window into your machine&#39;s health. By seeing your CPU usage ripple through Kafka and appear in Spark in near real-time, you&#39;ll master the fundamentals of the modern streaming stack. Now go, and create a <strong>SPARK</strong>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a99e2a4f01e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>