<?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 Hazemaltakriti on Medium]]></title>
        <description><![CDATA[Stories by Hazemaltakriti on Medium]]></description>
        <link>https://medium.com/@hazemaltakriti?source=rss-263692bc179e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*szfLrRHTb5ePADcVJ0g5mw.png</url>
            <title>Stories by Hazemaltakriti on Medium</title>
            <link>https://medium.com/@hazemaltakriti?source=rss-263692bc179e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:43:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hazemaltakriti/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[Designing a Scalable Notification System for a Large User Base]]></title>
            <link>https://medium.com/@hazemaltakriti/designing-a-scalable-notification-system-for-a-large-user-base-ea907e075305?source=rss-263692bc179e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea907e075305</guid>
            <category><![CDATA[notification-system]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[sqs]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Hazemaltakriti]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 14:49:56 GMT</pubDate>
            <atom:updated>2025-07-16T14:49:56.208Z</atom:updated>
            <content:encoded><![CDATA[<p>Sending notifications at scale — whether push, SMS, or email — is a core requirement for many modern applications. But doing it reliably and efficiently for millions of users is no small feat. It requires thoughtful design, careful resource management, and resilience in the face of failures.</p><p>In this post, I’ll walk through how we approached building a system that handles high-volume notifications across multiple channels without compromising performance or reliability.</p><h3>The Core Challenges</h3><p>At this scale, sending notifications isn’t just about looping through a list of users and firing off API requests. The system has to account for:</p><ul><li><strong>Efficient data access</strong> — Fetching millions of records without overloading the database.</li><li><strong>Controlled batch processing</strong> — Avoiding memory bloat and timeouts by chunking work into smaller jobs.</li><li><strong>Third-party rate limits</strong> — Staying within the limits of SMS, email, or push notification providers.</li><li><strong>Resilience</strong> — Recovering from partial failures without duplicating or losing data.</li></ul><h3>High-Level Architecture</h3><p>To solve these challenges, we built a system using:</p><ul><li><strong>Redis</strong> for in-memory tracking of job progress and counters.</li><li><strong>Amazon SQS</strong> for decoupling processing with reliable queues and built-in retry logic.</li><li><strong>PostgreSQL</strong> for structured user and notification data.</li><li><strong>AWS Lambda</strong> for scalable, serverless report generation.</li></ul><h3>Key Components and Flow:</h3><ol><li><strong>Retriever</strong>: Divides users into chunks (e.g., 100 per batch) and stores them in the database.</li><li><strong>Publisher</strong>: Pushes those chunk references into SQS for processing.</li><li><strong>Consumer</strong>: Listens to SQS, processes each chunk, and sends notifications.</li><li><strong>Redis</strong>: Tracks remaining work and progress at runtime.</li><li><strong>PostgreSQL</strong>: Stores user records, campaign metadata, and logs.</li></ol><h3>Design Strategies That Helped Us Scale</h3><h3>Chunked Processing</h3><p>Instead of trying to send millions of notifications in one go, we break the job into smaller parts:</p><ul><li>Each chunk contains a fixed number of user IDs.</li><li>Chunks are pushed to SQS where they’re processed independently.</li><li>Redis tracks how many chunks remain.</li></ul><p>This allows for easy scaling and fault tolerance. If something crashes mid-way, Redis helps resume from the last completed chunk without duplicating messages.</p><h3>Multi-Channel Support</h3><p>Each channel (SMS, email, push) comes with its own constraints and formats. While services like AWS SNS offer generic fan-out, we chose direct control for better flexibility:</p><ul><li><strong>Custom payloads</strong> for each channel</li><li><strong>Channel-specific retry logic</strong></li><li><strong>Avoiding fan-out to unnecessary targets</strong>, which helps with cost and performance</li></ul><h3>Campaign Completion Tracking</h3><p>Knowing when all notifications have been sent is essential — for both admins and follow-up automation.</p><p>We use a Redis counter to track how many chunks are still being processed. Each consumer decrements the counter when it finishes. When the counter hits zero, we trigger a “campaign complete” event, which can notify admins and initiate cleanup.</p><h3>Click Tracking Without Killing the Database</h3><p>Let’s say half a million users click on a notification within 10 minutes. Writing that many updates directly to the database can overwhelm it.</p><p>To handle this:</p><ul><li>We could buffer click events in Redis.</li><li>Flush to the database in batches, either every few seconds or after a threshold.</li><li>This reduces write load dramatically — from tens of thousands of writes per minute to a few hundred.</li></ul><p>Yes, this adds some risk (data in Redis is volatile), but for non-critical analytics like click tracking, it’s an acceptable tradeoff.</p><h3>Failure Handling &amp; Recovery</h3><p>Failures are inevitable at scale, so we planned for them:</p><ul><li><strong>Publisher crash</strong>: Redis tracks the last published chunk; the system resumes from that point.</li><li><strong>Consumer crash</strong>: SQS retries automatically, with exponential backoff. Failed messages go to a dead-letter queue for investigation.</li><li><strong>Database downtime</strong>: SQS retains messages while consumers pause and retry later — no loss, just delay.</li></ul><h3>Reporting at Scale</h3><p>Admins often need reports on campaign performance — like who received what, or who clicked.</p><p>To handle this efficiently:</p><ul><li>We use AWS Lambda to generate reports on demand.</li><li>Data is streamed to S3 to avoid memory limitations.</li><li>Reports are cached for a short period (e.g., 1 hour) to avoid recomputing the same data repeatedly.</li></ul><h3>Final Thoughts</h3><p>Designing a notification system that works at large scale isn’t just about sending messages — it’s about doing it <strong>reliably</strong>, <strong>efficiently</strong>, and <strong>resiliently</strong>.</p><p>The key takeaways from our system:</p><ul><li>Break down big jobs into manageable chunks.</li><li>Use queues to control flow and isolate failures.</li><li>Track progress in memory for recovery.</li><li>Avoid hammering the database with smart batching.</li><li>Prioritize flexibility over one-size-fits-all tools when necessary.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea907e075305" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bloom Filters: The Smart Way to Check Membership Efficiently]]></title>
            <link>https://medium.com/@hazemaltakriti/bloom-filters-the-smart-way-to-check-membership-efficiently-b949e94c90f6?source=rss-263692bc179e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b949e94c90f6</guid>
            <category><![CDATA[probabilistic-algorithms]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[bloom-filter]]></category>
            <dc:creator><![CDATA[Hazemaltakriti]]></dc:creator>
            <pubDate>Fri, 23 May 2025 06:36:07 GMT</pubDate>
            <atom:updated>2025-05-23T06:36:07.867Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Challenge: Efficient Email Existence Checks</h3><p>Suppose you manage a massive dataset of user emails and need a quick way to determine whether a specific email exists.</p><h3>Naive Approach: Direct Lookup</h3><p><strong>Method:</strong> Query the database or file system for each email.<br> <strong>Drawback:</strong> High I/O overhead — slow and inefficient for large-scale datasets.</p><h3>Improved but Limited: Caching Frequently Accessed Emails</h3><p><strong>Method:</strong> Store the most commonly queried emails in a cache.<br> <strong>Drawback:</strong> Ineffective if access is uniformly distributed — no clear “hot” items to cache.</p><h3>Hashmap-Based Lookup</h3><p><strong>Method:</strong> Store all emails in a hashmap for near-instant (O(log n)) lookups.<br> <strong>Drawback:</strong> High memory consumption — storing millions of emails is costly.</p><h3>A Better Alternative: Bloom Filters</h3><p>A <strong>Bloom filter</strong> is a probabilistic data structure that:</p><ul><li><strong>Guarantees</strong> no false negatives: if it says an element is not present, it truly isn’t.</li><li><strong>Allows</strong> a small probability of false positives.</li><li><strong>Uses</strong> significantly less memory than traditional storage structures.</li></ul><h3>How Bloom Filters Work</h3><ul><li><strong>Bit Array:</strong> An array of m bits, all initially set to 0.</li><li><strong>Hash Functions:</strong> k distinct hash functions applied to each item.</li><li><strong>Insertion:</strong><br> For an email like email@example.com, compute k hash values and set the corresponding bits to 1.</li></ul><p><strong>Example:</strong></p><ul><li>h1(email) = 3 → set bitArray[3] = 1</li><li>h2(email) = 7 → set bitArray[7] = 1</li><li>h3(email) = 9 → set bitArray[9] = 1</li><li><strong>Lookup:</strong></li><li>Recompute the k hashes.</li><li>If <strong>all</strong> corresponding bits are 1 → the email <em>might</em> exist.</li><li>If <strong>any</strong> bit is 0 → the email <em>definitely</em> does not exist</li></ul><h3>Handling Hash Collisions</h3><ul><li><strong>False positives</strong> can result from hash collisions.</li><li>To minimize this:</li><li>Use <strong>multiple hash functions</strong>.</li><li>Increase the <strong>bit array size (</strong><strong>m)</strong>.</li></ul><h3>Choosing the Right Parameters</h3><p>Performance depends on:</p><ul><li>n = Expected number of elements (e.g., 1,000,000 emails)</li><li>p = Desired false positive rate (e.g., 1% → p = 0.01)</li></ul><h4>1. Bit Array Size (m)</h4><p>Optimal size formula:</p><p>m = -(n * ln(p)) / (ln(2))²</p><p>Approximation for p = 0.01:</p><ul><li>m ≈ 9.58 million bits ≈ <strong>1.2 MB</strong></li></ul><h4>2. Number of Hash Functions (k)</h4><p>Optimal number: k = (m/n) * ln(2) ≈ 0.693 * (m/n).</p><p>For example p = 0.01, k ≈ 6.64 → round to <strong>7 hash functions</strong></p><h3>Improving CPU Efficiency</h3><p>With multiple hash computations per lookup, CPU efficiency becomes critical. Two optimization strategies:</p><h4>Strategy 1: Double Hashing</h4><p>Instead of computing k distinct hashes, derive them from two base hashes:</p><ol><li>Compute two base hashes:</li></ol><p>h1(x) = hash1(x)<br>h2(x) = hash2(x)</p><p>2. Derive additional hashes:</p><p>hi(x) = h1(x) + i * h2(x) mod m for i = 0 to k - 1</p><h4>Strategy 2: Use Fast, Non-Cryptographic Hashes</h4><p>Avoid heavy cryptographic hashes like SHA-256. Instead, prefer:</p><ul><li><strong>MurmurHash3</strong>: Good balance of speed and distribution</li><li><strong>xxHash</strong>: Even faster, though with slightly higher collision risk</li></ul><h3>Practical Example</h3><ul><li><strong>n =</strong> 1,000,000 emails</li><li><strong>p =</strong> 0.01</li><li><strong>m =</strong> ~9.58 million bits (≈1.2 MB)</li><li><strong>k =</strong> 7 hash functions</li></ul><h3>Real-World Applications</h3><ul><li><strong>Databases:</strong> Cassandra and Postgres use Bloom filters to avoid unnecessary disk reads.</li><li><strong>Web Crawlers:</strong> Quickly check if a URL has already been visited.</li></ul><h3>Summary</h3><p><strong>Bloom Filters Offer:</strong></p><p>✅ Extremely fast lookups (O(k))<br> ✅ High memory efficiency<br> ✅ No false negatives<br> ⚠️ <strong>The Tradeoff: </strong>Tunable false positive rate (typically 1–5%)</p><p>By carefully choosing m and k, you can strike the right balance between memory usage and accuracy for your needs. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b949e94c90f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Estimating Cardinality with HyperLogLog]]></title>
            <link>https://medium.com/@hazemaltakriti/estimating-cardinality-with-hyperloglog-4913d74cff13?source=rss-263692bc179e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4913d74cff13</guid>
            <category><![CDATA[implementation]]></category>
            <category><![CDATA[large-item]]></category>
            <category><![CDATA[cardinalities]]></category>
            <category><![CDATA[unique-item]]></category>
            <category><![CDATA[hyperloglog]]></category>
            <dc:creator><![CDATA[Hazemaltakriti]]></dc:creator>
            <pubDate>Fri, 16 May 2025 09:31:15 GMT</pubDate>
            <atom:updated>2025-05-25T12:17:45.898Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Cardinality?</h3><p>Cardinality refers to the count of distinct elements in a dataset. For example, given the list [“Alice”, “Bob”, “Jack”, “Alice”], the cardinality is <strong>3</strong>, as there are only three unique names.</p><p>A straightforward way to compute cardinality is by using a hash set — each unique element is stored once, and the total count is the number of keys. While hash lookups are efficient (~O(log n)), this approach requires <strong>linear memory</strong> relative to the number of unique elements. For large-scale datasets (e.g., tracking Facebook’s daily visitors), storing every unique entry becomes impractical due to memory constraints.</p><p>This raises an important question: <strong>Do we always need an exact count, or is an approximation sufficient?</strong> In many real-world scenarios (e.g., website analytics), an approximate count is acceptable and far more cost-effective.</p><h3>A Probabilistic Approach to Cardinality Estimation</h3><p>To estimate cardinality efficiently, we can leverage probability theory. Consider a simple analogy: flipping a fair coin. The probability of getting <strong>Heads (H)</strong> or <strong>Tails (T)</strong> is <strong>½</strong>.</p><ul><li>The chance of getting <strong>three consecutive Heads (HHH)</strong> is lower than getting <strong>two Heads (HH)</strong>, which in turn is lower than a single <strong>Head (H)</strong>.</li><li>If someone reports observing <strong>HHH</strong>, we can infer they likely performed many trials to achieve this outcome.</li></ul><p>This intuition forms the basis of probabilistic cardinality estimation.</p><h3>From Random Numbers to Hashing</h3><p>Suppose we hash each element in a dataset, producing uniformly distributed values between <strong>[0, 1]</strong>. For example:</p><p><strong>Input:</strong> [120, 100, 90, 100, 90]<br><strong>Hashed:</strong> [0.2, 0.4, 0.3, 0.4, 0.3]</p><p>A naive estimator would be:</p><p>Estimate=1/min⁡(hashed values)=1/0.2=5</p><p>However, this method has two major flaws:</p><ol><li><strong>High Variance</strong> — Due to the infinite range of possible hash values.</li><li><strong>Overestimation Risk</strong> — A single extremely small hash value skews the result.</li></ol><h3>Improving Stability: Counting Leading Zeroes</h3><p>To reduce variance, we can convert hash values to binary and count the number of <strong>leading zeroes</strong>. The probability of observing <strong>k consecutive zeroes</strong> is:</p><p>P(k leading zeros)=1/(2^k)</p><p>Thus, the estimator becomes:</p><p>Estimate=2(maximum leading zeros observed)</p><p>But this still has issues:</p><ul><li>Estimates are constrained to powers of two (<strong>2, 4, 8, 16, …</strong>).</li><li>Variability remains high because a single extreme value (e.g., many leading zeros) can distort the estimate.</li></ul><h3>LogLog: Reducing Variance with Multiple Buckets</h3><p>The <strong>LogLog algorithm</strong> improves accuracy by using <strong>multiple hash functions</strong> (or splitting one hash into buckets and that will reduce using intensive computational for multiple hash value).</p><p><strong>How it works:</strong></p><ol><li>Divide the hash output into two parts:</li></ol><p>2. The first few bits determine the <strong>bucket</strong>.</p><p>3. The remaining bits determine the <strong>leading zero count (R)</strong>.</p><p>4. Track the <strong>maximum R</strong> per bucket.</p><p>5. Combine results using:</p><p>Estimate=constant×m×2^√m∑Ri​</p><ul><li>m = number of buckets</li><li>Ri​ = max leading zeros in bucket i</li></ul><p><strong>Performance:</strong></p><ul><li><strong>Error rate:</strong> ~1.3/√m With <strong>2048 buckets (11 bits each)</strong>, memory usage is just <strong>1.2KB</strong>, supporting cardinalities up to 2²⁷ with ~2.8% error.</li></ul><h3>HyperLogLog: Further Refinement</h3><p><strong>HyperLogLog (HLL)</strong> enhances LogLog by:</p><ul><li>In <strong>HyperLogLog (HLL)</strong>, the harmonic mean is used to <strong>combine estimates from multiple buckets</strong> (instead of the arithmetic mean in LogLog). This helps because:</li><li>Some buckets may have <strong>unusually high cardinality estimates</strong> due to hash collisions. The harmonic mean <strong>dampens the effect of these outliers</strong>, leading to a more stable and accurate final estimate.</li><li>Reducing the error rate to <strong>~1.05/√m</strong> without additional memory.</li></ul><h3>Implementation and Results</h3><p>I’ve developed a <strong>high-performance, memory-efficient HyperLogLog algorithm in TypeScript</strong>, now available as an <a href="https://www.npmjs.com/package/@hazemaltakriti/hyperloglog"><strong>npm package</strong></a><strong> </strong>and i can share the result of implementing this using 2¹⁴ buckets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vjXHlXr90hkqJtpbK7UClw.png" /></figure><p>If you want to take a review on implementation: <a href="https://www.npmjs.com/package/@hazemaltakriti/hyperloglog">https://www.npmjs.com/package/@hazemaltakriti/hyperloglog</a></p><p><strong>Redis and HyperLogLog</strong></p><p>Redis includes a built-in implementation of HyperLogLog using the PFADD, PFCOUNT, and PFMERGE commands, with a default precision of 14, effectively distributing the data into 2¹⁴ buckets.</p><pre>PFADD unique_visitors &quot;user1&quot; &quot;user2&quot; &quot;user3&quot; &quot;user1&quot;<br>PFCOUNT unique_visitors # Returns 3</pre><h3>Conclusion</h3><p>HyperLogLog provides an <strong>efficient, memory-friendly</strong> method for approximate cardinality estimation, making it ideal for large-scale systems like web analytics, databases, and distributed computing. By leveraging probabilistic techniques, it achieves high accuracy with minimal storage — proving that sometimes, <strong>approximation is better than perfection</strong>.</p><p><strong>References:</strong></p><ul><li><a href="https://algo.inria.fr/flajolet/Publications/FlFuGaMe07.pdf">https://algo.inria.fr/flajolet/Publications/FlFuGaMe07.pdf</a></li><li><a href="https://engineering.fb.com/2018/12/13/data-infrastructure/hyperloglog/">https://engineering.fb.com/2018/12/13/data-infrastructure/hyperloglog/</a></li><li><a href="https://antirez.com/news/75">https://antirez.com/news/75</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4913d74cff13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design: Efficiently Exporting and Sending Large Reports]]></title>
            <link>https://medium.com/@hazemaltakriti/system-design-efficiently-exporting-and-sending-large-reports-437f26c5e962?source=rss-263692bc179e------2</link>
            <guid isPermaLink="false">https://medium.com/p/437f26c5e962</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Hazemaltakriti]]></dc:creator>
            <pubDate>Fri, 09 May 2025 18:30:45 GMT</pubDate>
            <atom:updated>2025-05-11T11:55:21.771Z</atom:updated>
            <content:encoded><![CDATA[<p>Exporting large datasets from a PostgreSQL database and delivering them to users — often in CSV format — is a common task in many backend systems. While seemingly simple, doing this efficiently at scale can present various challenges: high memory usage, database performance issues, and long-running operations.</p><p>In this article, we’ll explore <strong>three approaches</strong> to designing such a system, with trade-offs and implementation strategies. We’ll also touch on enhancements like serverless functions and caching mechanisms to make the process more robust and scalable.</p><p>We assume the backend uses <strong>PostgreSQL</strong>, and the client expects a <strong>CSV report</strong>.</p><h3>🧠 Approach 1: Naive In-Memory Export</h3><h3>🧾 How it works</h3><p>This is the simplest approach:</p><ol><li>Query all the required data from the database at once.</li><li>Load the data entirely into memory.</li><li>Use a library to convert the data into CSV format.</li><li>Send or upload the generated CSV file.</li></ol><pre>// Pseudo-code (Node.js style)<br>const data = await db.query(&#39;SELECT * FROM large_table&#39;);<br>const csv = utils.toCSV(data.rows);<br>await uploadToDrive(&#39;report.csv&#39;, csv);</pre><h3>✅ Pros</h3><ul><li><strong>Very simple</strong> to implement.</li><li>Minimal database interaction: only one query.</li><li>Easy to maintain and debug for small datasets.</li></ul><h3>❌ Cons</h3><ul><li><strong>High memory usage</strong>: Loading large datasets into memory can consume significant resources.</li><li><strong>Risk of crashing the application</strong>: If the dataset is too large, it may exhaust server memory, leading to application failure.</li><li><strong>Database strain</strong>: A large query might lock the table or slow down other operations.</li></ul><h3>🌀 Approach 2: Pagination with Streaming Upload</h3><h3>🧾 How it works</h3><p>Instead of loading the entire dataset into memory at once, this approach processes the data in <strong>batches (pages)</strong> and streams it directly to the output destination (e.g., cloud storage like Google Drive or AWS S3). This is Minimizes <strong>RAM</strong> consumption and balances database pressure</p><p>Basic steps:</p><ol><li>Query the data in paginated chunks (using LIMIT and OFFSET, or better, cursor-based pagination).</li><li>Convert each chunk to CSV on-the-fly.</li><li>Write the CSV chunk to a stream connected to a file upload handler (like a cloud storage stream writer).</li><li>Repeat until all data is processed.</li></ol><h3>💻 Pseudo-code Example (Simplified)</h3><pre>let offset = 0;<br>const batchSize = 1000;<br>const streamBody = openStream();<br>const uploadTask = Driver.upload(&#39;report.csv&#39;, streamBody);<br>while (true) {<br>  const res = await db.query(`SELECT * FROM table_name LIMIT ${batchSize} OFFSET ${offset}`);<br>  if (res.rows.length === 0) break;<br>  const csvChunk = utils.toCsv(res.rows);<br>  streamBody.write(csvChunk);<br>  offset += batchSize;<br>  await sleep(100); // optional delay to reduce DB pressure<br>}<br>streamBody.end();<br>await uploadTask;</pre><h3>✅ Pros</h3><ul><li><strong>Low memory usage</strong>: Only a small chunk of data is in memory at any given time.</li><li><strong>Efficient for large exports</strong>: It can handle millions of rows without crashing the app.</li><li><strong>Streamlined flow</strong>: Data is processed and uploaded incrementally.</li></ul><h3>❌ Cons</h3><ul><li><strong>Many DB queries</strong>: For large datasets, pagination generates lots of small queries.</li><li><strong>Offset performance issue</strong>: Using OFFSET in PostgreSQL leads to performance degradation. PostgreSQL still has to scan and skip rows, even if they&#39;re not returned, For example:OFFSET 0 is fast, but OFFSET 100000 causes PostgreSQL to scan and skip 100,000 rows before returning the next 1,000.</li><li><strong>Long transactions</strong>: If not managed carefully, this could still hold a transaction open for a long time.</li></ul><p>🧭 Cursor-Based Pagination as a Fix</p><p>A more performant alternative to OFFSET is to use <strong>cursor-based pagination</strong>, which avoids scanning and skipping large numbers of rows. There are two common ways to implement this:</p><h3>1. Stateless Cursor via WHERE Clause (Simple &amp; API-Friendly)</h3><p>Use an indexed column (like id or created_at) to keep track of the last processed row between requests. This is ideal for stateless HTTP-based pagination.</p><pre>SELECT * FROM users WHERE id &gt; last_seen_id ORDER BY id ASC LIMIT 1000;</pre><p>Update last_seen_id after each batch. This method prevents row skipping and keeps queries efficient—even with large datasets.</p><h3>2. PostgreSQL Cursors with FETCH (Best for Batch Processing)</h3><p>For backend processes (e.g., batch jobs or report generators), using PostgreSQL’s <strong>server-side cursor</strong> allows you to fetch rows incrementally within a single transaction.</p><pre>  try {<br>    // Begin transaction and declare cursor<br>    await client.query(&#39;BEGIN&#39;);<br>    await client.query(&#39;DECLARE user_cursor CURSOR FOR SELECT * FROM users ORDER BY id&#39;);<br><br>    let hasMoreRows = true;<br>    const batchSize = 1000;<br>    const streamBody = openStream();<br>    const uploadTask = Driver.upload(&#39;report.csv&#39;, streamBody);<br>    while (hasMoreRows) {<br>      // Fetch batch of rows<br>      const result = await client.query(`FETCH ${batchSize} FROM user_cursor`);<br>      <br>      if (result.rows.length === 0) {<br>        hasMoreRows = false;<br>      } else {<br>        // Process your batch here<br>        console.log(`Processing batch of ${result.rows.length} rows`);<br>        streamBody.write(utils.toCsv(result.rows))<br>      }<br>    }<br><br>    // Clean up<br>    await client.query(&#39;CLOSE user_cursor&#39;);<br>    await client.query(&#39;COMMIT&#39;);<br>  } catch (error) {<br>    await client.query(&#39;ROLLBACK&#39;);<br>    console.error(&#39;Error processing users:&#39;, error);<br>  } finally {<br>    client.release();<br>    await pool.end();<br>  }<br>}</pre><p>⚠️ <strong>Note:</strong> This is best used for backend jobs — not exposed via HTTP — since cursors require a persistent DB session and transaction context.</p><h3>When to use</h3><ul><li>The dataset is large and won’t fit into memory.</li><li>You want to balance performance and implementation complexity.</li><li>You can rely on a stable ordering column (like id) for cursor-based pagination.</li></ul><h3>⚡ Approach 3: PostgreSQL COPY Command</h3><h3>How it works</h3><p>PostgreSQL can export data directly to CSV using COPY TO STDOUT.</p><pre>const client = await db.connect();<br>const streamBody = openStream();<br>const uploadTask = Driver.upload(&#39;report.csv&#39;, streamBody);<br>const copyStream = client.query(<br>  copyTo(`COPY (SELECT * FROM users) TO STDOUT WITH CSV HEADER`)<br>);<br>copyStream.pipe(streamBody);<br>copyStream.on(&#39;end&#39;, () =&gt; streamBody.end());<br>await uploadTask;</pre><h3>✅ Pros</h3><ul><li>Extremely fast.</li><li>One query only.</li><li>No CSV conversion needed in the app.</li></ul><h3>❌ Cons</h3><ul><li>Harder to transform data.</li><li>Less flexible than other approaches.</li><li>Requires handling raw streams.</li></ul><h3>🚀 Enhancements for Production</h3><h3>☁️ Use Serverless for Async Processing</h3><p>Avoid backend timeouts:</p><ol><li>Backend receives request → creates <strong>job</strong>.</li><li>Triggers <strong>serverless(e.g lambda)</strong> function.</li><li>Function streams data and uploads the report.</li><li>Marks the job as complete and provides the generated report’s download link.</li><li>Frontend polls /jobs/:id for status and downloads the file on completion.</li></ol><h3>📦 Add Caching</h3><ul><li>Save report metadata (timestamp, filters).</li><li>If a request is made with the <strong>same parameters</strong> within a defined time window (e.g., <strong>2 hours</strong>), return the <strong>cached version</strong> instead of regenerating the report.</li><li>Saves compute and database resources.</li></ul><h3>🧹 Scheduled Cleanup to Reduce Storage Costs</h3><p>To optimize storage usage and reduce costs, implement a scheduled job (e.g., a cron job or serverless scheduler) that automatically deletes old report files such as those older than one month from your storage provider. This helps avoid unnecessary retention of outdated reports.</p><h3>🧮 Summary Table (Updated)</h3><h3>Comparison: Large Report Export Methods</h3><p><em>(✓ = Best, △ = Trade-offs, ✗ = Limitation)</em></p><h4>1. Naive In-Memory Export</h4><ul><li><strong>🧠 Memory</strong>: ✗ High usage (entire dataset loaded)</li><li><strong>⚡ Speed</strong>: ✓ Fast for small datasets (&lt;10K rows)</li><li><strong>🛠️ Implementation</strong>: ✓✓✓ Easiest (simple queries + in-memory conversion)</li><li><strong>🎨 Flexibility</strong>: ✓✓✓ Full data transformation control</li></ul><h4>2. Pagination + Streaming</h4><ul><li><strong>🧠 Memory</strong>: ✓ Efficient (processes batches)</li><li><strong>⚡ Speed</strong>: △ Moderate (many small queries; avoid OFFSET)</li><li><strong>🛠️ Implementation</strong>: ✓✓ Medium (cursor logic + streaming)</li><li><strong>🎨 Flexibility</strong>: ✓✓ Some constraints (requires ordered IDs)</li></ul><h4>3. PostgreSQL COPY + Stream</h4><ul><li><strong>🧠 Memory</strong>: ✓✓✓ Minimal (direct DB-to-stream piping)</li><li><strong>⚡ Speed</strong>: ✓✓✓ Fastest (single efficient query)</li><li><strong>🛠️ Implementation</strong>: ✓ Moderate (stream handling required)</li><li><strong>🎨 Flexibility</strong>: △ Limited (hard to transform data mid-export)</li></ul><h3>🏁 Conclusion</h3><p>When designing a report export system, the choice of method depends largely on the scale of the data and your performance requirements. Here’s a quick recap:</p><ul><li><strong>Naive (in-memory) Export</strong>: Simple and quick to implement, but not suitable for large datasets due to high memory usage and potential crashes. Ideal for smaller datasets or prototyping.</li><li><strong>Pagination + Streaming</strong>: A balanced approach that reduces memory usage and handles large datasets. However, it introduces multiple queries and can slow down over time as the dataset grows. The cursor-based pagination fix improves performance but still requires careful management.</li><li><strong>PostgreSQL </strong><strong>COPY + Stream</strong>: The most efficient approach for large-scale exports, offering the best memory efficiency and speed. While it’s slightly less flexible for complex transformations, it’s the go-to choice for handling huge datasets in production, especially when transformations can be done at the database level.</li></ul><p>Ultimately, if you’re looking for <strong>scalability, efficiency, and performance</strong> with minimal overhead, the COPY + Stream approach is highly recommended. It strikes the right balance across all key metrics—memory efficiency, speed, flexibility, and ease of implementation—making it a solid choice for most enterprise-level applications.</p><p>In any case, the ideal approach depends on the specific requirements of your system, so choose wisely!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=437f26c5e962" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>