<?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 Piyush Kumar Singh on Medium]]></title>
        <description><![CDATA[Stories by Piyush Kumar Singh on Medium]]></description>
        <link>https://medium.com/@piyushkumarsingh.nmims?source=rss-1adb855069a7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BKhFCz43oBpqGObVfYyAOA.jpeg</url>
            <title>Stories by Piyush Kumar Singh on Medium</title>
            <link>https://medium.com/@piyushkumarsingh.nmims?source=rss-1adb855069a7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:15:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@piyushkumarsingh.nmims/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[The Morning fuel: Power smoothie]]></title>
            <link>https://medium.com/@piyushkumarsingh.nmims/the-morning-fuel-power-smoothie-a65539987cbf?source=rss-1adb855069a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a65539987cbf</guid>
            <category><![CDATA[lifestyle]]></category>
            <category><![CDATA[food]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[life]]></category>
            <dc:creator><![CDATA[Piyush Kumar Singh]]></dc:creator>
            <pubDate>Sun, 14 Jun 2026 11:17:51 GMT</pubDate>
            <atom:updated>2026-06-14T11:17:51.251Z</atom:updated>
            <content:encoded><![CDATA[<p>Do you like your mornings slow and breezy, or are you running through them like me?</p><p>If you are a runner, it is highly possible that you are skipping breakfast entirely, or just relying on coffee and a slice of bread to get you out the door.</p><p>Personally, I am a huge believer in breakfast being the heaviest meal of my day , the core fuel that carries me through everything else. But how do you combine a fast morning with a heavy, nutritious meal?</p><p>I struggled with that question for years. I tried coffee and bread, traditional oatmeal, sandwiches, and plenty of other quick fixes. While those options technically got the job done, I’d find myself starving again two hours later. That’s a massive bummer when you are deep in a workflow or sitting in a meeting. I detest my energy levels dropping when I need them most, only for hunger to take over.</p><p>So, I came to a solution: <strong>The Power Smoothie</strong> (one of my friends affectionately calls it the “cement mix”). It requires almost zero prep time, minimal ingredients, and keeps you full for hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*0NaEC1CmTZ344AMA2QlVCg.png" /><figcaption>Morning smoothie</figcaption></figure><p>Ingredients:</p><ul><li><strong>The Base:</strong> 30–50g whole oats</li><li><strong>The Protein:</strong> 1 scoop of your favorite protein powder + a scoop of yogurt</li><li><strong>The Flavor:</strong> 1 banana or half a mango</li><li><strong>The Extras:</strong> A handful of nuts, a scattering of berries, and a squeeze of honey</li><li><strong>The Liquid &amp; Binder:</strong> Water and a pinch of salt (to balance the sweetness)</li></ul><p>The beauty of this is the efficiency. You throw all of these ingredients straight into a blender. It works best if your blender jar doubles as a portable travel bottle , meaning you can blend, grab it, and drink it on the go. No extra dishes, no wasted time.</p><p>This meal is so flexible that in case you feel you want to switch up the flavor of the smoothie some day, you can easily switch one ingredient for the other and it is good to go again.</p><p>This smoothie is the definition of a high-yield, low-maintenance routine. It gives me the heavy fueling I need without sacrificing a single minute of my morning momentum.</p><p>With this routine, you get a fast morning, a heavy meal, and a genuinely great start to your day. Give it a mix, grab your keys, and let me know if it keeps you powered through your morning meetings.</p><p>Let me know if you try this out, or if you have your own variation to keep your mornings efficient. What’s your go-to “run-out-the-door” fuel? Dropping a comment below is highly appreciated!</p><p>Until the next kitchen shenanigan!</p><p><em>For more kitchen shenanigans, feel free to follow along.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a65539987cbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A thought popped up then I built a real time Computer Vision system]]></title>
            <link>https://medium.com/@piyushkumarsingh.nmims/a-thought-popped-up-then-i-built-a-real-time-cv-system-23f6014c8274?source=rss-1adb855069a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/23f6014c8274</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Piyush Kumar Singh]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 15:39:10 GMT</pubDate>
            <atom:updated>2026-06-05T17:26:54.413Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometimes one random thought shows up and suddenly you are deep in a build. That is exactly how this project started.</p><p>The thought was simple: can I build a real-time system that tracks pose, hands, face, and holistic signals, and make it reliable outside a perfect demo video?</p><h4>The Real Problem</h4><p>Most CV demos look amazing for a few seconds. Then real life happens: lighting changes, movement gets fast, body parts go out of frame, and landmarks jitter.</p><p>The model still outputs points, but the behavior gets noisy. And once behavior is noisy, people stop trusting it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*9Nmhay-Kw35FYopbeq8PbQ.gif" /><figcaption>Real-time multi-modal tracking in practical conditions.</figcaption></figure><h4>What I Built</h4><p>I built a multi-modal real-time tracking pipeline with pose tracking, hand tracking, face tracking, and holistic coordination across all three.</p><p>The big shift for me was this: rendering landmarks is the easy part. Making stable decisions from noisy landmarks is the real challenge.</p><h4>How The Pose Tracking Actually Works</h4><p><em>Under the hood, the core stack is:</em></p><p>- Media Pipe for landmark inference (pose, hand, face, holistic)</p><p>- FastAPI backend for low-latency detection endpoints</p><p>- A lightweight frontend loop for camera capture, visualization, and control</p><p><em>For pose specifically, each frame goes through this flow:</em></p><p>1. Camera frame is captured in the browser.</p><p>2. Frame is sent to the backend detector endpoint.</p><p>3. MediaPipe Pose returns normalized landmarks with confidence.</p><p>4. Low-confidence points are filtered.</p><p>5. Temporal smoothing is applied to reduce jitter.</p><p>6. Landmarks + connections are returned for rendering and downstream logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OpeQ7Lif4mcCGsfj0cSxrg.png" /><figcaption>UI with camera switched off</figcaption></figure><p><em>One important design choice: </em><br>landmarks are treated as signals, not final decisions.</p><p>That means all product-level behavior (state changes, rep counting, alerts) sits on top of confidence thresholds + temporal logic, instead of trusting one raw frame.</p><p>In practice, this architecture gives a good balance:</p><p>- Fast enough for real-time interaction</p><p>- Stable enough to avoid noisy UX</p><p>- Modular enough to extend into exercise classification and coaching</p><h4>What Broke First</h4><p>Version one looked cool and behaved badly.</p><p>Main failures:</p><p>1. Jitter triggered false state changes.</p><p>2. Low-confidence frames polluted decision flow.</p><p>3. Single-frame logic overreacted.</p><p>4. Holistic mode added context but increased complexity and latency pressure.</p><p>That was the turning point. I stopped optimizing for “looks nice in a clip” and started optimizing for “works consistently.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*muGgHH8CjKfjshTZ6prFSQ.jpeg" /><figcaption>Peace and Thumbs up sign</figcaption></figure><h4>What Actually Improved It</h4><p>Four changes made the biggest difference:</p><p>1. Confidence-aware filtering</p><p>Only trust critical signals when confidence is high enough.</p><p>2. Temporal smoothing</p><p>Reduce noise without making the system feel sluggish.</p><p>3. State-based transitions</p><p>Use persistence over time, not one-frame decisions.</p><p>4. Cross-signal validation</p><p>In holistic mode, validate decisions with multiple signals.</p><h4>Why This Is Useful</h4><p>This is more than a visual demo. It is a practical base for exercise tracking, movement analysis, gesture interaction, and multi-modal human-signal products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*WzMVzN5lueFWypozcoOeIA.jpeg" /><figcaption>Face tracking</figcaption></figure><h4>Where I Want to Take It Next</h4><p>The next step is turning this into a real exercise tracker and coaching assistant.</p><p>To get there, I need three things:</p><p>1. Build a strong exercise classifier.</p><p>2. Collect better quality and more diverse exercise data.</p><p>3. Add a coaching layer that uses pose signals plus an LLM.</p><h4>Intended flow:</h4><p>- Pose and temporal features detect what the body is doing.</p><p>- A classifier identifies which exercise is being performed.</p><p>- An LLM converts structured signals into natural coaching feedback.</p><p>If that works well, the system can provide rep quality hints, form correction prompts, and session-level coaching guidance.</p><h4>Caveats I’m Thinking About Early</h4><p>This direction is exciting, but it comes with real caveats:</p><p>1. CV can run in real time, but LLM responses are usually slower.</p><p>So the LLM should run on events (rep complete, phase change, periodic summary), not every frame.</p><p>2. Good exercise data is limited.</p><p>Public datasets exist, but high-quality form-labeled data for coaching is harder to find.</p><p>3. Product reliability needs layered design.</p><p>The real-time loop should stay lightweight, while the coaching loop can be slightly delayed.</p><h4>Practical architecture direction:</h4><p>- Fast loop: CV + classifier (real-time)</p><p>- Slow loop: LLM feedback (near-real-time)</p><h4>Takeaways for Builders</h4><p>1. Landmarks are raw signals, not intelligence.</p><p>2. Single-frame rules break quickly in the real world.</p><p>3. Confidence should drive decision quality.</p><p>4. Smoothing is a balance between jitter and lag.</p><p>5. Holistic tracking is powerful when complexity is managed deliberately.</p><p>This started as a spontaneous build. Now it is slowly turning into a serious foundation for an exercise-tracking and coaching system.</p><p>If you are building in pose estimation, fitness AI, or multimodal CV, I would love to connect and compare approaches.</p><p>In case you might want to try on the <a href="https://github.com/PiyushSinghKumar/PoseAI">code</a>, Happy to receive feedback and comments.<br>Reach out to me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23f6014c8274" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Dashboard That Actually Loads Fast (Drill-Down with Pre-Aggregation)]]></title>
            <link>https://medium.com/@piyushkumarsingh.nmims/building-a-dashboard-that-actually-loads-fast-drill-down-with-pre-aggregation-34c3818fcc30?source=rss-1adb855069a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/34c3818fcc30</guid>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Piyush Kumar Singh]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 11:36:02 GMT</pubDate>
            <atom:updated>2026-02-14T11:36:02.270Z</atom:updated>
            <content:encoded><![CDATA[<p>The secret isn’t complex optimization, it’s pre-aggregating everything</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P9wHZfmFmypb8wCrQscSog.jpeg" /></figure><h4>The Goal</h4><p>I have 100 million transactions sitting in my lakehouse. Now I need to visualize them.</p><p>Users want:</p><ul><li>Overview: All years, regional breakdowns, category analysis</li><li>Yearly drill-down: Select a year, see monthly breakdown</li><li>Monthly drill-down: Select a month, see daily sales</li><li>Weekly drill-down: Select a week, see day-by-day performance</li></ul><p>And it needs to:</p><p>✅ Load quickly with minimal wait time<br>✅ Render charts smoothly<br>✅ Work on localhost (no cloud required)<br>✅ Handle filter changes responsively</p><p>Most people would reach for:</p><ul><li>Tableau (expensive, requires license)</li><li>PowerBI (Windows-heavy, Microsoft ecosystem)</li><li>Looker (cloud-only, complex setup)</li></ul><p>I chose <strong>Dash</strong> (Python, free, runs anywhere).</p><p>Here’s why it worked and how I made it fast.</p><h4>The Problem Everyone Hits</h4><p>First attempt (what everyone tries):</p><p>Loading all 100M transactions, filtering on every user interaction, aggregating every time.</p><p><em>Result</em>: Slow, unresponsive dashboard with long wait times.</p><p>Why it’s slow:</p><ul><li>Loading 100M rows</li><li>Filtering on every interaction</li><li>Aggregating on every filter change</li><li>Rendering after every calculation</li></ul><p><strong>Every. Single. Filter. Change.</strong></p><p>This doesn’t scale.</p><p>The Solution: Pre-Aggregation (Gold Layer)</p><p>Remember the Gold layer from Article 1? This is where it pays off.</p><p>Instead of aggregating 100M rows on every dashboard load, I pre-compute everything:</p><p>Gold layer files (total 50 MB vs 1.3 GB Silver):</p><ul><li>yearly_sales.parquet -&gt; 6 rows</li><li>monthly_sales.parquet -&gt; 72 rows</li><li>weekly_sales.parquet -&gt; 312 rows</li><li>daily_sales.parquet -&gt; 2,190 rows</li><li>sales_by_region.parquet -&gt; 96 rows</li><li>sales_by_category.parquet -&gt; 66 rows</li></ul><p>Now the dashboard loads tiny pre-aggregated files instead of querying 100M rows. Filter changes update instantly because we’re filtering 6–72 rows, not millions.</p><p><em>Total</em>: Loads instantly instead of freezing.</p><p>That’s the power of pre-aggregation.</p><h4>Part 1. Choosing Dash Over Alternatives</h4><p>I evaluated several dashboard frameworks:</p><p><strong>Streamlit<br></strong>Tried it. Too limiting.</p><p>Streamlit is great for quick demos, but:<br>❌ Limited layout control (everything is vertical)<br>❌ Full page reload on every interaction<br>❌ Hard to customize styling</p><p><strong>Gradio</strong><br>Great for ML, wrong for analytics.</p><p>Gradio excels at model demos, not dashboards.</p><p><strong>Dash</strong><br>Winner. Full control, production-ready.</p><p>✅ Complete layout control (CSS Grid, Bootstrap)<br>✅ Callback-based (only update what changes)<br>✅ Plotly integration (best Python charts)<br>✅ Used by Fortune 500 companies</p><p><em>I chose Dash.</em></p><h4>Part 2. The Architecture (Modular, Not Monolithic)</h4><p>I didn’t write one giant 2,000-line `dashboard.py` file.</p><p>Instead, I split it into logical modules:</p><pre>analysis/<br>├── retail_dashboard.py (50 lines - entry point)<br>└── dashboard_components/<br> ├── data_loaders.py (100 lines - load Parquet files)<br> ├── charts.py (400 lines - create charts)<br> ├── filters.py (50 lines - filter UI)<br> ├── layout.py (150 lines - page structure)<br> └── callbacks.py (350 lines - interactivity<br></pre><p>Why this matters:<br>✅ Easy to test individual components<br>✅ Clear separation of concerns<br>✅ Multiple people can work in parallel<br>✅ Easier to debug (“chart bug? Check charts.py”)</p><p>The main file is tiny just imports, layout setup, callback registration, and server start. 12 lines of code total.</p><h4>Part 3. The 4-Level Drill-Down</h4><p>Level 1: Overview (All Years)</p><p>Shows everything:<br>- Yearly trend (2020–2026)<br>- Regional breakdown (16 German states)<br>- Category breakdown (11 categories)</p><p>No filters active users see the big picture.</p><p>Data loaded: 6 + 96 + 66 = 168 rows (tiny!)</p><p>Level 2: Yearly (Select Year → See Months)</p><p>User clicks “<em>Yearly Drill-Down</em>” tab, selects “<em>2024</em>”.</p><p>Dashboard shows:<br>- Monthly breakdown for 2024 (12 bars)<br>- Regional sales for 2024<br>- Category sales for 2024</p><p>Data loaded: 12 + 16 + 11 = 39 rows (filtered from Gold layer, updates instantly)</p><p>Level 3: Monthly (Select Month → See Days)</p><p>User clicks “<em>Monthly Drill-Down</em>”, selects “<em>December 2024</em>”.</p><p>Dashboard shows:<br>- Daily sales for December 2024 (31 days)<br>- Regional/category breakdowns</p><p>Data loaded: ~31 rows (one month of daily data, very fast)</p><p>Level 4: Weekly (Select Week → See Days)</p><p>User clicks “<em>Weekly Drill-Down</em>”, selects “<em>Week 50, 2024</em>”.</p><p>Dashboard shows:<br>- Daily sales for that specific week (7 days)<br>- Regional/category breakdowns</p><p>Data loaded: ~7 rows (nearly instant)</p><p>The pattern: As you drill down, you load <strong>less data</strong>, so it gets <strong>faster</strong>.</p><h4>Part 4: Smart Filtering (Auto-Selection)</h4><p>One UX detail that matters: auto-selecting the latest values.</p><p>Bad UX (what most dashboards do):</p><ul><li>User opens dashboard</li><li>All filters empty</li><li>User has to manually select year, then month, then week</li><li>3 clicks just to see anything useful</li></ul><p>Good UX (what I built):</p><ul><li>User opens dashboard</li><li>Latest year auto-selected (2024)</li><li>Latest month auto-selected (December)</li><li>Latest week auto-selected (Week 52)</li><li>User sees data immediately, can change if needed</li></ul><p><strong>How it works</strong>: Callbacks that populate and set defaults:</p><p>When user switches to “<em>Yearly</em>” tab:</p><ul><li>Load available years from Gold layer</li><li>Sort years</li><li>Set dropdown value to `years[-1]` (latest)</li><li>Trigger chart update</li></ul><p>When user switches to “<em>Monthly</em>” tab:</p><ul><li>Load available months for selected year</li><li>Sort months</li><li>Set dropdown value to `months[-1]` (latest)</li><li>Trigger chart update</li></ul><p>Users appreciate this. It feels responsive and intelligent.</p><h4>Part 5: Performance Optimizations</h4><p>1. Callback Efficiency</p><p>Dash re-runs callbacks on every input change. Optimize by <strong>combining outputs</strong>:</p><p><strong>Bad approach</strong>: Two separate callbacks that both load the same data file, wasteful!</p><p><strong>Good approach</strong>: One callback with multiple outputs data loads once, both charts update.</p><p>2. Filter Visibility</p><p>Show only relevant filters for each tab:</p><ul><li>Overview tab: No filters (show all data)</li><li>Yearly tab: Year filter only</li><li>Monthly tab: Year + Month filters</li><li>Weekly tab: Year + Week filters</li></ul><p>This keeps the UI clean and prevents confusion.</p><p>3. Chart Type Selection</p><p>Single value→ Bar chart<br>Multiple values → Line chart</p><p>Example:</p><ul><li>Overview showing all years (2020–2026) → Line chart (trend over time)</li><li>Yearly showing one year → Bar chart (12 discrete months)</li></ul><p>Auto-selecting the right chart type makes insights clearer.</p><h4>The Results: Responsive Performance</h4><p>The dashboard delivers a smooth user experience:</p><p>Initial Load<br>The overview page loads 168 pre-aggregated rows (yearly, regional, and category data from Gold layer) — a tiny dataset compared to the 100M row Silver layer.</p><p>Filter Changes<br>Switching between years, months, or weeks updates the dashboard by filtering small Gold layer files. Since we’re working with dozens or hundreds of rows instead of millions, updates are responsive.</p><p>Tab Switches<br>Each drill-down level works with progressively smaller datasets:</p><ul><li>Overview: 168 rows</li><li>Yearly: ~39 rows (filtered)</li><li>Monthly: ~31 rows (one month)</li><li>Weekly: ~7 rows (one week)</li></ul><p>The key: Pre-aggregation means we never query 100M rows during dashboard interaction. We always work with small, pre-computed Gold layer files.</p><h4>What I Learned</h4><p><strong>1. Pre-Aggregation &gt; Real-Time Everything</strong></p><p>Yes, I’m computing aggregations in advance. But the user experience is <em>dramatically better</em>:</p><ul><li>Dashboards work with small datasets (dozens of rows, not millions)</li><li>No complex query optimization needed</li><li>Predictable, responsive performance</li></ul><p>The Gold layer is only 50 MB. Refreshing it processes efficiently. The trade-off is absolutely worth it.</p><p><strong>2. Modular Architecture Pays Off</strong></p><p>When I found a bug in the monthly drill-down chart, I knew exactly where to look: `dashboard_components/charts.py`.</p><p>When I wanted to add a new filter, I edited one file: `dashboard_components/filters.py`.</p><p>Single-file dashboards become unmaintainable fast.</p><p><strong>3. UX Details Matter</strong></p><p>Auto-selecting latest values seems like a small thing.</p><p>But users notice -&gt; “This actually shows me recent data by default”</p><p>Little details create big differences.</p><p><strong>4. Dash is Production-Ready</strong></p><p>When I first tried Dash I was worried it would feel “toy-like” compared to Tableau. It doesn’t.</p><p>With Bootstrap Components, the dashboard looks professional. Performance is excellent. Deployment is simple (it’s just a Flask app).</p><h4>Try It Yourself</h4><p>The code for the whole project is on github<br><a href="https://github.com/PiyushSinghKumar/retail_lakehouse">github.com/PiyushSinghKumar/retail_lakehouse</a></p><h4>What’s Next</h4><p>This completes the 4-part series! You now have:<br>✅ A medallion lakehouse architecture<br>✅ Realistic synthetic data generation<br>✅ Orchestration with Airflow and Prefect<br>✅ An interactive dashboard with drill-downs</p><p>Thanks for following this series! If you build something with these techniques, I’d love to hear about it in the comments.</p><p>Questions about dashboard development? Drop them below! 👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34c3818fcc30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prefect vs Airflow : An honest comparison]]></title>
            <link>https://medium.com/@piyushkumarsingh.nmims/prefect-vs-airflow-an-honest-comparison-28f91be460e6?source=rss-1adb855069a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/28f91be460e6</guid>
            <category><![CDATA[knowledge]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Piyush Kumar Singh]]></dc:creator>
            <pubDate>Sun, 01 Feb 2026 15:14:20 GMT</pubDate>
            <atom:updated>2026-02-01T15:15:34.158Z</atom:updated>
            <content:encoded><![CDATA[<h3>Prefect vs Airflow : An honest comparison</h3><p><em>A developer’s honest comparison after implementing the exact same workflow in both orchestrators</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*FJGbdt_yTCV-9cNa67JKQg.png" /></figure><h4>The Experiment</h4><p>I had a data pipeline: ingest 100M transactions, clean them, aggregate them.</p><p>Simple, linear flow: Bronze → Silver → Gold.</p><p>But I couldn’t decide: <strong>Prefect </strong>or <strong>Airflow</strong>?</p><p>Everyone has opinions. Blog posts claim one is “better.” But most comparisons are:</p><ul><li>Outdated (comparing Airflow 1.x to Prefect 2.x)</li><li>Biased (written by vendors)</li><li>Theoretical (no real code)</li></ul><p>So I did something different: <strong>I built the exact same pipeline in both</strong>.</p><p>Same data. Same transformations. Same outputs. Different orchestrator.</p><p>Here’s what I discovered.</p><h4>Round 1: Getting Started</h4><p><strong>Airflow Setup</strong></p><p>Airflow requires more setup steps to get started:</p><ul><li>Install Airflow</li><li>Initialize a database (required even for local development)</li><li>Create an admin user</li><li>Start the standalone server</li><li>Open browser and authenticate</li></ul><p>The UI requires login credentials even for local development.</p><p><em>Experience</em>: Multi-step process with database initialization</p><p><strong>Prefect Setup</strong></p><p>Prefect has a simpler getting-started experience:</p><ul><li>Install Prefect</li><li>Write flows as decorated Python functions</li><li>Run directly with python pipeline.py</li><li>UI is optional (start with prefect server start if desired)</li></ul><p>No authentication required for local development.</p><p><em>Experience</em>: Minimal setup, runs immediately</p><p><em>Winner</em>: <em>Prefect</em><strong>, </strong>Much faster to start</p><h4>Round 2: Writing the Pipeline</h4><p><strong>The Airflow Version</strong></p><p>Airflow requires specific structure:</p><ul><li>DAG context manager with configuration</li><li>default_args dictionary for common settings</li><li>Wrapping functions in operators (PythonOperator)</li><li>Task dependencies with &gt;&gt; operator</li><li>Files placed in specific DAG directory</li></ul><p>What I like:</p><ul><li>✅ Clear task dependencies (&gt;&gt; operator)</li><li>✅ Built-in retry logic</li><li>✅ Schedule syntax is clean</li></ul><p>What frustrates me:</p><ul><li>❌ Significant boilerplate required</li><li>❌ Must wrap everything in operators</li><li>❌ DAG file must be in specific directory</li><li>❌ Changes require DAG refresh delay</li></ul><p><strong>The Prefect Version</strong></p><p>Prefect uses a decorator-based approach:</p><ul><li>Decorate functions with @task</li><li>Wrap workflows in @flow</li><li>Define dependencies with wait_for</li><li>Run like normal Python scripts</li></ul><p>What I like:</p><ul><li>✅ Looks like normal Python</li><li>✅ Run with python pipeline.py</li><li>✅ Changes take effect immediately</li><li>✅ Easy to test locally</li></ul><p>What frustrates me:</p><ul><li>❌ wait_for is less elegant than &gt;&gt;</li><li>❌ Fewer built-in operators</li></ul><p><em>Winner: Prefect </em>Feels like Python, not configuration</p><h4>Round 3: Development Experience</h4><p><strong>Testing in Airflow</strong></p><p>Testing individual tasks requires:</p><ul><li>Using CLI commands (airflow tasks test)</li><li>Providing execution dates for tests</li><li>Relying on logs for debugging (debugger not easily available)</li><li>Testing entire DAGs with separate commands</li></ul><p>The testing workflow requires Airflow-specific knowledge.</p><p><strong>Testing in Prefect</strong></p><p>Testing works like normal Python:</p><ul><li>Add if __name__ == &quot;__main__&quot; block</li><li>Run with python pipeline.py</li><li>Use standard debugger (pdb, IDE breakpoints)</li><li>Test individual tasks or full flows</li></ul><p>Standard Python debugging tools work out of the box.</p><p><strong><em>Winner</em></strong><em>: </em><strong><em>Prefect</em></strong><em> </em>Normal debugging, normal testing</p><h4>Round 4: The UI Experience</h4><p><strong>Airflow UI</strong></p><p>Strengths:</p><ul><li>Beautiful Gantt chart showing task timing</li><li>Tree view of historical runs</li><li>Extensive configuration options</li><li>Variables and connections UI</li></ul><p>Weaknesses:</p><ul><li>Overwhelming for simple pipelines</li><li>Requires authentication (even locally)</li><li>4–5 clicks to see task logs</li><li>Heavy UI (lots of tabs and menus)</li></ul><p><em>My feeling</em>: Built for data teams, not individuals.</p><p><strong>Prefect UI</strong></p><p>Strengths:</p><ul><li>Clean, modern interface</li><li>Real-time flow visualization</li><li>2 clicks to see logs</li><li>No authentication required locally</li></ul><p>Weaknesses:</p><ul><li>Fewer features than Airflow</li><li>Less mature ecosystem</li><li>Some advanced Airflow features missing</li></ul><p><em>My feeling</em>: Built for developer happiness.</p><p><strong><em>Winner: Tie</em></strong> Airflow has more features, Prefect is easier to use</p><h4>Round 5: Performance</h4><p>I ran both pipelines multiple times to compare performance:</p><p><em>Results (100M transactions)</em></p><p>Both orchestrators completed the pipeline in roughly the same time. The actual data processing (Bronze → Silver → Gold transformations) dominates the runtime, not the orchestration overhead.</p><p><strong>Orchestration overhead</strong>:</p><ul><li>Airflow: Higher overhead from scheduler polling and task queuing</li><li>Prefect: Lower overhead with direct flow execution</li></ul><p>For simple linear pipelines like mine, <strong>Prefect has marginally less overhead</strong>. For complex DAGs with many parallel tasks, Airflow’s scheduler might actually be more efficient.</p><p><strong><em>Winner</em></strong><em>: </em><strong><em>Tie</em></strong><em> </em>Performance differences are negligible compared to actual data processing time</p><h4>Round 6: Deployment</h4><p><strong>Deploying Airflow (Docker)</strong></p><p>Airflow needs:</p><ul><li>Two containers (Airflow server + PostgreSQL)</li><li>Database initialization</li><li>Admin user creation</li><li>4–5 setup commands</li></ul><p><strong>Deploying Prefect (Docker)</strong></p><p>Prefect needs:</p><ul><li>One container (Prefect server with built-in SQLite)</li><li>One command to start</li></ul><p><strong><em>Winner</em></strong><em>: </em><strong><em>Prefect</em></strong><em> </em>Simpler deployment</p><h3><strong>Round 7: When Things Go Wrong</strong></h3><p><strong>Airflow Error Handling</strong></p><p>Task fails. I see it in UI. Click task. View logs. Scroll through 500 lines of Airflow internals. Finally find my error.</p><p>Retry logic is great, but debugging requires digging through logs.</p><p><strong>Prefect Error Handling</strong></p><p>Task fails. Exception appears in terminal (if running locally) or UI. Clear stack trace. Easy to diagnose.</p><p><strong><em>Winner</em></strong><em>: </em><strong><em>Prefect</em></strong><em> </em>Clearer error messages</p><h4>The Honest Verdict</h4><p><strong>Choose Airflow if:</strong></p><p><strong><em>You have a team</em></strong> Airflow’s maturity shines with multiple people</p><ul><li>Built-in authentication and RBAC</li><li>Extensive provider ecosystem (AWS, GCP, Snowflake, etc.)</li><li>Battle-tested at thousands of companies</li></ul><p><strong><em>You have complex DAGs</em> </strong>Airflow excels at:</p><ul><li>Dynamic task generation</li><li>Complex branching and conditionals</li><li>SLA monitoring</li><li>Task-level timeouts</li></ul><p><strong><em>You’re already invested</em></strong><em> </em>Switching has cost:</p><ul><li>Team knowledge</li><li>Existing DAGs</li><li>Infrastructure</li></ul><p><strong>Choose Prefect if:</strong></p><p><strong><em>You value developer experience</em></strong> Prefect feels like modern Python</p><ul><li>Fast iteration (no DAG refresh delay)</li><li>Normal debugging (breakpoints work!)</li><li>Less boilerplate</li></ul><p><strong><em>You have simple-to-moderate pipelines</em></strong> Linear flows, light branching</p><ul><li>My pipeline is perfect for Prefect</li><li>Complex enterprise workflows might need Airflow</li></ul><p><strong><em>You’re starting fresh</em></strong><em> </em>No legacy to maintain</p><ul><li>Modern architecture</li><li>Active development (Prefect 3.0 just launched)</li></ul><h4>My Choice for This Project</h4><p>I chose <strong>Prefect</strong> because:</p><ol><li><strong>Development speed</strong> I iterate 5x faster</li><li><strong>Simplicity</strong> My pipeline doesn’t need Airflow’s complexity</li><li><strong>Python-first</strong> Feels natural</li></ol><p>But if I were at a company with 100+ DAGs and a data engineering team of 10+, I’d choose <strong>Airflow</strong> for its maturity and ecosystem.</p><h4>The Surprising Insight</h4><p>Both tools are <strong>excellent</strong>. The “Airflow vs Prefect” debate is like “React vs Vue” both work great, choice depends on your context.</p><p><strong><em>The real lesson</em></strong>: Separate orchestration from business logic.</p><p>Both my Airflow and Prefect implementations use the exact same transformation code. The project structure keeps framework-agnostic pipeline logic (encapsulated in a shared pipeline module) separate from orchestration wrappers.</p><p>This means:</p><ul><li>✅ Easy to switch orchestrators</li><li>✅ Can run both in parallel (testing)</li><li>✅ Business logic is testable without orchestrator</li></ul><p><strong><em>Pro tip</em></strong>: Always decouple transformation logic from orchestration.</p><h4>Try Both Yourself</h4><p>The project includes both implementations. You can:</p><ol><li>Run the Airflow version</li><li>Run the Prefect version</li><li>Compare performance on your hardware</li><li>Decide which fits your needs</li></ol><h4>What’s Next in This Series</h4><p>This is <strong>Part 3</strong> of a 4-part series:</p><ul><li><a href="https://medium.com/@piyushkumarsingh.nmims/building-a-production-ready-data-lake-house-on-your-laptop-ac359d7e86a5">Building a production ready data lake on your laptop</a></li><li><a href="https://medium.com/@piyushkumarsingh.nmims/how-i-generated-100-million-realistic-transactions-d85bfd83551b?postPublishedType=initial">Synthetic Data Generation</a></li><li><strong>Prefect vs Airflow </strong>(you just read this)</li><li>Interactive Dashboards Building drill-down analytics with Dash</li></ul><h3>🔗 Project Repository</h3><p>Both Airflow and Prefect implementations are on GitHub:</p><p><a href="https://github.com/PiyushSinghKumar/retail_lakehouse"><em>github.com/PiyushSinghKumar/retail_lakehouse</em></a></p><p>See /airflow and /prefect directories.</p><p><em>Follow for Part 4 where I build an interactive dashboard with 4-level drill-downs using Dash and Plotly.</em></p><p><em>Which orchestrator do you prefer? Comment below!</em> 👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28f91be460e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Generated 100 Million Realistic Transactions]]></title>
            <link>https://medium.com/@piyushkumarsingh.nmims/how-i-generated-100-million-realistic-transactions-d85bfd83551b?source=rss-1adb855069a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d85bfd83551b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[synthetic-data]]></category>
            <category><![CDATA[synthetic-data-generation]]></category>
            <category><![CDATA[fakers]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Piyush Kumar Singh]]></dc:creator>
            <pubDate>Fri, 23 Jan 2026 21:57:58 GMT</pubDate>
            <atom:updated>2026-01-23T21:57:58.746Z</atom:updated>
            <content:encoded><![CDATA[<h3>And Why It’s Awesome</h3><p><em>The surprising challenge of creating fake data that looks real as well as complete with seasonal patterns, holiday dips, and economic trends.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*DqBc0DHK9JmK3ZgWii6ZtQ.png" /></figure><p><strong>The Problem Nobody Talks About</strong></p><p>You want to build a data pipeline. Great! But where’s your data?</p><p>“Just use real data,” they say. Except:</p><p><strong>Real data is sensitive: </strong>Customer names, credit cards, addresses</p><p><strong>Real data is regulated: </strong>GDPR, CCPA, compliance nightmares</p><p><strong>Real data is stuck: </strong>Behind VPNs, approvals, legal reviews</p><p>So you need <strong>synthetic data</strong>. But here’s the trap most people fall into:</p><p>Creating random data with uniform distributions, dates picked randomly, amounts picked randomly, no patterns whatsoever. This creates data that’s <strong>technically correct but obviously fake.</strong></p><p><strong>No seasonal patterns</strong> (December looks like July), <strong>No economic trends</strong> (2020 sales = 2024 sales), <strong>No realistic behavior </strong>(every day has equal transactions)</p><p>When you analyze it, you immediately know it’s synthetic. Patterns don’t emerge. Insights don’t appear. I needed something better.</p><p><strong>The Goal: Indistinguishable from Reality</strong></p><p>I wanted to generate data so realistic that:</p><p>✅ Sales peak in December (Christmas shopping)</p><p>✅ Sales dip on holidays (stores close early)</p><p>✅ Revenue grows 15% year-over-year (normal business growth)</p><p>✅ Summer has more traffic than winter</p><p>✅ Transaction amounts follow real distributions (not uniform)</p><p>And I needed <strong>100 million transactions</strong> spanning 6 years (2020–2026) across 500 stores.</p><p>Here’s how I did it.</p><p><strong>Part 1: The Easy Stuff (Stores and Products)</strong></p><p><strong>Generating 500 Stores</strong></p><p>I needed realistic German retail locations. Enter <strong>Faker</strong>. It is a library that generates fake-but-realistic data in 50+ languages. Setting it to German locale (`de_DE`) gives me:</p><p>Real German cities, Real postal codes, Real street names, 500 stores across 16 German states, distributed by population.Each store got a random chain name (REWE, Edeka, ALDI, Lidl) and a location.</p><p><strong>Generating 50,000 Products</strong></p><p>Products needed to make sense for their categories:</p><p><strong>Dairy products</strong> (Molkereiprodukte):</p><ul><li>Vollmilch 3.5% (whole milk) €0.89-€1.99</li><li>Butter gesalzen (salted butter) €1.49-€3.99</li><li>Schwarzbrot (dark bread) €1.49-€3.99</li><li>Brötchen (rolls) €0.29-€0.99</li></ul><p>I created realistic German product names and category-appropriate pricing. Milk doesn’t cost €50. Electronics don’t cost €0.99.</p><p><strong>Part 2: The Hard Part (Realistic Transactions)</strong></p><p>Here’s where it gets interesting. I needed 100 million transactions distributed across 6 years with realistic patterns.</p><p><strong>Challenge 1: Year-Over-Year Growth</strong></p><p>Real businesses don’t have flat sales. They grow (or shrink).</p><p>I wanted <strong>15% year-over-year growth</strong>:</p><ul><li>2020: 12.5M transactions (baseline)</li><li>2021: 14.4M transactions (+15%)</li><li>2022: 16.5M transactions (+15%)</li><li>2023: 19.0M transactions (+15%)</li><li>2024: 21.9M transactions (+15%)</li><li>2025: 25.2M transactions (+15%)</li><li>2026: ~3M transactions (partial year, Jan only)</li></ul><p>How do you distribute 100M transactions to match this pattern?</p><p><strong>The trick</strong>: Time-weighted sampling.</p><p>Instead of picking random dates uniformly, I calculated a <strong>weight for each day</strong> based on how many years had passed:</p><pre>weight = (1 + growth_rate) ^ years_since_start</pre><p>Days in 2024 have ~2x the weight of days in 2020. When I sample dates, 2024 naturally gets twice as many transactions.</p><p><strong>Challenge 2: Seasonal Patterns</strong></p><p>December should be busy (Christmas shopping). January should be slow (post-holiday slump).</p><p>I created monthly multipliers based on German retail patterns:</p><ul><li><strong>December</strong>: 1.4× normal traffic (Christmas peak)</li><li><strong>July-August</strong>: 1.2× normal traffic (summer tourism)</li><li><strong>January</strong>: 0.7× normal traffic (post-holiday recovery)</li><li><strong>September</strong>: 0.85× normal traffic (back to school dip)</li></ul><p>These multipliers combine with the growth trend:</p><pre>final_weight = growth_weight × seasonal_multiplier</pre><p>Now December 2024 has the highest transaction probability. January 2020 has the lowest.</p><p><strong>Challenge 3: Holiday Effects</strong></p><p>German stores close early on public holidays. I needed to reflect this.</p><p>I loaded German holidays for 2020–2026:</p><ul><li>New Year’s Day (Jan 1)</li><li>Good Friday</li><li>Easter Monday</li><li>Christmas (Dec 25–26)</li><li>All regional holidays</li></ul><p>On holidays, I reduced traffic by <strong>20%</strong>:</p><pre>if is_holiday(date):<br>final_weight *= 0.8</pre><p>Now Christmas Day has fewer transactions than a regular December day — realistic!</p><p><strong>Challenge 4: Realistic Basket Sizes</strong></p><p>How many items do people buy per transaction?</p><p>I measured this at real supermarkets:</p><ul><li>Quick stops: 1–2 items (milk, bread)</li><li>Regular shops: 5–8 items (weekly groceries)</li><li>Big hauls: 15–20 items (monthly stock-up)</li></ul><p>Average: <strong>~3 items per transaction</strong></p><p>I used a <strong>Poisson distribution</strong> with λ=3. This naturally creates:</p><ul><li>Lots of 2–4 item transactions (most common)</li><li>Some 1-item quick stops</li><li>Rare 10+ item big shops</li></ul><p>Much more realistic than `random.randint(1, 10)`.</p><p><strong>The Results: Does It Look Real?</strong></p><p>Let’s validate the patterns in the generated data:</p><p><strong>Year-over-year growth check:</strong></p><p>The time-weighted sampling successfully creates consistent 15% year-over-year growth across all years (2020–2025), with 2026 showing partial year data.</p><p>✅ Compound growth pattern achieved</p><p><strong>Seasonality check:</strong></p><p>December shows roughly 2× the transaction volume of January, matching real retail patterns. Summer months (July-August) show elevated traffic, while post-holiday January shows the expected dip.</p><p>✅ Seasonal patterns match retail behavior</p><p><strong>Holiday effect check:</strong></p><p>Christmas Day and similar holidays show approximately 20% fewer transactions compared to surrounding non-holiday weekdays, creating realistic holiday dips without completely zeroing out (some stores stay open with reduced hours).</p><p>✅ Clear holiday effects without unrealistic gaps</p><p>The data <strong>looks real</strong>.</p><p><strong>The Performance Challenge</strong></p><p>Generating 100 million transactions isn’t instant. Memory management is critical.</p><p><strong>The Naive Approach (FAILS):</strong></p><p>Creating a huge list of all 100M transactions in memory, then converting to a DataFrame — this requires ~40GB of RAM and crashes on most laptops.</p><p><strong>My Approach (WORKS):</strong></p><p>Generate in <strong>batches of 1 million</strong>, write each batch to Parquet immediately, then concatenate the Parquet files. This keeps memory usage at ~4GB peak, working perfectly on a 16GB machine.</p><p><strong>What I Learned</strong></p><p><strong>1. Realism Requires Context</strong></p><p>Random data is easy. Realistic data requires understanding the <strong>domain</strong>:</p><ul><li>How do retail sales actually work?</li><li>When do people shop?</li><li>What’s a realistic basket size?</li></ul><p>I spent hours researching German retail patterns, holiday calendars, and shopping behavior.</p><p><strong>2. Distributions Matter</strong></p><p>The difference between `random.randint(1, 10)` and a Poisson distribution is huge. One looks random. The other looks human.</p><p><strong>3. Configurability Pays Off</strong></p><p>I initially hardcoded everything. Adding configuration took 2 hours but made the system <strong>10x more useful</strong>. I can now:</p><ul><li>Test different growth scenarios</li><li>Generate specific time windows</li><li>Disable patterns for testing</li><li>Simulate economic changes</li></ul><p><strong>4. Faker is a Game-Changer</strong></p><p>German cities, street names, company names — all from one line: `Faker(“de_DE”)`. I didn’t have to manually list 1,000 city names.</p><p><strong>Try It Yourself</strong></p><p>The data generator is fully open source. You can:</p><ul><li>Generate your own 100M transactions</li><li>Adjust all parameters (growth, seasonality, holidays)</li><li>Create different scenarios (recession, boom, uniform)</li></ul><p><strong>What’s Next in This Series</strong></p><p>This is <strong>Part 2</strong> of a 4-part series:</p><ul><li><a href="https://medium.com/@piyushkumarsingh.nmims/building-a-production-ready-data-lake-house-on-your-laptop-ac359d7e86a5">Building a production ready data lake on your laptop</a></li><li><strong>Synthetic Data Generation</strong> (you just read this)</li><li>Airflow vs Prefect Orchestrating the same pipeline with both tools</li><li>Interactive Dashboards Building drill-down analytics with Dash</li></ul><p><strong>🔗 Project Repository</strong></p><p>The complete data generation code is on GitHub:</p><p><a href="https://github.com/PiyushSinghKumar/retail_lakehouse"><strong><em>github.com/PiyushSinghKumar/retail_lakehouse</em></strong></a></p><p><em>Follow for Part 3 where I compare Airflow vs Prefect for orchestrating this exact pipeline.</em></p><p><em>Questions about data generation? Drop them in the comments!</em>👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d85bfd83551b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Production-Ready Data Lake house (On your laptop)]]></title>
            <link>https://medium.com/@piyushkumarsingh.nmims/building-a-production-ready-data-lake-house-on-your-laptop-ac359d7e86a5?source=rss-1adb855069a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac359d7e86a5</guid>
            <category><![CDATA[data-lakehouse]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Piyush Kumar Singh]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 23:12:03 GMT</pubDate>
            <atom:updated>2026-01-11T12:38:12.450Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>I Built a Data Lake house That Processes 100 Million Transactions on My Laptop</strong></p><p><em>And it runs on my laptop without Spark, Hadoop, or any distributed system*</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*43UoL95Iqmp85aYMaCa0_w.png" /></figure><p><strong>The Challenge That Started It All</strong></p><p>A few months ago, I asked myself a question: <strong>Can you build a production-ready data platform on a single machine?</strong></p><p>Not a toy project. Not a demo. A real system that handles:</p><p>- 100 million transactions</p><p>- 500 stores across Germany</p><p>- 50,000 products</p><p>- 6 years of historical data (2020–2026)</p><p>- Interactive dashboards with sub-second response times</p><p>And do it all without:</p><p>- ❌ Apache Spark</p><p>- ❌ Distributed databases</p><p>- ❌ Cloud data warehouses</p><p>- ❌ Kubernetes clusters</p><p>Just <strong>Python, smart architecture, and modern tools</strong>.</p><p>Spoiler: It worked. And it was faster than I expected.</p><p><strong>The Architecture: Why Medallion?</strong></p><p>I chose the <strong>medallion architecture</strong> a pattern popularized by Databricks that organizes data into three layers:</p><p>(Think of it like refining crude oil)</p><p>- <strong>Bronze</strong> = Crude oil (raw data, just extracted)</p><p>- <strong>Silver</strong> = Refined oil (cleaned, validated, ready for use)</p><p>- <strong>Gold</strong> = Premium fuel (optimized for specific purposes)</p><p>Each layer has a single responsibility, making the pipeline:</p><p>- <strong>Easy to debug</strong> Problems isolated to specific layers</p><p>- <strong>Easy to scale </strong>Reprocess only what’s needed</p><p>- <strong>Easy to understand </strong>New team members get it in 5 minutes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n-7k5aldfI3O10UnZsDO8w.png" /><figcaption>Architecture</figcaption></figure><p><strong>Act 1: The Bronze Layer (Raw Ingestion)</strong></p><p><strong>The Problem</strong>: Storing 100 million rows as CSV would take ~3GB or a database will require more effort then required.</p><p><strong>The Solution</strong>: Generate directly to Parquet with aggressive compression.</p><p>I configured the data generator to write <strong>Parquet</strong> files directly using <strong>Zstandard compression level 9</strong>.</p><p><strong>The Efficiency Win</strong>:</p><p>- <strong>CSV Equivalent</strong>: ~3.0 GB (estimated)</p><p>- <strong>Actual Parquet</strong>: 1.2 GB (60% smaller!)</p><p>- Columnar format enables reading only needed columns</p><p>- Reduced memory footprint</p><p>The Bronze layer consists of these raw Parquet files. They contain the data exactly as generated messy, potentially duplicated, but efficiently stored.</p><p>Why keep a raw layer? Because if I mess up my cleaning logic in the next step, I can always re-read the Bronze files without regenerating 100M transactions.</p><p><strong>Act 2: The Silver Layer (Data Quality)</strong></p><p><strong>The Problem</strong>: Raw data is messy. Duplicates, invalid values, missing fields.</p><p><strong>The Solution</strong>: Clean it once, use it everywhere.</p><p>The Silver layer is where I apply all data quality rules:</p><p><strong>What gets fixed</strong>:</p><p>- ✅ <strong>Duplicates removed</strong> Found 127,000 duplicate transactions (0.13%)</p><p>- ✅ <strong>Invalid data filtered</strong> Removed negative quantities, zero prices</p><p>- ✅ <strong>Derived fields added</strong> Year, month, week extracted from dates</p><p>- ✅ <strong>Business rules validated</strong> Line totals match transaction totals</p><p>Here’s the interesting part: I used <strong>Polars</strong> instead of Pandas.</p><p>Everyone uses Pandas. It’s the standard. But Polars is <strong>dramatically faster</strong> for this workload.</p><p>Why Polars wins:</p><p>- <strong>Lazy evaluation</strong> Optimizes entire query before execution</p><p>- <strong>Parallel processing</strong> Uses all CPU cores by default</p><p>- <strong>Columnar operations</strong> Native support for Parquet</p><p>- <strong>Memory efficient</strong> Processes data in chunks</p><p>For operations like filtering, grouping, and joining on 100M rows, Polars significantly outperforms Pandas. The Silver layer processes efficiently without memory issues.</p><p><strong>Act 3: The Gold Layer (Pre-Aggregation Magic)</strong></p><p><strong>The Problem</strong>: Users want dashboards that load instantly. But aggregating 100M rows on every page load? Too slow.</p><p><strong>The Solution</strong>: Pre-compute everything.</p><p>This is where the magic happens. Instead of aggregating on-demand, I create small, fast tables:</p><p>- yearly_sales.parquet 6 years of data → 6 rows</p><p>- monthly_sales.parquet Monthly breakdown → 72 rows</p><p>- weekly_sales.parquet Weekly breakdown → 312 rows</p><p>- daily_sales.parquet Daily breakdown → 2,190 rows</p><p>- sales_by_region.parquet 16 regions × 6 years → 96 rows</p><p>- sales_by_category.parquet 11 categories × 6 years → 66 rows</p><p><strong>Total Gold layer size</strong>: 50 MB (vs. 1.3 GB Silver)</p><p>Now when someone opens the dashboard:</p><p>- <strong>Before</strong>: Query 100M rows, aggregate, display slow and painful</p><p>- <strong>After</strong>: Read 72 rows from Gold layer — nearly instant</p><p>That’s a <strong>massive speedup</strong>.</p><p><strong>The Complete Pipeline in Numbers</strong></p><p>Here’s what happens when I run the full pipeline:</p><pre>| Stage  | Input     | Output         | What Happens                     |<br>| - - - -| - - - - - | - - - - - - - -|- - - - - - - - - - - - - - - - - |<br>| Bronze | Generator | ~1.2GB Parquet | Direct Parquet generation        |<br>| Silver | 1.2GB     | ~1.3GB Parquet | Cleaning, validation, enrichment |<br>| Gold   | 1.3GB     | ~50MB Parquet  | Pre-computed aggregations        |<br>| Total  | Generator | ~2.5GB         | Complete medallion pipeline      |</pre><p>The entire pipeline runs efficiently on a laptop with 16GB RAM. Dashboard loads quickly.</p><p><strong>Why This Architecture Works</strong></p><p><strong>1. Separation of Concerns</strong></p><p>Each layer has one job:</p><p>- <strong>Bronze</strong>: Ingest fast</p><p>- <strong>Silver</strong>: Clean thoroughly</p><p>- <strong>Gold</strong>: Aggregate smartly</p><p>When something breaks, I know exactly where to look.</p><p><strong>2. Incremental Processing</strong></p><p>New data? I don’t reprocess everything:</p><p>- Append to Bronze</p><p>- Clean only new records → Silver</p><p>- Update only affected aggregations → Gold</p><p><strong>3. Cost Efficiency</strong></p><p>This entire system costs <strong>$0/month</strong> to run locally. For cloud deployment, a single-instance approach is far more economical than running distributed systems like Spark clusters or managed data warehouses.</p><p><strong>The Tools That Made It Possible</strong></p><p>I didn’t reinvent the wheel. I combined mature tools:</p><p><strong>Polars</strong> The DataFrame library that’s significantly faster than Pandas</p><p>- Lazy evaluation (optimizes entire query)</p><p>- Parallel processing (uses all CPU cores)</p><p>- Memory efficient (columnar format)</p><p><strong>Parquet + Zstandard</strong> — The storage format</p><p>- Columnar = Read only needed columns</p><p>- Zstandard = Best compression ratio</p><p>- Level 9 = Maximum compression without huge CPU cost</p><p><strong>Medallion Architecture</strong> The design pattern</p><p>- Proven at scale (Databricks, Netflix, Uber)</p><p>- Simple enough for one person</p><p>- Powerful enough for enterprise</p><p><strong>What I Learned</strong></p><p><strong>1. You Don’t Always Need Big Data Tools</strong></p><p>Spark is amazing for truly distributed workloads. But if your data fits on one machine (even 100M+ rows), simpler tools are:</p><p>- Faster to develop</p><p>- Easier to debug</p><p>- Cheaper to run</p><p><strong>2. Pre-Aggregation &gt; Real-Time Everything</strong></p><p>The Gold layer is a game-changer. Yes, I’m computing things in advance. But the <strong>user experience</strong> is dramatically better:</p><p>- Dashboards load quickly</p><p>- No complex query optimization needed</p><p>- Predictable performance</p><p><strong>3. Modern Python is Seriously Fast</strong></p><p>Polars, Parquet, and modern libraries changed the game. The Python ecosystem of 2026 is not the Python of 2016.</p><p><strong>Try It Yourself</strong></p><p>The entire project is open source. You can:</p><p>1. Clone the repo</p><p>2. Generate 100M transactions or more</p><p>3. Run the pipeline</p><p>4. Explore the dashboard (Just remember the data is synthetic)</p><p><strong>What’s Next in This Series</strong></p><p>This is <strong>Part 1</strong> of a 4-part series:</p><p>1. <strong>Lakehouse Architecture</strong> (you just read this)</p><p>2. <strong>Synthetic Data Generation</strong> How I created 100M realistic transactions with seasonal patterns</p><p>3. <strong>Airflow vs Prefect</strong> I built the same pipeline in both. Here’s what I learned.</p><p>4. <strong>Interactive Dashboards</strong> Building a 4-level drill-down dashboard with Dash</p><p><strong>🔗 Project Repository</strong></p><p>The complete code for this project is on GitHub:</p><p><a href="https://github.com/PiyushSinghKumar/retail_lakehouse"><strong><em>github.com/PiyushSinghKumar/retail_lakehouse</em></strong></a></p><p><em>*If you found this helpful, follow me for Part 2 where I explain how I generated 100M realistic transactions with seasonal patterns, holidays, and year-over-year growth.*</em></p><p><em>*Questions? Leave a comment below!*</em> 👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac359d7e86a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NixOS on WSL: The Best of Both Worlds]]></title>
            <link>https://medium.com/@piyushkumarsingh.nmims/nixos-on-wsl-the-best-of-both-worlds-bdcaba54ee58?source=rss-1adb855069a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdcaba54ee58</guid>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nixos]]></category>
            <dc:creator><![CDATA[Piyush Kumar Singh]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 02:50:38 GMT</pubDate>
            <atom:updated>2025-10-12T02:50:38.292Z</atom:updated>
            <content:encoded><![CDATA[<p>How I went from Windows → NixOS → Windows (again) and finally found peace with both.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*SBvraJSogH5T7BGH.jpg" /></figure><p>A while ago, I wrote about my big move from <strong>Windows to NixOS </strong>chasing that dream of a perfectly declarative, reproducible setup.<br>Everything defined, everything version-controlled, everything <em>mine</em>.</p><p>And it worked beautifully… until I wanted to relax.</p><h3>🎮 Reality Check: Games, Xbox, and the Cost of Purity</h3><p>Let’s be honest I didn’t leave Windows because I hated it.<br>I left because I loved control.</p><p>But when it came to gaming, NixOS made me <em>work</em> for it.<br>My <strong>Xbox wireless controller</strong> was a coin toss away from connecting properly.<br>Bluetooth quirks, driver quirks you name it.</p><p>Sure, I <em>could</em> have fixed it. But I didn’t want my evenings to turn into a Linux troubleshooting marathon when actually what I want to do is just relax.</p><p>Dual-booting didn’t help either. Every time I needed to jump back into Windows, it felt like a chore saving work, rebooting, logging in again, just to use an app or play a game.</p><p>That’s when it clicked:<br>I didn’t actually want to <em>quit</em> Windows.<br>I just wanted pure <strong>Nix inside it</strong>.</p><h3>💡 The Pivot: NixOS, Natively on WSL</h3><p>So I did what any pragmatic engineer would do I stopped overcomplicating things.</p><p>Instead of running Ubuntu + Nix, I installed <strong>the official NixOS image directly inside WSL</strong>.<br>No layers. No compromise. Just <strong>real NixOS</strong> running in Windows.</p><p>And it’s <em>beautifully seamless</em>.</p><p>✅ Real NixOS user space<br>⚙️ Flakes, Home Manager, and full declarative configs<br>🚀 Lightning-fast inside Windows Terminal</p><p>Now I get the exact same reproducible environments I had on bare metal NixOS but with working Xbox wireless, GPU acceleration, and all my games intact.</p><h3>🧩 My Setup</h3><p>If you’re on <strong>WSL 2.4.4 or later</strong>, just download the .wsl file from the latest release and double-click it — that’s it.</p><p>Or do it from PowerShell:</p><pre>wsl --install --from-file nixos.wsl</pre><p>You can customize the distro name and install path using the --name and --location flags.<br>Once installed, open your new NixOS environment with:</p><pre>wsl -d NixOS</pre><p>For older WSL versions:</p><pre>wsl --import NixOS $env:USERPROFILE\NixOS nixos.wsl --version 2</pre><p>Then update the Nix channels:</p><pre>sudo nix-channel --update</pre><p>Full instructions are here:<br> 🔗 <a href="https://nix-community.github.io/NixOS-WSL/install.html">NixOS-WSL Installation Guide (Official)</a></p><p>From there, I drop in my flake.nix and rebuild.<br>A few seconds later my entire development environment is ready, declaratively.</p><p>No dual-boot, No driver hunts, No “let me just fix this one thing.”</p><p>Just productivity.</p><h3>⚙️ Why It Works So Well</h3><p>WSL2 has matured it’s fast, supports systemd, and integrates tightly with Windows now.<br>NixOS-on-WSL isn’t a hack anymore; it’s a legit, supported way to run a pure Nix environment inside Windows.</p><p>It’s the <strong>perfect hybrid</strong>:</p><ul><li>🧱 <strong>Windows</strong> → for games, tools, and media</li><li>🧬 <strong>NixOS (WSL)</strong> → for reproducible dev work, scripting, and pet projects.</li></ul><p>No trade-offs. No second-guessing.</p><h3>🪶 The Windows Side</h3><p>Let’s be real Windows still feels bloated out of the box.<br>But you can fix that.</p><p>A few PowerShell de-bloat scripts later, and it feels snappy again no telemetry, no preloaded junk, just a clean base system.</p><p>That’s when the combo really shines:<br><strong>Windows stays light, Nix stays powerful.</strong></p><h3>💭 Closing Thoughts</h3><p>Switching <em>back</em> to Windows wasn’t defeat it was <strong>evolution</strong>.</p><p>The power of Nix isn’t tied to the distro.<br>It’s in the mindset reproducibility, control, and declarative design.</p><p>Now I get all of that inside a system that handles both work and play without compromise.</p><p>So yeah:</p><p>I game on Windows, I build on NixOS and they live happily ever after in one machine.</p><p>Do you know of any different way, let me know in the comments 🫡</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdcaba54ee58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Strategic Blueprint for Optimised, Scalable Data Processing on AWS]]></title>
            <link>https://medium.com/@piyushkumarsingh.nmims/a-strategic-blueprint-for-optimised-scalable-data-processing-on-aws-4e55d740fedd?source=rss-1adb855069a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e55d740fedd</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[finops]]></category>
            <dc:creator><![CDATA[Piyush Kumar Singh]]></dc:creator>
            <pubDate>Wed, 24 Sep 2025 15:35:46 GMT</pubDate>
            <atom:updated>2025-09-24T15:35:46.002Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of data engineering, the “build versus buy” debate is constant, and so is the challenge of “managing cloud costs while maintaining performance”. Instead of relying on a monolithic, one-size-fits-all solution, a really good strategy is to design a custom architecture on AWS that prioritises cost-efficiency, speed, and operational resilience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fog5sceI8ueuIiQK.jpeg" /></figure><p>What makes this approach truly powerful is that the entire architecture is defined as code, making it fully reproducible and deployable via modern Infrastructure-as-Code (IaC) tools.</p><p>This article breaks down a strategic approach for such a system, from dynamic resource allocation and smart data handling to a unique approach to system provisioning.</p><h3>The Core Challenge: Balancing Performance and Price</h3><p>Off-the-shelf solutions are great for many use cases, but for highly specific, bursty, or demanding workloads, they often lead to either over-provisioning or a lack of granular control. A great goal is to create a system that can handle massive, unpredictable workloads with maximum throughput and minimal waste.</p><p>This strategy is built on three pillars:</p><ul><li>Workload-Aware Resource Allocation</li><li>Cost-Minimising Data and Instance Management</li><li>Reproducible and Fast System Provisioning</li></ul><p>Let’s dive into each one.</p><h4>Pillar 1: Workload-Aware Resource Allocation with Worker Groups</h4><p>A key decision in this approach is to abandon a monolithic cluster in favor of specialised, isolated worker groups.</p><p>Each group is an independent Auto Scaling Group (ASG) designed for a specific job profile.</p><ul><li>GPU-Intensive Groups: For machine learning model training, rendering, or complex simulations, you can have dedicated worker groups provisioned with GPU-enabled EC2 instances.</li><li>CPU-Intensive Groups: For standard data transformation, ETL, and batch processing, use CPU-optimised instances to ensure you’re not paying for idle GPUs.</li><li>Memory-Optimised Groups: For workloads that need to hold large datasets in memory, configure groups with memory-optimised instances like r or x types.</li></ul><p>This micro-segmentation of the compute fleet allows for true “right-sizing” at the group level. A job requiring a specific instance type is routed to its designated worker group, ensuring that only the necessary resources are used and paid for.</p><h4>Pillar 2: The FinOps of Data Processing</h4><p>Cost optimisation should be an architectural consideration, not an afterthought. This approach focuses on two main areas: minimising data transfer costs and intelligently using the EC2 pricing model.</p><ul><li>No-Cost Data Transfers via Regional Proximity: A major cost driver in any cloud data pipeline is data egress. By ensuring all compute instances and data storage (S3 buckets) reside within the same AWS region, you can eliminate this cost almost entirely. All data movement between S3 and your EC2 instances is free. This simple, but critical, design choice can have a massive impact on the monthly bill, especially for large-scale data operations.</li><li>Dynamic Instance Pricing Strategy: This is where the strategy gets granular. The Auto Scaling Groups can be configured using a mixed instance policy, combining On-Demand and Spot Instances with a sophisticated allocation strategy.</li></ul><p>To understand the power of this, it’s essential to know the pros and cons of each instance type and why a hybrid approach is often the most intelligent choice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AkO9fRvMSnsZ6GKwmHj1yw.png" /></figure><p>A sample configuration could look something like this:</p><pre>instancesDistribution: {<br> onDemandAllocationStrategy: autoscaling.OnDemandAllocationStrategy.LOWEST_PRICE,<br> onDemandPercentageAboveBaseCapacity: n,<br> spotAllocationStrategy: autoscaling.SpotAllocationStrategy.PRICE_CAPACITY_OPTIMIZED,<br> spotMaxPrice: island.maxHourlyPriceInDollar,<br>}</pre><p>Let’s break down what this means:</p><ul><li>onDemandPercentageAboveBaseCapacity (n): This means the Auto Scaling Group has a base capacity of n On-Demand instances. This allows for a flexible balance between guaranteed uptime and significant cost savings. The value of “n” can be adjusted based on the specific reliability requirements of a given workload.</li><li>spotAllocationStrategy (PRICE_CAPACITY_OPTIMISED): This powerful strategy doesn’t just pick the cheapest spot instance; it considers both the price and the availability of the Spot market. This significantly reduces the chances of an instance being interrupted, making the pipeline more reliable and reducing job re-starts.</li><li>onDemandAllocationStrategy (LOWEST_PRICE): If you do need to fall back to On-Demand instances (for instance, if Spot capacity is unavailable), this ensures you pick the cheapest available instance type from your defined list.</li><li>spotMaxPrice (island.maxHourlyPriceInDollar): As an extra layer of control, you can even specify a maximum hourly price you are willing to pay for a Spot instance. If the price in the Spot market exceeds this limit, the instance will be terminated. This ensures you never pay more than a predetermined amount, providing a powerful guardrail for your budget. This is a strategic lever to pull if you want to be extremely disciplined with your cloud spend.</li></ul><p>By implementing this, the architecture can leverage the significant cost savings of Spot Instances while mitigating the risk of interruptions, all with an optional hard cap on spending.</p><h4>Pillar 3: Reproducible and Blazing-Fast System Provisioning</h4><p>The speed of a data pipeline isn’t just about runtime; it’s about the time it takes to go from a cold start to a fully operational machine. This can be solved by adopting the Nix package manager.</p><p>Here’s a potential workflow:</p><ol><li>Define the exact software stack and environment for each worker group using a Nix configuration file. This includes the base OS, required libraries (e.g. Python, CUDA and more), and specific application dependencies.</li><li>Use a maintained and updated AMI (Amazon Machine Image) from Nix, and install more packages on top of it, which are also maintained by Nix.</li><li>When a new EC2 instance is launched by the ASG, it doesn’t need to install anything from scratch. It checks the nix cache for its specific build. If the build exists, it simply pulls the pre-compiled, pre-configured environment. This is an incredibly fast process, turning a 10–20 minute setup into a 1–2 minute provisioning time.</li></ol><p>This Nix-based caching and provisioning provides:</p><ul><li>Reproducibility: The “it works on my machine” problem is eliminated. Every machine in a worker group is an identical, immutable replica of the defined environment.</li><li>Speed: Scaling up is near-instantaneous, allowing the system to react to demand spikes in seconds.</li><li>Consistency: Jobs are guaranteed to run in the exact same environment every time, which is essential for debugging and long-term reliability.</li></ul><h4>The Role of Infrastructure as Code</h4><p>This entire architecture is defined using Infrastructure as Code (IaC), which means all resources, configurations, and scaling policies are in version-controlled code. This not only makes the setup repeatable but also allows for an integrated development workflow where application code and infrastructure can be managed and deployed together.<br>A key benefit of this approach is its tool agnosticism. While the architecture is fully compatible with the AWS Cloud Development Kit (CDK), which allows you to define your infrastructure using familiar programming languages like Python or TypeScript it also offers flexibility. You can use other powerful IaC tools as long as they can provision the necessary AWS resources. This choice allows teams to leverage their existing skill sets and organisational standards without being locked into a single technology.</p><p><strong>Orchestration: The In-House Job Queue</strong></p><p>Connecting all these pieces is a custom job queue system. When a data processing job is submitted, the queue analyses its requirements (e.g., GPU needed, memory profile, storage requirements) and assigns it to the appropriate worker group. This intelligent routing ensures that the right job is always running on the most suitable and cost-effective resources.</p><p><strong>Conclusion: A Strategy for the Future</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6ushtqTzcgCk4bOR.jpeg" /></figure><p>This type of cloud architecture is more than just a collection of services; it’s a strategic blueprint designed for the real-world demands of data processing. By embracing specialised worker groups, a disciplined FinOps mindset, and the power of Nix-based caching, you can create a system that is not only robust and scalable but also remarkably cost-effective.</p><p>This approach gives you the agility to handle diverse workloads without sacrificing your budget. It’s a testament to the power of thoughtful, custom architecture in the age of cloud computing.</p><p>What’s your secret to managing cloud spend?<br>Share your thoughts in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e55d740fedd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Wasting Time on Setup: How to Create Bulletproof Dev Environments with Nix Flakes]]></title>
            <link>https://medium.com/@piyushkumarsingh.nmims/stop-wasting-time-on-setup-how-to-create-bulletproof-dev-environments-with-nix-flakes-1066a5bccbe6?source=rss-1adb855069a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1066a5bccbe6</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[thoughts]]></category>
            <category><![CDATA[declarative-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Piyush Kumar Singh]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 17:47:41 GMT</pubDate>
            <atom:updated>2025-08-01T17:47:41.228Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A step-by-step guide to building a self-contained, reproducible development environment with automated services using Nix and Systemd.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3CITD81_7ReKgKWAnJg0w.png" /></figure><p>We’ve all been there. You clone a new project, and the README.md greets you with a wall of setup instructions: &quot;Install Python x.xx.xx, then run pip install -r requirements.txt, make sure you have MongoDB vx.x installed and running, then install Node.js vxx...&quot;. Two hours later, you’re stuck in a dependency hell because your global npm packages conflict with the project&#39;s needs.</p><p>The “works on my machine” problem is a classic for a reason. Traditional environment management with tools like venv and requirements.txt only solves part of the problem, the Python part. They don&#39;t account for system-level dependencies, databases, or other developer tools.</p><p>What if you could define your <em>entire</em> development environment: the Python interpreter, the exact library versions, the MongoDB server, a GUI client, and even background services in a single, declarative file? What if a new developer could get a fully running environment with one command?</p><p>This is the power of Nix. In this article, I’ll walk you through a real-world project structure that uses Nix Flakes to create a bulletproof, reproducible, and automated development environment.</p><h3>What is Nix and Why Should You Care?</h3><p>Nix is a powerful package manager and build system that takes a unique approach to dependency management. Instead of installing packages globally or into a project-specific folder, Nix builds every package in isolation in its own unique directory inside the /nix/store.</p><p>This approach provides three killer features:</p><ol><li><strong>Declarative:</strong> You write a file (like our flake.nix) that <em>describes</em> the environment you want. You don&#39;t write imperative setup steps; you declare the final state.</li><li><strong>Reproducible:</strong> A Nix configuration file will produce the <em>exact same environment</em> on any machine, every time. By pinning the version of the Nix package set (nixpkgs), we ensure that every dependency, down to the last bit, is identical.</li><li><strong>Isolated:</strong> Packages don’t interfere with each other. You can have ten different projects with ten different versions of Python or Node.js on the same machine without any conflicts.</li></ol><h3>Anatomy of Our flake.nix</h3><p>The heart of our setup is the flake.nix file. It defines all the inputs (dependencies) and outputs (the development shell) for our project. Let&#39;s break it down.</p><pre>{<br>  description = &quot;Modular dev shell with systemd user services and Python env&quot;;<br><br>  inputs.nixpkgs.url = &quot;github:NixOS/nixpkgs/nixos-25.05&quot;;<br><br>  outputs = { self, nixpkgs, ... }:<br>    let<br>      system = &quot;x86_64-linux&quot;;<br>      pkgs = import nixpkgs {<br>        inherit system;<br>        config = { allowUnfree = true; };<br>      };<br><br>      pythonEnv = pkgs.python312.withPackages (ps: with ps; [<br>        pip<br>        ipykernel<br>        jupyterlab<br>        notebook<br>        numpy<br>        pandas<br>        pyarrow<br>        requests<br>        scikit-learn<br>        matplotlib<br>        pymongo<br>        seaborn<br>        geopy<br>        black<br>      ]);<br><br>      mongodbServiceTemplate = builtins.readFile ./systemd/mongodb.service.template;<br>      jupyterLabServiceTemplate = builtins.readFile ./systemd/jupyterlab.service.template;<br>      mongodPath = &quot;${pkgs.mongodb}/bin/mongod&quot;;<br>      jupyterPath = &quot;${pythonEnv}/bin/jupyter-lab&quot;;<br>    in<br>    {<br>      devShells.${system}.default = with pkgs; mkShellNoCC {<br>        # Main development environment with Python, MongoDB, Node.js, and utilities<br>        buildInputs = [<br>          pythonEnv<br>          mongodb<br>          nodejs<br>          yarn<br>          mongodb-compass<br>          systemd<br>          mongosh<br>          curl<br>          iproute2<br>        ];<br><br>        # shellHook sets up systemd user services and prints helpful info<br>        shellHook = &#39;&#39;<br>          # ... shellHook magic here ...<br>        &#39;&#39;;<br>      };<br>    };<br>}</pre><ul><li><strong>inputs</strong>: We declare our single input: nixpkgs from a specific release branch (nixos-25.05). This pins our dependencies to a known-good state, which is crucial for reproducibility.</li><li><strong>outputs</strong>: This function produces our final environment.</li><li><strong>let...in block</strong>: This is where we define local variables.</li><li>pkgs: We import the nixpkgs set for our specified system.</li><li>pythonEnv: This is where we define our Python environment. Using pkgs.python312.withPackages, we list all the Python libraries our project needs. Nix handles fetching them and their native dependencies.</li><li>The other variables are helpers for our service automation, which we’ll get to next.</li><li><strong>devShells.default</strong>: This defines the development shell.</li><li>buildInputs: This is the list of everything we want available in our shell&#39;s PATH. We include our entire pythonEnv, mongodb, nodejs, and even GUI tools like mongodb-compass. When we run nix develop, all these tools become available.</li></ul><h3>The Killer Feature: Automated Services with shellHook</h3><p>This is where the setup goes from great to magical. We don’t just want MongoDB available; we want it <em>running</em> in the background when we’re working on the project. We achieve this by using the shellHook to dynamically create <strong>systemd user services</strong>.</p><p>A systemd user service is a background process that runs under your user account and is managed by your user’s systemd instance. It’s perfect for development databases and servers.</p><p>First, we create templates for our services:</p><p><strong>systemd/mongodb.service.template</strong></p><pre>[Unit]<br>Description=Project Local MongoDB<br>After=network.target<br><br>[Service]<br>WorkingDirectory=__PROJECT_DIR__<br>ExecStart=__MONGOD_PATH__ --dbpath=.mongodb-data --bind_ip 127.0.0.1<br>Restart=always<br>RestartSec=5<br>StandardOutput=journal<br>StandardError=journal<br><br>[Install]<br>WantedBy=default.target</pre><p><strong>systemd/jupyterlab.service.template</strong></p><pre>[Unit]<br>Description=Project JupyterLab<br>After=network.target mongodb.service<br><br>[Service]<br>WorkingDirectory=__PROJECT_DIR__<br>ExecStart=__JUPYTER_PATH__ --no-browser --ip=127.0.0.1 --port=8888 --ServerApp.token=&#39;token&#39;<br>Restart=always<br>RestartSec=5<br>StandardOutput=journal<br>StandardError=journal<br><br>[Install]<br>WantedBy=default.target</pre><p>Notice the placeholders like __PROJECT_DIR__ and __MONGOD_PATH__. Now, look at the shellHook in our flake.nix that brings them to life:</p><pre># Inside devShells.default<br>shellHook = &#39;&#39;<br>  echo &quot;Dev shell activated.&quot;<br>  # ... helpful echo statements ...<br><br>  PROJECT_DIR=&quot;$(pwd)&quot;<br>  mkdir -p ~/.config/systemd/user<br>  mkdir -p &quot;$PROJECT_DIR/.mongodb-data&quot;<br><br>  # Write MongoDB service file, substituting the placeholders<br>  echo &quot;${mongodbServiceTemplate}&quot; | \<br>    sed &quot;s|__PROJECT_DIR__|$PROJECT_DIR|g&quot; | \<br>    sed &quot;s|__MONGOD_PATH__|${mongodPath}|g&quot; \<br>    &gt; ~/.config/systemd/user/mongodb.service<br><br>  # Write JupyterLab service file, substituting the placeholders<br>  echo &quot;${jupyterLabServiceTemplate}&quot; | \<br>    sed &quot;s|__PROJECT_DIR__|$PROJECT_DIR|g&quot; | \<br>    sed &quot;s|__JUPYTER_PATH__|${jupyterPath}|g&quot; \<br>    &gt; ~/.config/systemd/user/jupyterlab.service<br><br>  systemctl --user daemon-reload<br>&#39;&#39;;</pre><p>This script runs every time you enter the shell with nix develop. Here&#39;s what it does:</p><ol><li>It gets the absolute path to the current project directory.</li><li>It ensures the systemd/user directory exists.</li><li>It takes our service templates, and using sed, it replaces the placeholders with the <em>actual, Nix-managed paths</em> to the mongod and jupyter-lab binaries.</li><li>It writes these finalized .service files to the correct systemd user directory.</li><li>Finally, it runs systemctl --user daemon-reload to tell systemd to pick up the changes.</li></ol><p>The result? The moment a developer enters the shell, the services are configured and ready to be started.</p><h3>The User Experience: One Command to Rule Them All</h3><p>Now, let’s see the complete workflow for a developer joining the project:</p><ol><li>git clone &lt;your-repo-url&gt;</li><li>cd &lt;your-repo-directory&gt;</li><li>nix develop</li></ol><p>That’s it. Nix builds or downloads the exact versions of Python, its libraries, MongoDB, Node.js, and all other tools. The shellHook runs, configuring the systemd services. The developer is then greeted with helpful instructions printed by our shellHook:</p><pre>Dev shell activated.<br><br>Systemd user service units available:<br>  - mongodb.service<br>  - jupyterlab.service<br><br>To start services:<br>  systemctl --user enable --now mongodb.service<br>  systemctl --user enable --now jupyterlab.service</pre><p>The developer can now start the services and get to work immediately, knowing their environment is identical to every other team member’s.</p><p>By combining the declarative power of Nix with the automation of a shellHook, we&#39;ve eliminated an entire class of setup problems and created a truly seamless onboarding experience.</p><h3>Conclusion</h3><p>By moving beyond traditional environment management and embracing a declarative tool like Nix, we’ve built more than just a data science project; we’ve created a platform. A single nix develop command is all it takes for anyone to have a fully functional, bit-for-bit identical environment, complete with running background services. This approach drastically reduces setup friction and eliminates the dreaded &quot;it works on my machine&quot; syndrome.</p><p>While Nix has a reputation for a steep learning curve, patterns like the one in this project demonstrate its practical power. The initial investment in writing a flake.nix file pays dividends throughout the project&#39;s lifecycle, ensuring consistency, simplifying CI/CD pipelines, and making collaboration a breeze.</p><p>I encourage you to explore this setup for your own projects. You can use the flake.nix from this project as a starting point and adapt it to your needs. Try adding your own tools, services, or even different language environments the declarative nature of Nix makes it incredibly flexible.</p><p>As software projects become more complex, the need for robust, reproducible, and automated development environments is no longer a luxury it’s a necessity. Tools like Nix represent the future of sane, scalable development, allowing us to focus on what truly matters: building great things.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1066a5bccbe6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-Hosting Your Photos with Immich on NixOS: It’s Easier Than You Think]]></title>
            <link>https://medium.com/@piyushkumarsingh.nmims/self-hosting-your-photos-with-immich-on-nixos-its-easier-than-you-think-c3d14fcabad1?source=rss-1adb855069a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3d14fcabad1</guid>
            <category><![CDATA[nixos]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[immich]]></category>
            <category><![CDATA[self-hosting]]></category>
            <dc:creator><![CDATA[Piyush Kumar Singh]]></dc:creator>
            <pubDate>Fri, 11 Jul 2025 15:59:24 GMT</pubDate>
            <atom:updated>2025-07-11T15:59:24.795Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*ROs_wiTDxCpOpjdj" /></figure><p>Looking for a self-hosted alternative to Google Photos? <a href="https://immich.app/">Immich</a> is an open-source gem that gives you full control over your personal photo and video library. With features like automatic backups, multi-user support, and ML-powered search, it’s rapidly becoming the go-to option for privacy-conscious users.</p><p>But let’s be real self-hosting usually sucks. The typical Immich install guide involves:</p><ul><li>Cloning a GitHub repo</li><li>Writing or modifying a docker-compose.yml</li><li>Configuring PostgreSQL and Redis</li><li>Exposing ports via a reverse proxy</li><li>Managing environment variables</li><li>Debugging when something inevitably breaks</li></ul><p>Sound familiar? You wouldn’t be wrong to hesitate.</p><p>But what if I told you that on <strong>NixOS</strong>, you can get a production-ready Immich instance running with <strong>no Docker, no Compose file, and no fiddling with dependencies</strong> just a few declarative lines of config?</p><p>Let’s walk through exactly how.</p><h4>Immich with Nix: No Docker Required</h4><p>The Nix ecosystem now includes a first-class Immich module. This means we can set up the entire stack server, database, firewall, and all natively, using a <strong>fully declarative configuration</strong>, without a single container in sight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ptx_sgwM51iyRFzx7d59xw.png" /></figure><p>Why is that better?</p><ul><li><strong>Zero Docker overhead</strong></li><li><strong>No Compose YAML to maintain</strong></li><li><strong>Database and service lifecycle managed via systemd</strong></li><li><strong>Tighter integration with the OS</strong></li><li><strong>Cleaner logs, cleaner restarts, cleaner everything</strong></li></ul><p>Let’s get to the code.</p><h4>The Magic File: immich.nix</h4><p>Here’s the full configuration for Immich using the NixOS module:</p><pre># immich.nix<br>{<br>  services.immich = {<br>    enable = true;<br>    port = port;<br>    host = &quot;0.0.0.0&quot;; # Makes it accessible on your network<br>    mediaLocation = &quot;/var/lib/immich&quot;; # Ensure this has enough space<br>    openFirewall = true; # Auto-opens the port<br>  };<br>}</pre><p>That’s it. No database setup. No reverse proxy. No environment juggling.</p><h4>What happens when you deploy</h4><p>Nix will:</p><ul><li>Download Immich and its runtime dependencies</li><li>Set up PostgreSQL automatically</li><li>Create and enable the Immich server + microservices via systemd</li><li>Open the correct firewall ports</li></ul><p>After it’s done, open http://&lt;your-server-ip&gt;:port in your browser and complete the setup.</p><h4>NixOS vs Docker: The Inevitable Comparison</h4><p>Docker is great for running untrusted apps in isolated sandboxes, but it’s a poor fit for something you want <strong>deeply integrated into your system</strong>, like a photo management server.</p><p>With Docker, you’re effectively managing two layers of systems: the host and the containers.</p><p>With NixOS, <strong>there’s only one system and you declare everything about it</strong>.</p><p>Nix is reproducible, upgradeable, trackable, and integrates cleanly with the OS making it a more reliable, robust solution for home server setups.</p><h3>Final Thoughts: Declarative Self-Hosting</h3><p>By leveraging NixOS and the native Immich module, we’ve eliminated the need for Docker, compose files, and manual setup steps. We now have a <strong>fully-managed, self-updating photo server</strong> all defined in a handful of lines.</p><p>This is what declarative system management enables: a more sane, maintainable, and scalable way to self-host.</p><p>Want to dive deeper into building a declarative system from the ground up? Don’t miss:</p><p>🔗 <a href="https://medium.com/@piyushkumarsingh.nmims/from-windows-to-nixos-my-journey-to-declarative-system-management-0301020bf609">From Windows to NixOS: My Journey to Declarative System Management</a></p><p>🔗 <a href="https://medium.com/@piyushkumarsingh.nmims/my-nixos-journey-part-2-flakes-home-manager-and-the-unstable-edge-46a5e1ef667c">My NixOS Journey Part 2: Flakes, Home Manager, and the Unstable Edge</a></p><h3>Bonus: No More Google Storage Fees</h3><p>With Immich, your photos stay local: no cloud, no subscriptions, no limits (except your disk space).</p><p>Forget paying Google just to access your own memories. Self-hosting means <strong>you own the data</strong> and <strong>you control the cost</strong>.</p><p>With Immich + NixOS, your only limit is <strong>your own disk space</strong>.</p><ul><li>Need more storage? Add a drive.</li><li>Want privacy? It’s already local.</li><li>Tired of vendor lock-in? You’re free.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3d14fcabad1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>