<?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[DevData - Medium]]></title>
        <description><![CDATA[Experience and knowledge sharing on software development, engineering practices and programming languages - Medium]]></description>
        <link>https://medium.com/dev-data?source=rss----76dbf3dd6784---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>DevData - Medium</title>
            <link>https://medium.com/dev-data?source=rss----76dbf3dd6784---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:31:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/dev-data" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Prompting Is Architecture: Why Understanding Systems Matters More Than Ever]]></title>
            <link>https://medium.com/dev-data/prompting-is-architecture-why-understanding-systems-matters-more-than-ever-1764f1a8141a?source=rss----76dbf3dd6784---4</link>
            <guid isPermaLink="false">https://medium.com/p/1764f1a8141a</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[writing-prompts]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[Swapnil Sankla]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 12:57:58 GMT</pubDate>
            <atom:updated>2026-02-18T12:57:59.853Z</atom:updated>
            <content:encoded><![CDATA[<p>A Spark story about scale, grain, and why speed makes system awareness non-negotiable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*00laA7iTHtI5e5YkT-wlPQ.png" /><figcaption>Image generated using Chatgpt</figcaption></figure><h4>The Setup: When “Correct” Code Still Fails</h4><p>Recently, I ran into a Spark job that looked perfectly fine. I used Claude in this case to generate code which was</p><ul><li>Syntactically correct</li><li>Semantically correct</li><li>Easy to read and reason about</li></ul><p>This worked on the sample dataset. Assuming Spark will manage the scale we pushed it to production. However, on prod it took more than 3 hours to complete on a 40-node EMR cluster. It was trying to process ~99 GB fact dataset with ~150 MB dimension data.</p><p>What bothered us wasn’t just the runtime but also the fact that nothing looked obviously wrong.</p><p>Turned out, this wasn’t a Spark tuning problem nor an infrastructure problem. And interestingly, it wasn’t really an AI problem either.</p><p>It was a <strong>systems understanding problem</strong>.</p><h4>A Quick Translation (So We Don’t Get Lost in Domain Names)</h4><p>Before going further, let me simplify the domain language. This will keep our focus on the point I want to make rather than on the domain itself.</p><p>The real system was ad tech-related, but the specifics don’t matter. What does matter is the <strong>shape of the data</strong>.</p><p>So for the rest of this post, think in these neutral terms:</p><ul><li><strong>Entity: </strong>Thing we want metrics for (a campaign, product, page, or item)</li><li><strong>Fine-grained ID: </strong>A very detailed identifier (user, device, session, event)</li><li><strong>Group: </strong>A higher-level attribute (region, segment, category)</li></ul><p>Each row in the input dataset represented:</p><pre>(entity, group, fine_grained_id) → metric</pre><p>Keep this mental model in mind. It’s the key to everything that follows.</p><h4>The Spark Job (Simplified)</h4><p>The original Spark logic followed a very common pattern:</p><ol><li>Read a large fact dataset</li><li>Join it with a small dimension table (broadcasted)</li><li>Compute derived metrics</li><li>Aggregate the results</li></ol><p>In simplified form:</p><pre>factDataset<br>  .join(broadcast(dimension), joinKey)<br>  .withColumn(&quot;derived_metric&quot;, ...)<br>  .groupBy(...)<br>  .agg(...)</pre><p>Nothing here is wrong. In fact, this was exactly the kind of code I would have approved in a review without thinking twice.</p><p>So why did it crawl?</p><h4>The Missing Question: What Is the Grain?</h4><p>I spent a fair amount of time in Spark UI before realizing it wasn’t helping.<br>The breakthrough came only after I stopped looking at Spark altogether and asked myself a simpler question:</p><blockquote><strong><em>What does one row in this dataset actually represent?</em></strong></blockquote><p>Not how big it is in GB.<br>Not how many partitions it has.<br>But the <strong>grain</strong>.</p><p>In this case, each row was <strong>entity × fine-grained ID × group</strong>.</p><p>That means:</p><ul><li>Millions of rows per entity</li><li>Before any meaningful aggregation</li></ul><p>This detail was easy to miss and devastating at scale.</p><h4>Why Grain Matters More Than Size</h4><p>From a purely logical perspective, these two approaches are equivalent, and that’s exactly why I didn’t question the original version early enough:</p><pre>(join → aggregate)</pre><p>and</p><pre>(aggregate → join → aggregate)</pre><p>Both produce the same final answer.</p><p>But Spark doesn’t execute logic. It executes <strong>physical plans</strong>.</p><p>And in Spark:</p><ul><li>Joins <strong>multiply rows</strong></li><li>Aggregations <strong>reduce rows</strong></li><li>Shuffle cost grows with <strong>row count × row width</strong></li></ul><p>When you join a <strong>fine-grained dataset</strong> with a dimension that fans out:</p><ul><li>Spark must materialize all expanded rows</li><li>Move them across the network</li><li>Spill them to disk and only then reduce them later</li></ul><p>That intermediate blow-up is <strong>a row explosion</strong>.</p><p><strong>It’s invisible in code. It’s painfully visible in runtime.</strong></p><h4>The Fix Was Simple</h4><p>The fix wasn’t:</p><ul><li>More executors</li><li>Different join hints</li><li>Or Spark tuning flags</li></ul><p>It was changing <strong>when</strong> aggregation happened.</p><p>Instead of joining first and aggregating later, we aggregated <strong>to the correct grain first</strong>:</p><pre>factDataset<br>  .groupBy(&quot;entity&quot;, &quot;group&quot;)<br>  .agg(sum(&quot;metric&quot;).alias(&quot;group_metric&quot;))<br>  .join(broadcast(dimension), &quot;group&quot;)<br>  .groupBy(&quot;entity&quot;, &quot;dimension_key&quot;)<br>  .agg(sum(&quot;scaled_metric&quot;))</pre><p>Same logic. Same result.</p><p>Completely different execution shape.</p><p>By collapsing the fine-grained rows early:</p><ul><li>The row explosion disappeared</li><li>The shuffle volume dropped dramatically</li><li>Runtime fell from hours to minutes</li></ul><h4>Why This Was Actually a Prompting Failure</h4><p>At this point, you may wonder:</p><blockquote><strong><em>What does this have to do with prompting?</em></strong></blockquote><p>Here’s the uncomfortable answer:</p><p>The original prompt never described the system’s execution constraints, mostly because I hadn’t articulated them clearly to myself either.</p><p>When I asked the AI to generate the Spark transformation, my prompt implicitly assumed:</p><ul><li>Joins are cheap</li><li>Aggregation order doesn’t matter</li><li>Scale is just “bigger data”, not structurally different data</li></ul><p>Those assumptions are harmless in single-node code. However, they are catastrophic in distributed systems.</p><p>The AI did exactly what I asked and exactly what I failed to constrain.</p><h4>Why AI Misses Row Explosion</h4><p>Row explosion is not a syntax problem. It’s an <strong>execution model problem</strong>.</p><p>Understanding it requires knowing that:</p><ul><li>Joins fan out</li><li>Aggregation reduces cardinality</li><li>Shuffle cost dominates runtime</li><li>Order of operations changes physical plans</li></ul><blockquote><strong><em>AI models are trained on code, not execution traces. They learn what patterns appear together, not what those patterns cost at runtime. There’s no gradient signal for “this join will blow up your cluster.”</em></strong></blockquote><blockquote><strong><em>And unless you surface that knowledge explicitly in a prompt, the model has no reason to optimize for it.</em></strong></blockquote><h4>What a Better Prompt Would Have Looked Like</h4><p>Looking back, a better prompt wouldn’t just say what to compute.<br>It would have forced me to confront assumptions I was making implicitly.</p><p>For example:</p><blockquote><strong><em>The input dataset is at fine-grained (user/device/event) level.<br>Joining before aggregation will cause row explosion.<br>Please aggregate to the lowest meaningful grain before any fan out joins.</em></strong></blockquote><p>That single paragraph communicates:</p><ul><li>Data grain</li><li>Join behavior</li><li>Performance constraints</li></ul><p>Without that, the AI may naturally produce a logically correct but physically disastrous plan.</p><h4>Prompting Is Architecture</h4><p>This is the real lesson. Prompting is not about:</p><ul><li>Better wording</li><li>Clever phrasing</li><li>Longer instructions</li></ul><blockquote><strong><em>Prompting is about constraints. And constraints are architecture.</em></strong></blockquote><p>When you prompt an AI without understanding the system underneath, you’re effectively saying, “Decide the architecture for me.<em>”</em></p><p>The AI will happily do so guided only by local correctness.</p><h4>Closing Thought</h4><p>AI didn’t cause the failure — it just surfaced gaps in my thinking faster than I would have found them on my own.</p><p>The better you understand:</p><ul><li>Data grain</li><li>Execution models</li><li>Failure modes</li></ul><p>…the better your prompts become.</p><p>And at that point, AI stops being just a code generator<br>and starts becoming a true force multiplier.</p><blockquote><strong><em>In the age of AI, depth matters more than ever — because when code is easy to produce, the cost of wrong system-level choices grows exponentially.</em></strong></blockquote><p>This lesson isn’t unique to Spark. It applies anywhere execution cost is invisible in code — database query planners, network<br>serialization, memory allocation patterns. The domain changes; the principle doesn’t.</p><h3>About the Author</h3><p>I am a software engineer with 15+ years of experience building data-intensive systems. I work on building distributed systems and analytical platforms, with a focus on understanding systems from first principles. I like to document engineering tradeoffs and lessons learned from building systems under practical constraints.</p><h3>Review Credits</h3><p>Thanks <a href="https://www.linkedin.com/in/amaansh08/">Amaan</a>, <a href="https://www.linkedin.com/in/vighnesh-pathrikar/">Vighnesh</a> for reviewing this post and providing valuable feedback.</p><p><strong><em>Tags</em></strong><em>: Writing Prompts, LLM, Claude, Apache Spark, Architecture</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1764f1a8141a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-data/prompting-is-architecture-why-understanding-systems-matters-more-than-ever-1764f1a8141a">Prompting Is Architecture: Why Understanding Systems Matters More Than Ever</a> was originally published in <a href="https://medium.com/dev-data">DevData</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing OLAP Schemas by Query Shape]]></title>
            <link>https://medium.com/dev-data/designing-olap-schemas-by-query-shape-4abc31d1b894?source=rss----76dbf3dd6784---4</link>
            <guid isPermaLink="false">https://medium.com/p/4abc31d1b894</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[database-schema]]></category>
            <category><![CDATA[columnar-databases]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[clickhouse]]></category>
            <dc:creator><![CDATA[Swapnil Sankla]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 12:57:30 GMT</pubDate>
            <atom:updated>2026-02-18T12:57:32.387Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A ClickHouse schema design journey</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxKSnyXMBq39BW5Qaa1XpQ.png" /><figcaption>Image generated using chatgpt</figcaption></figure><p>How we learned that schema purity matters less than matching the natural grain of your queries.</p><h3>Setting the Scene: Digital Billboards and Audience Targeting</h3><p>Before we talk schema design, we need to discuss the problem. Without the domain context, the technical decisions won’t make sense.</p><h4>The Business: Out-of-Home Advertising</h4><p>Think of the digital billboards you see on highways, in malls, airports, or gyms. Each physical screen is called a <strong>frame</strong>.</p><p>Advertisers don’t just ask — How many people see this screen?<br>They ask:</p><blockquote><strong><em>Which frames should I buy to best reach my target audience?</em></strong></blockquote><h4>The Data We Work With</h4><p><strong>Frames</strong>: Physical advertising screens. In the US alone, there are millions — Times Square, shopping centers, transit hubs, everywhere.</p><p><strong>Audiences</strong>: Behavioral audiences like luxury car buyers, fitness enthusiasts, or working parents. A typical advertisement campaign targets 1–6 audiences simultaneously.</p><p><strong>Impressions</strong>: The estimated number of people who see a frame during a specific hour. Example: A Times Square billboard at 5 pm has more impressions than a suburban bus stop at 3 am.</p><p><strong>DMA (Designated Market Area)</strong>: Geographic regions used in advertising. Think New York metro area or Los Angeles market.</p><h4>The Key Metric: Audience Index</h4><p>Raw impression counts are misleading.</p><p>A Times Square frame may reach more fitness enthusiasts than a suburban bus stop — but it also reaches far more everyone else. What advertisers really care about is <strong>concentration</strong>, not absolute volume.</p><p>We measure this using an <strong>audience index</strong>:</p><pre>audience_index = (frame&#39;s audience ratio) / (market&#39;s natural delivery) × 100</pre><p>Where:</p><ul><li><strong>Frame’s audience ratio</strong> = audience impressions / total impressions at this frame</li><li><strong>Natural delivery</strong> = audience impressions / total impressions across ALL frames in the market</li></ul><p>Interpretation:</p><ul><li><strong>100</strong> → performs exactly at market average</li><li><strong>150</strong> → over-indexes by 50% (1.5× better than average)</li><li><strong>80</strong> → under-indexes by 20%</li></ul><h4>Why Hourly Granularity Is Non-Negotiable?</h4><p>Audience composition changes dramatically over the day:</p><ul><li><strong>8 am at a subway station</strong>: Commuters, working professionals</li><li><strong>2 pm at a mall</strong>: Stay-at-home parents, retirees</li><li><strong>8 pm at a gym</strong>: Fitness enthusiasts</li></ul><p>Advertisers buy specific <strong>dayparts</strong>, such as weekday mornings or weekend evenings. That leads to a crucial requirement:</p><blockquote><strong><em>Audience index must be computed at the hourly level, and only then averaged across the selected hours.</em></strong></blockquote><p>You cannot calculate a single daily index without losing correctness.</p><h4>The Query in Plain English</h4><p><em>Show me all frames in the New York market that over-index (index ≥ 100) for young professionals during weekday commute hours (8–10 am and 5–7 pm, Monday through Friday), subject to dynamic frame-level filters such as location type (e.g. roadside vs mall), media owner, pricing constraints, and availability.</em></p><p>This query is not a batch report or an offline analysis. It sits directly in the critical path of a <strong>chat-based user experience</strong>, where advertisers explore options conversationally and expect responses in near real time.</p><p>This requires:</p><ol><li>For each frame, for each selected hour: calculate the audience index</li><li>Average those hourly indices to get a single score per frame</li><li>Filter to frames with average index ≥ 100</li><li>The query must return within 1–2 seconds to keep the conversational flow intact, even as users refine audiences and time windows interactively.</li></ol><p>This query cannot be answered using precomputed DMA-level indices alone. While market-level natural delivery can be aggregated, the final index must be recomputed over the user-selected subset of frames, which varies per request based on interactive filters.</p><p>Now, let’s design a schema to make this query fast.</p><h4>The Scale of the Problem</h4><p>At full resolution, the data looks like this:</p><ul><li>≈ <strong>1.7 million</strong> Frames</li><li>We support around <strong>300</strong> Audiences on the platform</li><li><strong>168</strong> Time slots (24 hours × 7 days)</li></ul><p>That’s potentially <strong>85 billion data points</strong> (1.7M × 300 × 168).</p><p>We don’t materialize all of them at once, but the schema must support this dimensionality efficiently.</p><h4>The Intuition: Columnar Should Win</h4><p>We use ClickHouse, a columnar OLAP database. The standard advice is clear:</p><blockquote><strong><em>Put different attributes in different columns so queries read only what they need.</em></strong></blockquote><p>Applied naively, that suggested a very wide table. We add 16,800 columns to capture hourly audience impressions across 168 hours.</p><p>To test this locally, we decided to ingest 80,000 frames with 100 audiences:</p><pre>CREATE TABLE frames_hourly_insights (<br>    id String,<br>    dma LowCardinality(String),<br>    -- ... other frame attributes ...<br>    -- 100 audiences × 168 hours = 16,800 columns<br>    `audience1_mon_08` Float32,<br>    `audience1_mon_09` Float32,<br>    -- ... continues for all 168 hours per audience ...<br>)</pre><p>The appeal was obvious:</p><ul><li>Perfect column pruning</li><li>Querying Young professionals across during weekday commute hours (8–10 am and 5–7 pm, Monday through Friday) reads just 20<strong> </strong>columns</li><li>~99.9% of data skipped</li></ul><p>On paper, this looked ideal. In practice, it was dead on arrival.</p><p><strong>Why Extreme Width Breaks Down</strong>:</p><p>In ClickHouse, each column is a first-class entity:</p><ul><li>It has its own data files and mark files per part</li><li>It participates independently in merges</li><li>It contributes metadata that must be tracked, planned, and opened at query time</li></ul><p>At tens of thousands of columns, these costs compound quickly.<br>Even before considering query complexity, the system had to:</p><ul><li>Manage and reason about thousands of column files per part</li><li>Open and coordinate large numbers of file handles</li><li>Perform background merges that touch every column, regardless of how many are queried</li></ul><p>This overhead exists <strong>independent of the ingestion mechanism</strong>. While ClickPipe can mitigate write-time memory pressure by streaming data from object storage, it does not eliminate the operational costs of maintaining and merging extremely wide parts.</p><p>Even on a reduced dataset of 1000 frames, early queries exhibited disproportionate overhead:</p><pre>Duration: 1167 ms<br>Memory:   52 MiB<br>Parts:    40</pre><p>The parts selected metric revealed the problem: ClickHouse was opening 40 separate files. Despite reading very little actual data, query execution was dominated by column metadata handling rather than I/O or computation.</p><p>At this scale, the benefits of column pruning were outweighed by the cost of managing the column set itself.</p><p><strong>Lesson:</strong></p><ul><li>Extremely wide tables impose metadata, merge, and planning overheads that eventually dominate execution time.</li><li>Columnar databases are optimized for scanning fewer columns, not for managing tens of thousands of them.</li><li>In practice, to support ~300 audiences the ~50,000 columns is well beyond the operational comfort zone of a ClickHouse table — regardless of whether data arrives via direct INSERTs or through ClickPipe.</li></ul><h4>The Array Approach: A Promising Middle Ground</h4><p>We pivoted to arrays. Instead of 168 columns per audience, one column containing an array of 168 values:</p><pre>CREATE TABLE frames_hourly_insights_array (<br>    id String,<br>    dma LowCardinality(String),<br>    -- ... other frame attributes ...<br>    -- 168-element array per audience (7 days × 24 hours)<br>    -- Index = day_index × 24 + hour + 1 (Mon=0, Tue=1, ..., Sun=6)<br>    all_adults_impressions Array(Float32),<br>    `audience1_impressions` Array(Float32),<br>    `audience2_impressions` Array(Float32),<br>    -- ... 100 audience columns total ...<br>)</pre><p>Now we had:</p><ul><li>~100 audience columns instead of 16,800</li><li>Clean writes</li><li>Much lower metadata overhead</li></ul><p>Initial tests with 80,000 frames and 100 audiences on local were promising:</p><pre>Duration: 137 ms<br>Memory:   21.7 MiB<br>Parts:    2</pre><p>For a moment, this felt like the solution.</p><p><strong>The Query Pattern Trap:</strong></p><p>Those early tests used a simplified calculation:</p><ul><li>Sum impressions across selected hours</li><li>Compute one index from the totals</li></ul><p>But that wasn’t the real requirement.<br>The correct computation is: For each selected hour h:</p><ol><li>frame_ratio[h] = audience[h] / total[h]</li><li>natural_delivery[h] = SUM(audience[h]) / SUM(total[h]) (per DMA)</li><li>hourly_index[h] = frame_ratio[h] / natural_delivery[h] × 100</li></ol><p>Final score = AVG(hourly_index[h])</p><p>This requires joining at an hourly granularity<strong>.</strong></p><p><strong>Query</strong>:</p><pre>WITH target_hours AS (<br>      -- Array index = day_index * 24 + hour + 1 (Mon=0, Tue=1, ..., Fri=4)<br>      SELECT arrayJoin([<br>          9, 10, 18, 19,      -- Monday: 8am, 9am, 5pm, 6pm<br>          33, 34, 42, 43,     -- Tuesday<br>          57, 58, 66, 67,     -- Wednesday<br>          81, 82, 90, 91,     -- Thursday<br>          105, 106, 114, 115  -- Friday<br>      ]) AS hour_idx<br>  ),<br>  exploded AS (<br>      SELECT<br>          id,<br>          dma,<br>          hour_idx,<br>          all_adults_impressions[hour_idx] AS all_adults_imp,<br>          audience_impressions[hour_idx] AS audience_imp<br>      FROM frames_hourly_insights_array<br>      CROSS JOIN target_hours<br>  ),<br>  hourly_nat AS (<br>      SELECT<br>          dma,<br>          hour_idx,<br>          sum(audience_imp) / sum(all_adults_imp) AS natural_delivery<br>      FROM exploded<br>      GROUP BY dma, hour_idx<br>  ),<br>  hourly_index AS (<br>      SELECT<br>          e.id,<br>          e.dma,<br>          (e.audience_imp / e.all_adults_imp) / n.natural_delivery * 100 AS hour_index<br>      FROM exploded e<br>      JOIN hourly_nat n<br>          ON e.dma = n.dma<br>          AND e.hour_idx = n.hour_idx<br>  )<br>  SELECT<br>      id,<br>      dma,<br>      round(avg(hour_index), 2) AS audience_index<br>  FROM hourly_index<br>  GROUP BY id, dma<br>  HAVING audience_index &gt;= 100<br>  ORDER BY audience_index DESC</pre><p>With arrays, that means one thing: <strong>explosion</strong>.</p><p>To join per-hour natural delivery, arrays must be converted into rows, which turns:</p><p>80,000 frames * 1 row to 80,000 frames * 24 hours = 1,920,000 rows</p><p>Every query. This intermediate explosion:</p><ul><li>Consumes memory</li><li>Adds CPU overhead</li><li>Defeats the original elegance of the array schema</li></ul><p><strong>Lesson</strong>:</p><ul><li>Arrays are cheap to store. Exploding arrays repeatedly is not.</li><li>The array-based model would have been a good fit if the requirement were to aggregate impressions across hours first, rather than compute hour-level indices before aggregation.</li></ul><h4>The “Wrong” Solution: Pre-Exploded Rows</h4><p>Against our instincts, we tried a schema that already lived at the query’s natural grain:</p><pre>CREATE TABLE frames_hourly_insights_row_based (<br>    id String,<br>    dma LowCardinality(String),<br>    -- ... other frame attributes (repeated 168× per frame!) ...<br>    day_of_week LowCardinality(String),  -- &#39;mon&#39;, &#39;tue&#39;, etc.<br>    hour_of_day UInt8,                    -- 0-23<br>    all_adults_impressions Float32,       -- Single value for this hour<br>    `audience1_impressions` Float32,<br>    `audience2_impressions` Float32,<br>    -- ... 100 audience columns ...<br>)</pre><p>The Pre-Exploded table is ordered by (dma, day_of_week, hour_of_day, id), ensuring data locality for both hourly natural delivery aggregation and frame-level joins.</p><p>However, with this approach, each frame becomes <strong>168 rows</strong> — one per hour.</p><p>Yes:</p><ul><li>Frame attributes are repeated</li><li>Row count explodes</li><li>Storage grows dramatically</li></ul><p>But look at the shape:</p><pre>dma | day | hour | id | audience impressions</pre><p>This is exactly what the query wants.</p><ul><li>No array explosion.</li><li>No CROSS JOIN.</li><li>Just filters and joins on native columns.</li></ul><p><strong>Query</strong>: Query for determining frames for weekdays between <em>8–10 am and 5–7 pm </em>becomes natural:</p><pre>WITH hourly_nat AS (<br>      SELECT<br>          dma,<br>          day_of_week,<br>          hour_of_day,<br>          sum(audience_impressions) / sum(all_adults_impressions) AS natural_delivery<br>      FROM frames_hourly_insights_row_based<br>      WHERE day_of_week IN (&#39;mon&#39;, &#39;tue&#39;, &#39;wed&#39;, &#39;thu&#39;, &#39;fri&#39;)<br>        AND hour_of_day IN (8, 9, 17, 18)<br>      GROUP BY dma, day_of_week, hour_of_day<br>  ),<br>  hourly_index AS (<br>      SELECT<br>          r.id,<br>          r.dma,<br>          (r.audience_impressions / r.all_adults_impressions)<br>              / n.natural_delivery * 100 AS hour_index<br>      FROM frames_hourly_insights_row_based r<br>      JOIN hourly_nat n<br>          ON r.dma = n.dma<br>          AND r.day_of_week = n.day_of_week<br>          AND r.hour_of_day = n.hour_of_day<br>      WHERE r.day_of_week IN (&#39;mon&#39;, &#39;tue&#39;, &#39;wed&#39;, &#39;thu&#39;, &#39;fri&#39;)<br>        AND r.hour_of_day IN (8, 9, 17, 18)<br>  )<br>  SELECT<br>      id,<br>      dma,<br>      round(avg(hour_index), 2) AS audience_index<br>  FROM hourly_index<br>  GROUP BY id, dma<br>  HAVING audience_index &gt;= 100<br>  ORDER BY audience_index DESC</pre><p>Let’s break down what this query does:</p><ul><li>hourly_nat CTE: For each DMA + day + hour combination, calculate the market’s natural delivery (what percentage of all impressions are from our target audience?)</li><li>hourly_index CTE: For each frame at each hour, compare the frame’s audience concentration to the market average. A frame where 15% of viewers are young professionals in a market where only 10% are — that’s an index of 150.</li><li>Final aggregation: Average each frame’s hourly indices to get one score per frame.</li></ul><p>No CROSS JOIN. No array explosion. Just a natural join on existing dimensions.</p><h4>Results: Less Data Magic, More Performance</h4><p>At 80,000 frames with hourly-level index calculation:</p><pre>| Metric         | Array Table | Pre-Exploded Table| Winner                  |<br>|----------------|-------------|-------------------|-------------------------|<br>| Query Duration | 1,391 ms    | 718 ms            | Pre-Exploded 1.9x faster|<br>| Query Memory   | 95.73 MiB   | 69.11 MiB         | Pre-Exploded 1.4x less  |<br>| Bytes Read     | 211.54 MiB  | 614.32 MiB        | Array (2.9× less)       |<br>| Storage Rows   | 160,002     | 17,694,010        | Array (110× less)       |</pre><p>The Pre-Exploded table reads more data but processes it faster because:</p><ol><li><strong>No intermediate explosion</strong>: Data is already at the right granularity</li><li><strong>Efficient joins</strong>: Day and hour are native columns, not computed indices</li><li><strong>Lower memory</strong>: No need to materialize exploded array data</li></ol><h3>What This Is <em>Really</em> About</h3><p>This wasn’t a win for Pre-Exploded storage over columnar storage.</p><p>It was a win for <strong>matching schema grain to query grain</strong>.</p><p>All three designs were columnar in the physical sense. The difference was where data reshaping happened:</p><ul><li>The wide-table design pushed complexity into <strong>the schema width</strong></li><li>The array-based design pushed complexity into <strong>runtime reshaping</strong></li><li>The pre-exploded design pushed complexity into <strong>storage</strong></li></ul><p>Only one of those aligned with how the query actually executed.</p><ul><li>Arrays work beautifully when you aggregate within them.</li><li>Arrays become expensive when you must repeatedly explode and rejoin them.</li><li>Pre-exploded data trades storage efficiency for predictable execution, stable memory usage, and simpler queries. Beyond median latency, this design exhibited more predictable memory usage, making it safer under concurrent query load.</li></ul><p>The deeper lesson is this:</p><blockquote><strong><em>If your query needs to repeatedly reshape data at runtime, that reshaping likely belongs in the schema.</em></strong></blockquote><p>This principle isn’t ClickHouse-specific. It applies to any analytical system where correctness, latency, and predictability matter more than theoretical elegance.</p><p>Schema design is ultimately about choosing where complexity lives.<br>In this case, putting that complexity into storage turned out to be the least expensive option.</p><h4>Key Takeaways</h4><ul><li><strong>Schema design is query-driven</strong><br>Don’t design for elegance — design for how the data is actually consumed.</li><li><strong>Avoid runtime reshaping in hot paths</strong><br>Array explosion, CROSS JOINs, and dynamic joins are often more expensive than extra rows.</li><li><strong>Columnar systems still have practical limits</strong><br>Thousands of columns introduce memory and metadata overhead.</li><li><strong>Benchmark real queries, not toy ones</strong><br>Our initial tests favored arrays — until we ran the real calculation.</li><li><strong>Storage is cheaper than correctness bugs and slow queries</strong><br>Especially when user-facing performance is involved. In practice, the storage overhead is mitigated by efficient compression: low-cardinality dimensions (day_of_week, dma) and compact numeric types compress extremely well in ClickHouse.</li></ul><h4>Closing Thought</h4><p>Sometimes a theoretical “wrong” approach is right. The goal isn’t schema purity, it’s query performance. And performance comes from understanding your access patterns, not from following architectural dogma.</p><blockquote><strong>Build what works. Measure. Iterate.</strong></blockquote><h3>About the Author</h3><p>I am a software engineer with 15+ years of experience building data-intensive systems. I work on building distributed systems and analytical platforms, with a focus on understanding systems from first principles. I like to document engineering tradeoffs and lessons learned from building systems under practical constraints.</p><h3>Review Credits</h3><p>Thanks, <a href="https://www.linkedin.com/in/amaansh08/">Amaan</a>, <a href="https://www.linkedin.com/in/puneet-sharma-709a1116/">Puneet</a> for reviewing this post and providing valuable feedback.</p><p><em>Tested on ClickHouse 24.1 on a local Docker container with 8GB RAM. Results may vary based on hardware, data distribution, and ClickHouse version.</em></p><p><strong><em>Tags</em></strong><em>: ClickHouse, Database Design, Schema Design, Columnar Databases, Performance Optimization, Data Engineering</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4abc31d1b894" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-data/designing-olap-schemas-by-query-shape-4abc31d1b894">Designing OLAP Schemas by Query Shape</a> was originally published in <a href="https://medium.com/dev-data">DevData</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mobile facade to simplify mobile app development]]></title>
            <link>https://medium.com/dev-data/mobile-facade-to-simplify-mobile-app-development-ab822a3ee577?source=rss----76dbf3dd6784---4</link>
            <guid isPermaLink="false">https://medium.com/p/ab822a3ee577</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-facade]]></category>
            <category><![CDATA[backends-for-frontends]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Swapnil Sankla]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 06:46:36 GMT</pubDate>
            <atom:updated>2026-02-14T06:46:37.859Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, I will walk you through the journey of evolution of the mobile facade layer which we wrote while developing iOS and Android mobile applications. These applications consume APIs written by external vendors. APIs are developed primarily to cater data to the web application. To handle the situation we applied <a href="https://en.wikipedia.org/wiki/Facade_pattern">Facade design pattern</a>. The low level design of the facade is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PoSXqJdee5b2uVcWj49C1w.png" /><figcaption>Low level design</figcaption></figure><p>But you must be wondering why to write and maintain an extra layer. Right? To answer, let me walk you through the journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*b9A7-zumSOn2sHLyhTIPpg.jpeg" /><figcaption><strong><em>But why mobile facade?</em></strong></figcaption></figure><h3><em>Journey</em></h3><p>As I have mentioned before, mobile apps were hitting the APIs which cater data to web application. API responses created for website were sent to mobile apps <em>as-is</em>. We started consuming these backend APIs and soon, we realised that we are fetching a significant amount of data which is absolutely not needed for mobile. Hence we decided to add a server-side <em>thin</em> component which will filter out the unnecessary before passing responses to mobile. This component is deployed on the same server where backend services are deployed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R6F3n1oz-TQkJRp6CCfWfw.png" /><figcaption>High Level Design</figcaption></figure><p>This layer is owned by Mobile Team. The layer also helps in reducing the impact of the changes made in backend APIs. In future, entire backend API can be replaced by another API without impacting mobile applications (of course, if contract is adhered)</p><ul><li><strong>Anti-corruption</strong></li></ul><p>The Backend APIs are not Http compliant. For example, API returns Http status code 200 for both success and failure. Response body contains a status flag which indicates if the API call is successful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fpt_AewtIJ3u3NNGoBzw8w.png" /><figcaption>Error Response</figcaption></figure><p>This makes client code slightly complicated as the success handler needs to check the status flag and then trigger the error handling routine if needed. This needed to be addressed by creating a shield around backend APIs. Hence, we started to transform API responses to make them HTTP compliant. Such damage control falls under category of <em>Anti-corruption</em>.</p><blockquote>The intent of Anti-corruption is to either:</blockquote><blockquote>1. Create adapters to make backend systems suitable for modern applications.</blockquote><blockquote>2. Hide the design issues of the backend APIs.</blockquote><p>Martin fowler has written an amazing <a href="https://martinfowler.com/articles/refactoring-external-service.html">blog</a> about this.</p><ul><li><strong>Aggregator</strong></li></ul><p>While implementing a feature, we came across a requirement where we needed to hit multiple backend APIs sequentially. The output of the first API was provided as an input to the next one. No user intervention was required between these calls. So making multiple calls from mobile, it actually made sense to aggregate these backend API calls in the facade.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1eddBwiLI5x0R_oARBZpqw.png" /><figcaption>Call Aggregation</figcaption></figure><p><em>Benefits:</em></p><ol><li>Single vs multiple network calls.</li><li>Mobile does not need to know all backend endpoints.</li><li>If backend calls are independent, then those can be executed in parallel.</li></ol><ul><li><strong>Contract validation</strong></li></ul><p>Soon after we published our apps, many crashes were reported. Most of the crashes were due to failure of parsing API responses. Following were the issues:</p><ol><li>Mandatory nodes missing</li><li>Data type mismatch</li></ol><p>The root cause is the missing contract between Mobile and API Team. However, API Team refused to develop against client contracts. This led us to add a contract validation in the facade layer. If the backend response fails to adhere to the expected contract, a failure response is returned from facade to app.</p><ul><li><strong>Mobile friendly transformations</strong></li></ul><p>Life was great after customising facade layer to support things listed above. The Facade was following <a href="https://www.thoughtworks.com/insights/blog/rest-api-design-resource-modeling">REST</a> practices. REST is about treating your domain model as resource. You query for a resource and you get it back. So simple, right? But to display the details of the resource, mobile needed to create ViewModel first. Now the creation of these viewModels was repeated on each platform. To avoid this duplication, we decided to return ViewModel as resource instead of the domain model from the facade.</p><blockquote>Here, I am referring ViewModel as the object which is responsible for preparing and managing the data for view. It’s not the VM in MVVM.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gS46LP9G4IgkvRJxmNYmwQ.png" /></figure><p>Mobile Apps started binding the received responses directly to the views. This was an important step in process of making apps lighter.</p><p><em>Following diagram depicts how it works. Assuming UI needs to display user’s full name on the screen. API is returning the firstName and lastName nodes separately. Facade can combine these two as per the UI need and then mobile application directly binds this to the UI label.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zRFosmVyolKfCCRKj2MulQ.png" /><figcaption>Mobile Friendly Transformation</figcaption></figure><blockquote>Handling localisation can be tricky with this approach though.</blockquote><ul><li><strong>Links driving User capabilities</strong></li></ul><p>In the process of making apps lighter, one of the key consideration is how an availability of a particular feature can be controlled. Let’s take simple example of a mobile application which displays books in the library. On selecting a particular book; options like <em>view preface</em>, <em>request book, claim book </em>appears on the screen. However there are rules which drives which options are displayed.</p><ol><li><em>View preface</em> option is always displayed.</li><li><em>Request book</em> option is displayed only when book is available in the library.</li><li>Else <em>Claim book</em> option is displayed.</li></ol><p>Mobile can contain logic of determining which option to display. However simpler would be; the mobile facade tells the list of operations which are possible on the particular resource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YeNVSSSFi0IECv2sW6iTSw.png" /><figcaption>Driving User Capabilities Via Facade</figcaption></figure><p>When user selects a book, mobile code reads the links of the book and then creates the buttons on runtime based on the links present. With this approach, mobile code refers to the <em>href </em>and makes the API call. <em>No need to know these endpoints upfront!</em> This means you get a flexibility of changing the actual endpoints like <em>viewPreface, requestBook, claimBook</em> without making any change in mobile.</p><blockquote>No need to repeat the business logic of determining which features to be turned on/off on every platform.</blockquote><p>This is how you can leverage <a href="https://en.wikipedia.org/wiki/HATEOAS">HATEOAS</a> to make apps lighter.</p><ul><li><strong>Sidekicks</strong></li></ul><ol><li><strong>Compression</strong>: <a href="http://www.gzip.org/algorithm.txt">Gzip</a> for compressing API responses.</li><li><strong>Monitoring</strong>: <a href="https://github.com/prometheus">Prometheus</a> for Service monitoring.</li><li><strong>Circuit breakers</strong>: <a href="https://github.com/Netflix/Hystrix">Hystrix</a> for circuit breakers.</li></ol><p>Looking at the offerings below, we can say Mobile facade is playing role of <em>Backends for Frontends (BFF)</em></p><ol><li>Filtering unnecessary data</li><li>Mobile friendly transformations</li><li>Links driving User capabilities</li><li>Aggregating backend API calls.</li></ol><p>BFF has a simple intent of simplifying the client development. Sam Newman has explained this in depth in one of his <a href="http://samnewman.io/patterns/architectural/bff/">blog</a>.</p><p><em>I hope you enjoyed the journey of evolution of the facade. We started with a simple intent however with the evolution; facade is playing a vital role in the success of our apps.</em></p><p>But I faced one issue with BFF; response gets tightly coupled with the view. Hence you should consider this fact while designing.</p><blockquote><strong>Problem: Tight coupling of a response with View</strong></blockquote><p>With BFF, mobile facade response gets tightly coupled with a particular view. A requirement may come wherein same backend data needs to be rendered in the different format.</p><p>Let’s take an example where backend API sends you the information for the students along with the courses they are appearing for. To make suitable for UI, you transform the response where response would be first grouped by Student and then by subject. However on another UI you might want to show response group by the subject first. Then response created first would not be suitable for the second UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yH1Dn5jukSrP5E8TqnbEHQ.png" /></figure><p><strong>Solution</strong>: Create separate BFF endpoints for the individual screens. Both endpoints hit the REST endpoint <em>/students.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AGS7sDnaY93BCn1sCDqfqw.png" /></figure><h4><strong>Please share/recommend if you like this article.</strong></h4><p>This blog is also published on my personal website <a href="https://swapnilsankla.me/">https://swapnilsankla.me</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Flcontacts.herokuapp.com%2Fembed%2Fbutton%2Fwritercta%3FuserId%3D5a44f97a7bfcde6dec7f96ca%26mediumUserId%3D1eeba460bbc07b38adf03072e846287c4c87d63602ef49ec886d1b993d4a06ecd&amp;src=https%3A%2F%2Flcontacts.herokuapp.com%2Fembed%2Fbutton%2Fwritercta%3FmediumUserId%3D1eeba460bbc07b38adf03072e846287c4c87d63602ef49ec886d1b993d4a06ecd&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=lcontacts" width="480" height="350" frameborder="0" scrolling="no"><a href="https://medium.com/media/caae511ad99980369e61d40841093b64/href">https://medium.com/media/caae511ad99980369e61d40841093b64/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab822a3ee577" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-data/mobile-facade-to-simplify-mobile-app-development-ab822a3ee577">Mobile facade to simplify mobile app development</a> was originally published in <a href="https://medium.com/dev-data">DevData</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lexical scoping in Swift]]></title>
            <link>https://medium.com/dev-data/lexical-scoping-in-swift-ba95ab949b0c?source=rss----76dbf3dd6784---4</link>
            <guid isPermaLink="false">https://medium.com/p/ba95ab949b0c</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[lexical-scoping]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Swapnil Sankla]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 06:46:20 GMT</pubDate>
            <atom:updated>2026-02-14T06:46:22.164Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dghPOQXBfVFqlObWOxY2gQ.png" /><figcaption><a href="https://swift.org/">https://swift.org/</a></figcaption></figure><p>While going through lexical scoping concept in <a href="https://en.wikipedia.org/wiki/Lisp_(programming_language)">LISP</a>; I wondered whether such support is available in Swift or not. And it does. Yay…</p><p>I took a simple function — <em>square root of a number</em> to try out the lexical scoping. I used <a href="https://en.wikipedia.org/wiki/Newton%27s_method">Newton’s</a> method for calculating square roots. Below is the first version.</p><blockquote>sqRt is a recursive function. The code terminates when the guess made in earlier step is good enough. Else guess is improved and function is called again.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a947a1842dc14da6cce47517cd8046b7/href">https://medium.com/media/a947a1842dc14da6cce47517cd8046b7/href</a></iframe><p>But then functions like <em>goodEnough</em> and <em>improveGuess </em>does not make any sense outside squareRoot function scope. Thankfully in Swift, <em>functions are first class citizen</em>. We can declare function just like declaring variable. This brings me to the second version of <em>sqRt</em> function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f2c15abfc910f052b0e486a07200da1/href">https://medium.com/media/5f2c15abfc910f052b0e486a07200da1/href</a></iframe><p>Functions like <em>improveGuess</em>, <em>goodEnough</em> are operating on the function parameters of <em>sqRt</em>. As these functions are already in the scope of <em>sqRt</em> function, one can argue that passing parameters to these inner functions is redundant. Which is indeed true and that’s what is addressed with <em>lexical scoping</em>. Parameters/ variables of the enclosing function are in scope for these functions.</p><blockquote>A language with <a href="http://wiki.c2.com/?LexicalScoping">LexicalScoping</a> has following characteristics:</blockquote><blockquote>1. Functions (and procedures, etc.) can be defined within other functions</blockquote><blockquote>2. Such inner functions have access to the local variables defined in the enclosing scope.</blockquote><blockquote>3. These inner functions also have an access to the function parameters of the enclosing function.</blockquote><p>Version 3 of the <em>sqRt</em> function by leveraging lexical scoping support is as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/844fa186fbdba63cf18818f075b2d03b/href">https://medium.com/media/844fa186fbdba63cf18818f075b2d03b/href</a></iframe><p>Hey wait! Why can’t we leverage Swift’s support further to concise the code. <em>Square</em>, <em>goodEnough</em> and <em>improveGuess</em> look like variables. So let’s simplify those.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5abf83bcd1ed0ca6044d35a51149d068/href">https://medium.com/media/5abf83bcd1ed0ca6044d35a51149d068/href</a></iframe><p>I hope you understood lexical scoping support in Swift. Let me know your thoughts on this.</p><h4>Please share/recommend if you like this article.</h4><p>This blog is also published on my personal website <a href="https://swapnilsankla.me/">https://swapnilsankla.me</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Flcontacts.herokuapp.com%2Fembed%2Fbutton%2Fwritercta%3FuserId%3D5a44f97a7bfcde6dec7f96ca%26mediumUserId%3D1eeba460bbc07b38adf03072e846287c4c87d63602ef49ec886d1b993d4a06ecd&amp;src=https%3A%2F%2Flcontacts.herokuapp.com%2Fembed%2Fbutton%2Fwritercta%3FmediumUserId%3D1eeba460bbc07b38adf03072e846287c4c87d63602ef49ec886d1b993d4a06ecd&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=lcontacts" width="480" height="350" frameborder="0" scrolling="no"><a href="https://medium.com/media/caae511ad99980369e61d40841093b64/href">https://medium.com/media/caae511ad99980369e61d40841093b64/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba95ab949b0c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-data/lexical-scoping-in-swift-ba95ab949b0c">Lexical scoping in Swift</a> was originally published in <a href="https://medium.com/dev-data">DevData</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fragile -> Agile]]></title>
            <link>https://medium.com/dev-data/fragile-agile-4611ecfceb32?source=rss----76dbf3dd6784---4</link>
            <guid isPermaLink="false">https://medium.com/p/4611ecfceb32</guid>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[agile-development]]></category>
            <category><![CDATA[extreme-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Swapnil Sankla]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 06:46:03 GMT</pubDate>
            <atom:updated>2026-02-14T06:46:04.606Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*cQefRg5tpfY0N4hSrlpeIw.png" /><figcaption><a href="https://www.google.co.in/search?q=Think+beyond+images&amp;tbm=isch&amp;source=iu&amp;ictx=1&amp;fir=FT05cLzO5z12vM%253A%252CA-B9eT3if0k9MM%252C_&amp;usg=__KGOxrqyPs5Dd1xH6u3q2qwshxN0%3D&amp;sa=X&amp;ved=0ahUKEwiYyNX96r7ZAhUGvLwKHbgSByYQ9QEIKjAB#imgrc=FT05cLzO5z12vM:">Image source</a></figcaption></figure><p>Folks, you must be wondering what kinda title is this! But I would like to share my experience of how we turned the Fragile development into working Agile development.</p><p>@<a href="https://medium.com/u/8075bdd73dd9">ThoughtWorks</a> every project follows Agile software development practice. Our project is no exception. We were following most of the rituals.</p><ol><li>Pair programming</li><li>Continuous Integration</li><li>TDD, BDD</li><li>Agile ceremonies like standup, iteration planning meet-up, retros blah blah blah…</li></ol><p>List seems sufficient to qualify for Agile, isn’t it? However there were many things which we were doing incorrectly. So instead of Agile, the process was actually qualifying for ‘Fragile development’ (name credits: <a href="https://twitter.com/bhattvardhan">Vardhan</a>)</p><p>Ok so what were we doing wrong?</p><ol><li>Everyday starts with a standup however not everyone in Team is attending standup.</li><li>CI practices are followed but no one bothers about the failures in the Functional pipelines. Only core build and unit test pipelines receives that respect.</li><li>We begin iteration with a planning meeting, we commit to complete X points however almost every time we miss to achieve it. Still no one recons the smell. Instead of solving the problem, someone tossed up a new term ‘Healthy spillover’ 😞</li><li>Let’s assume that while working on a story, dev pair identifies 10 things to refactor. But they able to knock off only 5 due to various reasons. Sad part is, details of the smells which were identified but not addressed are not captured anywhere.</li><li>We typically follow a ratio of 1 QA person per 2/3 dev pairs. Developers focus on story implementation and move stories to QA bucket. As devs churn work fast, the QA bucket keeps on growing. QA need to write automation test, perform manual test around the story and do sanity test of app. This creates a panic during last days on the iteration. Developer assumes <em>implementation done =&gt; story complete.</em> S/he picks up a new story but don’t feel like helping QA so that the stories would be completed faster.</li><li>Due to the panic which QA Team faces while testing the story, they don’t get time to write the Functional/Automation tests. Stories are moved to DONE without the tests. And these tests are written in next iteration iff QA Team gets time.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7J4krXa8AfdLX3ebFSXHJw.png" /><figcaption><a href="https://www.google.co.in/search?q=gorilla+thinking+image&amp;tbm=isch&amp;tbo=u&amp;source=univ&amp;sa=X&amp;ved=0ahUKEwiw4eaghMDZAhUMLI8KHcP3D-UQsAQIJQ&amp;biw=1307&amp;bih=669#imgrc=KYWyifAfh-ft9M:">Image Source</a></figcaption></figure><p>Sounds like we are doing enough wrong things and hence we cannot say that we are Agile. Apparently we started new project. My BA(<a href="https://twitter.com/bhattvardhan">Vardhan</a>) and I decided to address these concerns. Simple tricks helped us. Below is how.</p><ol><li>We started penalties for people who miss standup and for latecomers. Few bucks for every miss! Cool isn’t it! However as money is the easiest thing to pay, people started paying the dues without realising that missing standup is a problem.</li></ol><blockquote>Every person who miss standup or come late has to do X push ups in front of the Team. Crazy right! But it worked, now everyone is on time every time.</blockquote><p>2. We made a rule that developers cannot push a code if the functional pipeline is red. Initially people resisted the idea however later on everyone started owning up these functional pipelines just as they own the core build pipelines.</p><blockquote>The success rate of functional pipeline is more than 75%. There are no flaky tests. Random/flaky behaviours are detected and fixed early.</blockquote><p>3. We made sure that we complete whatever we signup in the iteration planning meeting. Of course sometimes this can be tricky when there are factors which you cannot control e.g. unavailability of APIs. However apart from such external dependencies; we should not give any other excuse.</p><blockquote>No spillover in last 7 iterations. First time on the account in last 5–6 years.</blockquote><p>4. We started tracking refactoring which a pair identified but could not complete. We started managing this in a separate tech. task board. Anyone can signup to complete these at anytime.</p><blockquote>Separate board to track remaining refactoring/ tech. tasks. We trust our tests and hence we can carry out such refactoring at any time.</blockquote><p>5. Developers started owning up the Automation tests. Just like unit and integration tests, devs write functional tests before moving story to QA bucket. QA can pair with the devs for these tests.</p><blockquote>Devs to own Functional automation along with QAs.</blockquote><p>6. Devs/ QA pairs up with BA for requirement gathering, analysing API responses. During the last 2–3 panic days of iteration, devs and BA contributes in testing stories.</p><blockquote>Think beyond building cross functional Teams. Make sure that people are open to help other roles as well. Every Individual can do/help in analysis, development, testing etc.</blockquote><p>With these small things everyone started feeling motivated. Everyone in the Team cherish moments when story is marked as done. In an iteration of 2 weeks, we now complete signed up items in 8–9 days. We save at least a day every iteration! Awesome isn’t it? But what to do with this extra day? We started a new experiment in which every Team member gets a day to explore whatever thing s/he wants to do. It can be literally anything like learning a new language, knocking off tech. tasks or even enhancing Table Tennis skills! It’s now 3 iterations since we started this and everyone waits for that day to come. 😮😮😮</p><h4>Please clap/share/recommend if you like this article.</h4><p>This blog is also published on my personal website <a href="https://swapnilsankla.me/">https://swapnilsankla.me</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4611ecfceb32" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-data/fragile-agile-4611ecfceb32">Fragile -&gt; Agile</a> was originally published in <a href="https://medium.com/dev-data">DevData</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write your own Network layer in Swift]]></title>
            <link>https://medium.com/dev-data/write-your-own-network-layer-in-swift-36ae4e205876?source=rss----76dbf3dd6784---4</link>
            <guid isPermaLink="false">https://medium.com/p/36ae4e205876</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[rxswift]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Swapnil Sankla]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 06:45:47 GMT</pubDate>
            <atom:updated>2026-02-14T06:45:48.956Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*raVG7rFGzlRqRlc_UjrxMg.jpeg" /><figcaption><a href="https://www.google.co.in/url?sa=i&amp;rct=j&amp;q=&amp;esrc=s&amp;source=images&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwj057KmlpTcAhVFWH0KHSKSDB8QjRx6BAgBEAU&amp;url=https%3A%2F%2Fwww.flickr.com%2Fphotos%2F86530412%40N02%2F7975205041&amp;psig=AOvVaw12wlOtbIng86oSi9FKIknJ&amp;ust=1531299636053207">Image source</a></figcaption></figure><p>Let us try to build our own Network layer in pure Swift. It is super simple to build with Swift’s strong support for generics, type inference</p><p>So let’s start with basics. This network layer is based on <a href="https://developer.apple.com/documentation/foundation/urlsession">URLSession</a> object. By definition this is <em>an object that coordinates a group of related network data transfer tasks</em>. You don’t even need to create a custom object of URLSession in most of the cases. We will also keep it simple and use the default <em>shared</em> instance.</p><blockquote><strong>Get Requests</strong></blockquote><p>To make a GET request let’s use a dataTask method on URLSession. The method looks like below.</p><pre>open func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -&gt; Swift.Void) -&gt; URLSessionDataTask</pre><p>We need to pass following parameters:</p><ol><li><strong>request</strong>: GET requests are pretty simple. We just need endpoint and header details. We can create the URLRequest with these.</li></ol><p>2. <strong>completionHandler</strong>: It is called as a result of request execution. It contains following fields</p><ul><li><em>data: Data? :</em> Contains the response in Data form. As the signature suggests, it is optional. When request succeeds you get data else it will be nil.</li><li><em>urlResponse: URLResponse? :</em> Contains auxiliary details like</li></ul><ol><li>mimeType</li><li>encoding</li><li>Headers</li><li>Status code etc.</li></ol><ul><li><em>error: Error? : </em>Contains error information. On success you receive it as nil.</li></ul><p>To determine whether the request has actually succeeded or not, we rely on each of these.</p><p>With above details I wrote my first network layer code.</p><h4><strong>First attempt:</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d5d1cf5b17b8fd23955f60fbb571889/href">https://medium.com/media/3d5d1cf5b17b8fd23955f60fbb571889/href</a></iframe><p>Bingo! It’s super simple. Make sure you call resume() method so that the suspended task gets picked up for execution.</p><p>Though the above code is simple however the caller needs to do a lot of things. It needs to take care of building and processing urlRequest and completionHandler. Most of the code which caller writes is actually common. So let’s try to simplify that.</p><h4>Second attempt:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13f96a7a3836c2d812a4cd32c087d800/href">https://medium.com/media/13f96a7a3836c2d812a4cd32c087d800/href</a></iframe><p><em>What did I change?</em></p><ol><li>Instead of completionHandler now the get method accepts success and error handlers.</li><li>Success handler is called when the response contains success status code and response is convertible into Data. This makes caller code very easy. Either success or error handler gets called. Caller just need to do the processing accordingly.</li></ol><p>Taking a closer look, I felt converting Data to appropriate response object task is also common among all consumers. So why should everyone repeat the logic? That brought me to the third attempt.</p><h4>Third attempt:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daf1a200a20256cd5be7a04531bd9f87/href">https://medium.com/media/daf1a200a20256cd5be7a04531bd9f87/href</a></iframe><p><em>What did I change?</em></p><ol><li>SuccessHandler signature is changed to (T) -&gt; Void. Instead of sending Data let’s send the concrete object itself.</li><li>T is restricted to be Decodable. <em>This is the secret recipe</em>. With Codables, we don’t need to write our own parsers to convert data to the appropriate type.</li></ol><p>So now how does client code looks like? It’s as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b54c141fc704eede6193faec552e230a/href">https://medium.com/media/b54c141fc704eede6193faec552e230a/href</a></iframe><p>Looking closely at caller’s code one can understand the power of <em>generics and type inference</em>. I don’t need to specify what network layer should return on success or on failure.</p><p>Still the creation of URLRequest can be extracted out. Let’s do that too!</p><h4>Fourth attempt:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56e86e7bee28c125b73806446b733f08/href">https://medium.com/media/56e86e7bee28c125b73806446b733f08/href</a></iframe><p><em>What did I change?</em></p><ol><li>Consumer just needs to send the endpoint and optionally the headers. Network layer takes care of building URLRequest and handling URL creation failure.</li></ol><p><strong><em>Error Handling</em></strong></p><p>Get method calls errorHandler in one of the following cases.</p><ol><li>URL creation failure</li><li>Response parsing failure</li><li>Status code based error handling</li><li>Network layer errors e.g. request timeout etc.</li></ol><blockquote><strong>POST Requests</strong></blockquote><p>POST requests are equally simple. To make a POST request let’s use a uploadTask method on URLSession. The method looks like below.</p><pre>func uploadTask(with request: <a href="/service/apple-reference-documentation://hs-y-qEskb">URLRequest</a>, from bodyData: <a href="/service/apple-reference-documentation://hsDZIxGRh8">Data</a>?, completionHandler: @escaping (<a href="/service/apple-reference-documentation://hsDZIxGRh8">Data</a>?, <a href="/service/apple-reference-documentation://hs88hIbE2g">URLResponse</a>?, <a href="/service/apple-reference-documentation://hsz_WFDkul">Error</a>?) -&gt; <a href="/service/apple-reference-documentation://hsHG2idfN6">Void</a>) -&gt; <a href="/service/apple-reference-documentation://hsB3UQSBmH">URLSessionUploadTask</a></pre><p>We need to pass following parameters:</p><ol><li><strong>request</strong>: URL request object.</li><li><strong>body</strong>: Data which needs to be uploaded</li><li><strong>completionHandler</strong>: We have already used this one in GET request.</li></ol><p>As we already know the power of generics, type inference. So based on that the post method looks like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f600b2c65abc2a09917804c989ef8d54/href">https://medium.com/media/f600b2c65abc2a09917804c989ef8d54/href</a></iframe><p><em>Things to consider</em></p><ol><li>T is restricted to encodable and without knowing the real type we can create Data object from it.</li><li>Caller does not need to take care of setting up common POST request params. Following are set inside post method.</li></ol><ul><li>headers</li><li>timeout</li><li>httpMethod</li><li>httpBody</li></ul><p>That’s it! The Network layer now supports GET and POST requests. Although it is not very powerful however it will suffice the need.</p><blockquote><strong>Unit testing</strong></blockquote><p>I have always seen problems while testing the code which calls network layer. So let’s check whether the caller code is testable or not.</p><p>We all know that Swift recommends to not to use mocks and rather rely on the other types of test doubles. We will use Dummy object to test caller method.</p><p>Let’s assume you want to test getExample() method from the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbe422be47a3f2de42247c8f4619d514/href">https://medium.com/media/cbe422be47a3f2de42247c8f4619d514/href</a></iframe><p><em>Things to consider:</em></p><ol><li>networkLayer is injected into Presenter. This makes it easy for us to inject the dummy object.</li><li>The default value of networkLayer is the real NetworkLayer. Hence the caller does not need to create and pass it.</li></ol><p>Let’s try to write a test for getExample() method. The focus is to verify whether displayEmployees() is being called or not. We don’t want our test to make real network calls right? So time for dummy objects!</p><p><em>Things to consider:</em></p><ol><li>Inject the dummy network layer while creating presenter.</li><li>Inject the dummy view so that we can easily test the view code and assert upon.</li><li>If we want to test the success case then set networkLayer.successResponse. Otherwise set networkLayer.errorResponse.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/366083cdf2e9791b17b4bf352c63d21a/href">https://medium.com/media/366083cdf2e9791b17b4bf352c63d21a/href</a></iframe><p>Cool! The code is easily testable, isn’t it? Similarly we can write test method for failure cases and also for the POST request.</p><p>You can find the complete code on <a href="https://github.com/SwapnilSankla/Swift_SimpleNetworkLibrary">github</a></p><p><a href="https://github.com/SwapnilSankla/Swift_SimpleNetworkLibrary/blob/master/Swift_SimpleNetworkLibrary/Classes/NetworkLayer.swift">SwapnilSankla/Swift_SimpleNetworkLibrary</a></p><p>I have published <em>Swift_SimpleNetworkLibrary</em> on <a href="https://cocoapods.org/pods/Swift_SimpleNetworkLibrary">cocoapods</a>. The framework also contains the DummyNetworkLayer. Hence the unit testing becomes very easy.</p><p>To install Swift_SimpleNetworkLibrary add following into your Podfile.</p><pre>pod &#39;Swift_SimpleNetworkLibrary&#39;</pre><blockquote><strong>Can Rx further simplify our network layer?</strong></blockquote><p>Let’s try to use RxSwift to build our network layer. I am not going into the details of the Rx concepts. Let’s check the usage directly. The network layer code looks something like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83cb9a0833545740535d62d7423c91ed/href">https://medium.com/media/83cb9a0833545740535d62d7423c91ed/href</a></iframe><p><em>Things to consider:</em></p><ol><li>Returning an observable on which the caller will have to observe upon.</li><li>Success and failure handlers are replaced with observer.onNext and observer.onError respectively.</li><li>Complete code goes inside a closure which is passed to Observables.create</li></ol><p>Now let’s look at the caller code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a18ffcfc5aa1f82982182d20787b3911/href">https://medium.com/media/a18ffcfc5aa1f82982182d20787b3911/href</a></iframe><p>We assign onNext and onError just like we set successHandler and errorHandler earlier. Here we get a disposable object from the network layer. It needs to be disposed appropriately.</p><p>Caller code remains mostly same in both the approaches. However the get method gets complicated with Rx. Hence after trying both approaches, at least I am convinced that callbacks are simpler than Rx in current use case. Rx are more powerful however here I don’t feel the need right now.</p><h4>Please clap/share/recommend if you like this article. 😃</h4><p>Reference: <a href="https://swapnilsankla.github.io/Swift_SimpleNetworkLibrary/">https://swapnilsankla.github.io/Swift_SimpleNetworkLibrary/</a></p><p>This blog is also published on my personal website <a href="https://swapnilsankla.me/">https://swapnilsankla.me</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36ae4e205876" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-data/write-your-own-network-layer-in-swift-36ae4e205876">Write your own Network layer in Swift</a> was originally published in <a href="https://medium.com/dev-data">DevData</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>