<?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 Abhishek G on Medium]]></title>
        <description><![CDATA[Stories by Abhishek G on Medium]]></description>
        <link>https://medium.com/@abhishek.g.abhi333?source=rss-c26a8d0d6d52------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gnewPs8tM26_Oq1h</url>
            <title>Stories by Abhishek G on Medium</title>
            <link>https://medium.com/@abhishek.g.abhi333?source=rss-c26a8d0d6d52------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 02:19:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhishek.g.abhi333/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[We Cut a 15-Minute Export Down to 10 Seconds by Deleting Code, Not Adding It]]></title>
            <link>https://medium.com/@abhishek.g.abhi333/we-cut-a-15-minute-export-down-to-10-seconds-by-deleting-code-not-adding-it-ea97755f0fba?source=rss-c26a8d0d6d52------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea97755f0fba</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Abhishek G]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 07:06:26 GMT</pubDate>
            <atom:updated>2026-07-10T08:03:56.318Z</atom:updated>
            <content:encoded><![CDATA[<p><em>5 million rows. 35 columns. Same download button, same job queue, same file on disk. The only thing that changed was who does the work — and the answer was “not Python.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5vsl7BZ7OkjhEFAb_IYWcw.png" /></figure><h3>The export nobody thinks about until it breaks</h3><p>Every product with data eventually grows an “Export to CSV” button. It starts innocent: query the database, loop over the rows, write them to a file. Nobody thinks twice about it — until the row count stops being in the thousands and starts being in the millions.</p><p>That’s what happened to us. Our analytics backend — a web API, a ClickHouse database, and a background worker that builds files on export — had already survived two rewrites of its export logic by the time we built a third. This is the story of that third one: how a <strong>5-million-row export went from ~15 minutes to 10.2 seconds</strong> (88x faster) without changing anything the user sees.</p><h3>Round 1: stop crashing the worker (v2)</h3><p>The first production version existed to fix one thing: <strong>out-of-memory crashes.</strong> Early attempts pulled an entire export into the app in one query — fine for small exports, catastrophic for large ones, where the database ended up sorting millions of rows in memory and taking the worker down with it.</p><p>The fix was classic <strong>chunking</strong>: instead of fetching 2 million rows at once, fetch 500,000 at a time, remember where you stopped, and ask for the next batch from there.</p><p>It worked — memory stayed predictable — but it was slow:</p><ul><li><strong>Too many round trips.</strong> A 2M-row export could mean four-plus separate database calls, each paying its own latency.</li><li><strong>Re-sorting every chunk</strong>, because the requested order didn’t match how data was stored on disk.</li><li><strong>Bookmark bookkeeping</strong> for partial chunks and tied timestamps added real complexity.</li><li><strong>Metadata still parsed by hand</strong>, row by row, after every fetch.</li></ul><p>v2 was correct and safe. It was not fast once exports crossed a few hundred thousand rows.</p><h3>Round 2: stop fighting the storage layout (v3)</h3><p>The next rewrite asked a better question: not <em>“how do we paginate?”</em> but <em>“how is this data actually laid out on disk, and how do we read it that way?”</em></p><ol><li>Find which <strong>calendar days</strong> in the range have data, skip the empty ones.</li><li>For each day, run <strong>one continuous streaming query</strong> instead of many paginated ones.</li><li>Ask for columns in the order they’re <strong>physically stored</strong>, so ClickHouse scans instead of sorting.</li><li>Only pull the <strong>custom fields that actually exist</strong> for that range.</li><li><strong>Overlap fetch and write</strong> so the next chunk loads while the current one is being saved.</li><li>Trim the final chunk precisely when a user capped their row count.</li></ol><p>This was a real leap: one stream per active day replaced v2’s bookmark-chasing entirely, and reads finally matched how ClickHouse stores data.</p><p>But one bottleneck survived both rewrites: <strong>every row still passed through the application</strong> — renamed, formatted, decrypted, escaped — cell by cell, in Python. At production scale (5M rows, 35 columns) that added up to <strong>~15 minutes.</strong> Fine for a while, not fine once workers started holding database connections open for a quarter hour at a stretch.</p><p>That’s the problem v4 set out to solve.</p><h3>The insight: if ClickHouse can already speak CSV, let it</h3><blockquote><strong><em>If the output is CSV and every transform can be written as SQL, the database can just emit CSV bytes directly — no app-side row parsing required.</em></strong></blockquote><p>v4 doesn’t touch the job queue, progress bar, or download link. It replaces exactly one thing: <strong>the inner loop that turns rows into file bytes.</strong></p><p>v3 inner loop v4 inner loop Row chunks pulled from the database Headerless CSV bytes straight from the database Every row transformed in application code Transforms expressed as SQL SELECT expressions CSV lines built manually in Python No row parsing in the application at all One query across the full date range One <strong>parallel query per active day</strong> Sequential writes to a single file Per-day temp files, merged at the byte level</p><p>Python’s job shrinks to writing the header once, then gluing together headerless CSV bodies ClickHouse already produced — pure byte concatenation, no re-parsing.</p><h3>How it runs</h3><ol><li><strong>Same job shell</strong> — queue, status, progress events all unchanged.</li><li><strong>Discover active days</strong>, same as v3.</li><li><strong>One SQL query per day</strong>, with renaming, formatting, and sensitive-field handling all in the SELECT.</li><li><strong>Write the header once.</strong></li><li><strong>Ask ClickHouse for CSV directly</strong> via native FORMAT CSV, header suppressed.</li><li><strong>Run up to three days in parallel</strong>, capped by the export connection pool.</li><li><strong>Stream each day to its own temp file</strong> — nothing waits for all 5M rows in memory.</li><li><strong>Merge each day into the final file</strong> the moment it finishes, via a kernel-level file copy.</li><li><strong>Mark the job complete</strong> — same file path, same download link.</li></ol><p>The application’s job went from <em>“understand every row”</em> to <em>“orchestrate queries and glue bytes together.”</em></p><h3>What moved out of Python</h3><p>Work v3 did per row Where v4 does it instead Column renaming / labels SQL aliases Date/time formatting formatDateTime() Custom metadata flattening Map projections (custom_attributes[&#39;key&#39;]) Nested JSON-like values toJSONString() Phone decryption/masking SQL against a vault join CSV escaping and line-building Native FORMAT CSV</p><p>The output stays byte-identical in shape to v3’s — same columns, order, and header labels — because v4 reuses v3’s column-discovery logic. Only <em>where</em> the transform runs changed.</p><h3>What we didn’t touch</h3><p>v4 is an overlay, not a replacement. Jobs needing v3 semantics — deduplicated exports, exact row-cap trimming — still run through v3. A single feature flag switches v4 off entirely, so rollout could be compared and rolled back instantly, no redeploy needed.</p><h3>Architecture: parallel days, serialized merge</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*khioHeK-73T_SkZ6KoxT8g.png" /></figure><p><strong>Why split by day?</strong> Parallelism (three days stream concurrently, bounded by the connection pool), smaller self-contained responses that are easier to retry, partition-friendly scans that let ClickHouse skip irrelevant disk parts, and bounded memory — the worker never holds more than a few buffers at once.</p><p><strong>Why temp files, then merge?</strong> Parallel days finish in unpredictable order, so each day writes its own .part file; a lock ensures only one thread appends to the final file at a time. On Linux the append uses the kernel&#39;s sendfile path — disk to disk, never through Python.</p><p><strong>Trade-off accepted:</strong> row order across days follows completion order, not calendar order (within a day, order still matches the storage key). For analytics downloads, that was an easy call — people want the full dataset, not a globally sorted file.</p><p>At 5M rows and 35 columns, v3 spent ~15 minutes on per-row application work. v4’s time is dominated by ClickHouse scanning and emitting CSV, not Python loops — which is why 10.2 seconds was possible at all.</p><h3>SQL as the transform layer</h3><pre>-- Illustrative example (simplified)<br>SELECT<br>  event_id,<br>  formatDateTime(event_time, &#39;%Y-%m-%dT%H:%i:%S&#39;) AS event_date_time,<br>  greatest(0, toInt64OrZero(toString(duration_ms))) AS duration_seconds,<br>  custom_attributes[&#39;full_name&#39;] AS full_name,<br>  decrypt(&#39;aes-256-gcm&#39;, …) AS phone_number   -- when vault join enabled<br>FROM analytics.events<br>WHERE tenant_id IN {tenant_ids}<br>  AND event_date = {start_date}<br>  AND source != &#39;internal_test&#39;<br>FORMAT CSV</pre><p>A few details mattered for parity with v3: ClickHouse settings pin LF line endings and empty strings for NULL, so the file looks identical downstream. FORMAT CSV skips the header row entirely, which is what makes raw concatenation safe. Sensitive fields like phone numbers are decrypted via SQL against a vault join, gated on matching v3&#39;s output row-for-row before trusting it in production.</p><p>The single most important design choice underneath all of this: <strong>one shared source of truth for column metadata</strong>, used by both v3 and v4, so the two paths can never quietly drift apart.</p><h3>Takeaways</h3><ol><li><strong>Profile before you rewrite.</strong> Our v3 logs showed the cost was in transform-and-write, not database wait time.</li><li><strong>Push formatting into the database when the format is native.</strong> CSV, JSON, TSV — most column stores can emit these directly.</li><li><strong>Parallelize along boundaries the data already respects.</strong> Calendar days matched our partitioning and how the team already thought about the data.</li><li><strong>Byte concatenation beats parse-and-re-serialize.</strong> Write the header once, append headerless bodies after it.</li><li><strong>Ship it as an overlay, not a rewrite.</strong> Feature flags and instant fallback make a scary migration boring — and boring is what you want in production.</li></ol><h3>The short version</h3><p><strong>v2</strong> taught us never to load an entire export into memory at once. <strong>v3</strong> taught us to stream with bounded memory — but every row still passed through the app. <strong>v4</strong> asked a narrower question: <em>for CSV, can the database just emit the file as bytes?</em></p><p>Yes. SQL transforms, native CSV output, parallel per-day streams, and a kernel-level file merge took our largest production export from <strong>~15 minutes to 10.2 seconds.</strong> Same download button, same file on disk. What changed is who does the work — ClickHouse builds the CSV, the application just stitches the bytes together.</p><p>It wasn’t a new system. It was a better division of labor between your application and your column store — worth checking whether your own export has the same one sitting unexamined.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea97755f0fba" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>