<?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 Itay Bittan on Medium]]></title>
        <description><![CDATA[Stories by Itay Bittan on Medium]]></description>
        <link>https://medium.com/@itay-bittan?source=rss-43233e94ad28------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*muDXT05dXJPYOSI3CUM_Ig.jpeg</url>
            <title>Stories by Itay Bittan on Medium</title>
            <link>https://medium.com/@itay-bittan?source=rss-43233e94ad28------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 15:02:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@itay-bittan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The AWS Console Doesn’t Know Your Business - So We Built One That Does]]></title>
            <link>https://itnext.io/the-aws-console-doesnt-know-your-business-so-we-built-one-that-does-6e02beca1821?source=rss-43233e94ad28------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e02beca1821</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Itay Bittan]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 11:22:34 GMT</pubDate>
            <atom:updated>2026-03-30T22:20:03.543Z</atom:updated>
            <content:encoded><![CDATA[<h4>How a domain-aware S3 UI gave us visibility, safe deletion, and $4K/month back</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*28cwFEF-q5iy_kRyliZtsQ.png" /><figcaption>S3 Bucket metrics after cleanup - bucket size dropped from ~45 TB to ~4.5 TB, with a temporary spike in object count due to soft-delete markers before full removal (image by author)</figcaption></figure><p>TLDR; Control your own S3 bucket with a customized S3 UI instead of AWS S3 Web Console.</p><h3>Why S3 Lifecycle Rules Couldn’t Save Us (And What We Built Instead)</h3><p>We had a growing problem. Literally.</p><p>Our feeds catalogs S3 bucket, the ones that power product recommendations for thousands of customers - kept growing, month over month, with no end in sight. Old feeds catalogs versions piled up. Nobody deleted anything because, honestly, nobody wanted to be the person who accidentally broke a customer’s active feed.</p><p>So the buckets grew. And we paid for it — in S3 storage costs, and in every process that had to go through thousands of old versions just to find the one active feed catalog per customer.</p><p>In the spirit of modern vibe coding - move fast, use AI to handle the boilerplate, iterate quickly, and ship - we built Feeds Manager: a web application that gives us full visibility into our S3 feeds catalogs data and safely automates the cleanup. Here’s how we got there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*epjvmQsv133fLqccqbrrGg.png" /><figcaption>Monthly AWS S3 costs from July 2025 to February 2026, showing a steady climb from ~$1.2K to ~$5.4K (image by author)</figcaption></figure><h3>The Structure of the Problem</h3><p>Our feed catalog data lives in S3 with a clear hierarchy:</p><pre>output/<br>├── {section_id}/         # Customer ID (e.g., 8765432)<br>│   ├── {feed_id}/        # Feed catalog ID (e.g., 1000)<br>│   │   ├── {timestamp}/  # Unix timestamp - the version being processed<br>│   │   │   ├── SUCCESS<br>│   │   │   ├── ERROR<br>│   │   │   ├── DELETE_ME<br>│   │   │   ├── catalog.csv.gz<br>│   │   │   └── catalog.csv<br>│   │   ├── {timestamp}/<br>│   │   └── …</pre><p>Every time a customer’s feed pipeline runs, it creates a new timestamped folder with the data and a marker file. Successful runs get a SUCCESS marker. Failed runs get ERROR. Over time, each feed catalog collects hundreds or thousands of version folders.</p><h3>The Visibility Problem - or, Death by Four Clicks</h3><p>Before building anything, we tried to understand the problem using the tools we had. The AWS S3 Console.</p><p>Want to check one feed catalog version? Here’s the workflow:</p><ol><li>In AWS Console S3, find the feeds catalog bucket and click into output/</li><li>Click into a section (customer) ID - but which customer is 8765432? No idea. It&#39;s just a number.</li><li>Click into a feed ID - what type of feed is 1000? Is it big? Small? Who knows.</li><li>Click into a timestamp folder - is 1770893674000 from yesterday or last month? Quick, do the math.</li></ol><p>Four clicks to reach one version. And if you want to actually <em>see</em> the data? Download it to your laptop, unzip it, open it in a text editor. Repeat for the next version.</p><p>We have thousands of customers, each with up to dozens of feeds, each with potentially thousands of versions. The AWS Console simply doesn’t work for this kind of inspection.</p><p>The customer metadata - names, publishers, account tiers, feed types - lives in a separate internal database. Every time you need context, you’re switching to another tool and searching by ID.</p><h3>“What If We Built Our Own S3 Console?”</h3><p>That was the pitch. Not a full platform - a focused tool that does one thing well: give us visibility into our feed buckets, enriched with the context we actually need.</p><p>We started from the <a href="https://github.com/fastapi/full-stack-fastapi-template">FastAPI full-stack template</a> and began adding our domain logic on top. The core idea: take the S3 hierarchy and combine it with data from our internal API. Instead of seeing section_id: 8765432, you see <strong>&quot;Acme Corp - Premium Tier - Fashion Publisher&quot;</strong>. Instead of guessing at a timestamp, you see a human-readable date with a relative time label.</p><p>While we started with the feeds catalogs bucket, the vision is bigger - this could become an S3 viewer for other business logic buckets as well, enriching the raw S3 data with metadata from our internal store. The same pattern works anywhere you have S3 objects that need business context on top.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LXuNun1ek8YaiEWIDPVhPg.png" /></figure><h3>CSV Preview: See the Data Without Downloading It</h3><p>One of the most requested features from day one. Click any .csv or .csv.gz file and get an inline table preview - the first rows pulled directly from S3.</p><p>For plain CSV, we use an S3 Range request to grab the first 1 MB. For gzipped files, we download up to 10 MB and decompress on the fly. Either way, the user sees a clean table in a modal - no downloads, no local tools needed.</p><p>We also added image URL detection: if a column contains image URLs, hovering over a cell shows a thumbnail preview. Small touch, but a big improvement when you’re checking product catalog feeds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MmKbOFvv6spvLcA2JkUjVQ.png" /><figcaption>Inline CSV preview modal - clicking a catalog feed file shows the first rows as a formatted table, with thumbnail previews for image URL columns (image by author)</figcaption></figure><h3>The Hard Part: Deletion Without Destruction</h3><p>The browser was useful on its own, but the real motivation was cost control. We needed to delete old feed versions - safely.</p><p>The first thought was “just use S3 lifecycle rules.” Delete objects older than X days. Done. Except - no. A customer’s feed pipeline might fail for an entire week. The last successful version from 10 days ago is still the active version other systems read from. A date-based rule would delete it and break everything. We needed something smarter.</p><p>So we built a simple algorithm: keep the last N successful versions per feed (we use 4, it’s configurable), delete everything older than that. If there aren’t even 4 successful versions? Delete nothing. Safe default.</p><p>A few things we learned about doing destructive ops at scale:</p><ul><li><strong>Soft delete first.</strong> S3 versioning means “delete” just adds a marker - nothing is actually gone. Pair it with a lifecycle rule that removes markers after 30 days and you have a full month to catch mistakes.</li><li><strong>Audit everything.</strong> The first time someone asks “what was deleted from customer X last Tuesday?” you’ll be glad you did.</li><li><strong>Stage before prod.</strong> Run it on staging, check the results carefully, then apply to production.</li><li><strong>Build a kill switch.</strong> One-click restore and a hard cap on objects per run. Runaway deletions are a real risk.</li></ul><h3>Automating It: The Cron Job</h3><p>Manual cleanup is fine for the first few runs while you’re building confidence. But the whole point is automation. We added a simple cron scheduler — one environment variable:</p><pre>BULK_DELETION_CRON=&quot;0 2 * * *&quot; # Run daily at 2 AM</pre><p>The scheduler runs inside the FastAPI process itself - no external scheduler, no separate cron service, no Kubernetes CronJob to manage. It checks every X seconds if a run is due, respects the concurrency guard (won’t start if another run is active), and logs everything through the same audit pipeline.</p><p>This keeps our buckets at a steady state: new versions come in, old versions get cleaned up, storage stays flat instead of growing forever.</p><h3>Bonus Features We Didn’t Plan For</h3><p>Once you have a tool that gives visibility into your S3 data, people start asking for things:</p><p><strong>Section Heatmap</strong> - A ranked view of the top 30 customers by feed volume. Shows right away which accounts generate the most data and helps with capacity planning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hWLTcXEx661_9U8wCDg2HQ.png" /><figcaption>Section Heatmap showing the top customers ranked by feed volume (image by author)</figcaption></figure><p><strong>Dynamic Subtitles</strong> - At each navigation level, the page shows counts in context: ”312 sections in S3 (247 in database)” at the root, “15 feeds - 8 success, 3 error, 4 delete” at the section level. Quick health check without clicking into anything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5evcKCkFhSZC-mXWjPTe_g.png" /><figcaption>The Feeds Manager browse view showing enriched metadata - customer names, feed health indicators, and dynamic subtitles replace raw S3 IDs (image by author)</figcaption></figure><p><strong>Deep Linking</strong> - Every S3 path maps to a URL: /feeds/browse/output/8765432/1000/. Share it in Slack, bookmark it, link it from an incident doc. This turned out to be one of the most used features - nobody has to explain &quot;go to section X, then feed Y&quot; anymore.</p><p><strong>Dark Mode</strong> - Because our on-call engineers browse feeds at 2 AM and we’re not monsters.</p><h3>The Stack</h3><p>We optimized for speed of development. The FastAPI full-stack template gave us auth, user management, Docker setup, and CI/CD out of the box. We focused entirely on domain logic.</p><p><strong>Backend:</strong> FastAPI, SQLModel, PostgreSQL, boto3, Pydantic</p><p><strong>Frontend:</strong> React + TypeScript, TanStack Router/Query/Table, Tailwind</p><p><strong>Infrastructure:</strong> Docker, GitHub Actions, JWT auth</p><p><strong>Testing:</strong> pytest (backend), Playwright E2E (frontend)</p><h3>The Numbers</h3><p>Here’s what the cleanup actually looks like in practice (accross all accounts/environments):</p><ul><li><strong>Objects before cleanup</strong>: 200 million objects across thousands feeds</li><li><strong>Objects after cleanup</strong>: 110 million objects</li><li><strong>Storage reclaimed</strong>: 360 TB → 180 TB</li><li><strong>Monthly cost savings</strong>: ~$4K/month in S3 storage</li></ul><p>The cron job runs every night. Each run typically processes ~80K versions and deletes ~ 200K objects. Thanks to the 30-day soft delete window, we always have a safety net.</p><p>The speed of development came from three things: a solid template as the starting point, AI-assisted coding for boilerplate and fast iteration, and a tight feedback loop - we deployed to staging continuously and used the tool ourselves from day one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KPBNWwXdTn3JO97jMUC6Qw.png" /><figcaption>S3 cost and usage graph for one of our five catalog feeds environments, showing daily costs climbing from ~$13 to ~$37 over six months, then dropping to ~$2 after cleanup (image by author)</figcaption></figure><h3>What We Learned</h3><p><strong>Start with visibility, then add actions.</strong> Building the S3 browser first - before any deletion logic - was the right call. It let us understand the data, spot patterns, and build confidence. By the time we added deletion, we already had a clear sense of what “normal” looked like.</p><p><strong>Metadata makes all the difference.</strong> The difference between “section 8765432” and “Acme Corp - Premium - Fashion” is the difference between a tool nobody uses and one that’s open in everyone’s browser.</p><p><strong>Don’t underestimate a simple cron job.</strong> No event-driven architecture, no message queues, no lambda functions. One cron expression, one process, one database. It runs at 2 AM, cleans up, and logs what it did. Sometimes boring is exactly right.</p><p><em>Feeds Manager is an internal tool built at Dynamic Yield, a Mastercard company. The project is built on the </em><a href="https://github.com/fastapi/full-stack-fastapi-template"><em>FastAPI full-stack template</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e02beca1821" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/the-aws-console-doesnt-know-your-business-so-we-built-one-that-does-6e02beca1821">The AWS Console Doesn’t Know Your Business - So We Built One That Does</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Invisible Failures: The Python Server Mistake We Made in Production]]></title>
            <link>https://itnext.io/invisible-failures-the-python-server-mistake-we-made-in-production-7d20f144c480?source=rss-43233e94ad28------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d20f144c480</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Itay Bittan]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 21:21:06 GMT</pubDate>
            <atom:updated>2026-01-26T20:58:44.071Z</atom:updated>
            <content:encoded><![CDATA[<p>This is one of those “old” issues that people assume is solved - until it bites them in production as the system grows and scale becomes real.</p><p>Back in 2018 at <a href="https://www.dynamicyield.com/">Dynamic Yield</a>, our main backend servers had to handle hundreds of requests per second. Our initial setup was fairly simple: a <a href="https://bottlepy.org/docs/dev/">bottle</a>-based Python web server running with <a href="https://uwsgi-docs.readthedocs.io/en/latest/">uWSGI</a> as a WSGI application on Linux, deployed on relatively small EC2 instances. We ran dozens of these EC2 instances behind an AWS Load Balancer.</p><p>On an average day, everything worked just fine. However, from time to time we experienced sudden traffic spikes caused by our customers’ clients, and that’s where things started to break down.</p><h3>The bottleneck</h3><p>With the WSGI setup, the main bottleneck turned out to be the <strong>uWSGI internal listen queue</strong>, which was set to 100 by default. Any request beyond that limit was simply dropped, resulting in 5XX INTERNAL SERVER ERROR responses.</p><p>In contrast, when using an async <a href="https://www.tornadoweb.org/en/stable/">tornado</a> web server, the main bottleneck shifted to <strong>Python memory usage</strong>, which is far more visible, measurable, and most importantly - much easier to scale.</p><p>These 5XX errors were clearly visible in the AWS Load Balancer metrics (HTTP 5XXs, per minute). We observed a consistent number of requests that were never handled by our servers.</p><blockquote><strong><em>Side note:</em></strong><em> For simplicity, I’m skipping over the fact that we also had Nginx running on the EC2 instances, acting as a reverse proxy between the load balancer and uWSGI.</em></blockquote><h3>What we saw in production</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*KJvL0HTuyNkgJL66g2rzoQ.png" /><figcaption>11/29 08:00 deployment time, AWS Load Balancer Metric</figcaption></figure><p>The screenshot above shows the 5XX response rate from the AWS Load Balancer, and the sharp decrease after we switched to an async web server on <strong>11/29 at 08:00</strong>.</p><p>At the same time, uWSGI logs clearly showed the root cause:</p><pre>*** uWSGI listen queue of socket &quot;127.0.0.1:XXXXX&quot; (fd: 3) full !!! (101/100) ***</pre><p>This means requests were being dropped on the floor before they even reached the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yi8L2TizMRcdIEuCXsuP-w.png" /><figcaption>uwsgi.log</figcaption></figure><p>Below is another screenshot from our old StatsD metrics, showing how the 5XX responses stopped almost completely after we deployed the async web server (moving from uWSGI + Bottle to a Tornado-based async server):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2Ad39wdMoiq1dUV3okwyQ.png" /><figcaption>11/29 08:00 deployment time, main service</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KTJnDhhIKgimcuML1pc_Ig.png" /><figcaption>11/29 08:00 deployment time, second service</figcaption></figure><h3>Reproducing the issue locally</h3><p>To demonstrate this behavior in a simple, isolated environment, I created a <a href="https://github.com/itayB/sync-vs-async">GitHub repository</a>.</p><p>The setup includes three Docker containers:</p><ol><li><strong>Sync web-server</strong> — Flask running with uWSGI</li><li><strong>Async web-server</strong> — FastAPI</li><li><strong>Load generator</strong> — a <a href="https://k6.io/">k6</a> container simulating 1,000 virtual users</li></ol><p>Each virtual user sends the same simple GET request, which does nothing except sleep for 500ms, simulating an I/O-blocking operation.</p><p>When running the sync web server, we consistently see the following uWSGI log:</p><pre>*** uWSGI listen queue of socket &quot;127.0.0.1:36675&quot; (fd: 3) full !!! (101/100) ***</pre><p>This clearly indicates that requests are being dropped.</p><h3>k6 results: sync vs async</h3><h4>Sync web server (Flask + uWSGI)</h4><pre>checks_succeeded...: 37.70% 377 out of 1000<br>checks_failed......: 62.30% 623 out of 1000<br><br>http_req_duration..............: avg=46.82s<br>http_req_failed................: 62.23%</pre><p>Only <strong>37%</strong> of the requests succeeded. Most requests failed with 5XX errors, and the average request duration was extremely high.</p><h4>Async web server (FastAPI)</h4><pre>checks_succeeded...: 100.00% 1000 out of 1000<br>checks_failed......: 0.00%   0 out of 1000<br><br>http_req_duration..............: avg=6.66s<br>http_req_failed................: 0.09%</pre><p>Here, <strong>100%</strong> of the requests succeeded, with significantly lower average latency.</p><h3>Key observations</h3><p>There are two main takeaways:</p><ol><li><strong>Latency:</strong><br> The sync server took roughly <strong>7× longer</strong> on average to complete requests.</li><li><strong>Reliability (the critical part):</strong><br> While the async server successfully handled <strong>almost 100%</strong> of requests, the sync WSGI-based server succeeded in only <strong>37%</strong> of them.<br> The remaining requests were dropped entirely, resulting in 5XX errors.</li></ol><p>In other words, the async approach didn’t just improve performance, it fundamentally changed the system’s failure mode under load, from <em>silently dropping traffic</em> to <em>gracefully handling it</em>.</p><h3>Lessons learned</h3><ul><li><strong>WSGI backpressure is real and dangerous</strong><br>When the uWSGI listen queue fills up, requests are silently dropped. This failure mode is easy to miss and hard to reason about under traffic spikes.</li><li><strong>Async changes the failure mode, not just performance</strong><br>Moving to an async server didn’t just reduce latency, it eliminated request loss under load and made bottlenecks visible (CPU / memory) instead of hidden and easy to scale.</li><li><strong>Traffic spikes expose architectural limits, not average load</strong><br>Our system looked fine most of the time. The real issues only appeared during short bursts of high concurrency.</li><li><strong>Observability matters</strong><br>Load balancer 5XX metrics, uWSGI logs, and internal StatsD metrics together told the full story. Any one of them alone would have been misleading.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d20f144c480" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/invisible-failures-the-python-server-mistake-we-made-in-production-7d20f144c480">Invisible Failures: The Python Server Mistake We Made in Production</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Packaging Your TypeScript Client into a Python Backend]]></title>
            <link>https://medium.com/data-science/packaging-your-typescript-client-into-a-python-backend-b087e50c5c1a?source=rss-43233e94ad28------2</link>
            <guid isPermaLink="false">https://medium.com/p/b087e50c5c1a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Itay Bittan]]></dc:creator>
            <pubDate>Fri, 05 Apr 2024 01:05:47 GMT</pubDate>
            <atom:updated>2024-04-05T01:05:47.675Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YASPhhfIdC0paqxZ" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>A FULL HANDS-ON GUIDE</h4><h4>Combine your React Application with the FastAPI web-server</h4><p>In this guide, you will learn how to package a simple TypeScript <a href="https://react.dev/">React Application</a> into a <strong>Python package</strong> and serve it from your <a href="https://fastapi.tiangolo.com/">FastAPI</a> Python web server. Check out the <a href="https://github.com/itayB/vite-project">client</a> and the <a href="https://github.com/itayB/backend">server</a> repos, if you want to see the full code. Let’s get started!</p><p>During the development process, you probably use two different IDEs:</p><ol><li>TypeScript or JavaScript React App window, running on a dedicated listening port (e.g., 5173) to serve the client/frontend pages.</li><li>Python FastAPI, running on a different port (e.g., 8080) to serve a REST API.</li></ol><p>In other words, you have two different servers running locally. Whenever you want to call your FastAPI server, the browser interacts with two different servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NiIJb0auuune5vsnpEwlsQ.png" /><figcaption>Local development (Image by Author)</figcaption></figure><p>While it works fine locally (in localhost), you’ll encounter a “Cross-Origin Request Blocked” error in your browser when you deploy that code. Before taking your code to production, the best practice is to serve both client pages and REST API from the same backend web server. That way the browser will interact with a single backend. It’s better for security, performance, and simplicity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ht6hQcgrUhOIXE1h4FBQrQ.png" /><figcaption>Preparing for Production (Image by Author)</figcaption></figure><h4>1. Create a Simple React Application</h4><p>First, in your workspace directory, let’s create a new TypeScript React application using <a href="https://vitejs.dev/">vite</a>:</p><pre>~/workspace ➜ npm create vite@latest<br>✔ Project name: … vite-project<br>✔ Select a framework: › React<br>✔ Select a variant: › TypeScript</pre><p>Then, enter into the new project directory, install the dependencies, and run the application (<a href="http://localhost:5174/">http://localhost:5173</a>):</p><pre>~/workspace ➜ cd vite-project<br>~/workspace/vite-project ➜ npm install<br>~/workspace/vite-project ➜ npm run dev</pre><p>You should see something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FvDjJCwUuyhz-BUJeweo_Q.png" /><figcaption>First Vite React Template (Image by Author)</figcaption></figure><p>Now, let’s make a small addition to the template — we’ll add an async HTTP call to the future FastAPI backend to get its status:</p><pre>function App() {<br>  ...<br>  const [health, setHealth] = useState(&#39;&#39;);<br><br>  useEffect(() =&gt; {<br>    const getStatus = async () =&gt; {<br>      const response = await fetch(&#39;/v1/health-check/liveness&#39;, {<br>        method: &#39;GET&#39;,<br>      });<br>      let status: { [status: string]: string } = {};<br>      try {<br>        status = await response.json();<br>      } catch (err) {<br>        console.log(`failed to get backend status. ${err}`);<br>      }<br>      setHealth(status[&#39;status&#39;] || &#39;unknown&#39;);<br>    };<br>    getStatus();<br>  }, []);<br><br>  return (<br>  ...<br>     &lt;div&gt;Backend Status: {health}&lt;/div&gt;<br>  ...<br>  )<br>}</pre><p>And now we should get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTTHhBYLHq7gtMAQq8UyLg.png" /><figcaption>With a Backend call (Image by Author)</figcaption></figure><p>At this point, the <strong>Backend Status</strong> is unknown because we haven’t implemented it yet. No worries, we will handle that shortly. Lastly, let’s build the client for packaging it later on:</p><pre>~/workspace/vite-project ➜ npm run build</pre><p>The build output should create a dist folder with the final optimized code that looks like this:</p><pre>└── dist/<br>    ├── assets/<br>    ├── static/<br>    └── index.html</pre><h4>2. Building a Python Package</h4><p>At this point, we are switching to Python. I prefer to work in a <a href="https://docs.python.org/3/library/venv.html">virtual environment</a> for isolation. In a dedicated virtual environment, we will install twine and build , for creating our Python package:</p><pre>~/workspace/vite-project ➜ python3 -m venv venv<br>~/workspace/vite-project ➜ . venv/bin/activate<br>~/workspace/vite-project (venv) ➜ python -m pip install --upgrade pip<br>~/workspace/vite-project (venv) ➜ pip install twine==5.0.0 build==1.2.1</pre><p>Let’s create a new setup.py file in the root folder (vite-project), with the following content:</p><pre>from setuptools import setup<br>from pathlib import Path<br><br><br>cwd = Path(__file__).parent<br>long_description = (cwd / &quot;README.md&quot;).read_text()<br><br>setup(<br>    name=&quot;vite-project&quot;,<br>    version=&quot;0.0.1&quot;,<br>    package_dir={&quot;vite_project&quot;: &quot;dist&quot;},<br>    package_data={&quot;vite_project&quot;: [&quot;**/*.*&quot;]},<br>    long_description=long_description,<br>    long_description_content_type=&quot;text/markdown&quot;,<br>)</pre><p>and run the following to create the package:</p><pre>~/workspace/vite-project (venv) ➜ python setup.py sdist -d tmp<br>~/workspace/vite-project (venv) ➜ python -m build --wheel --outdir tmp<br>~/workspace/vite-project (venv) ➜ twine upload -u ${USERNAME} -p ${PASSWORD} --repository-url ${REPO_URL} tmp/*</pre><p>The last line above is optional if you intend to upload your package to a remote repository such as <a href="https://pypi.org/">PyPI</a>, <a href="https://jfrog.com/artifactory/">JFrog Artifactory</a>, etc.</p><h4>3. Create a FastAPI Python web-server</h4><p>The final step is to build the Python server and use the client package. For that, we will:</p><ul><li>Create a new backenddirectory.</li><li>Create a new virtual environment.</li><li>Install the relevant packages and our client package:</li></ul><pre>~/workspace/backend ➜ python3 -m venv venv<br>~/workspace/backend ➜ . venv/bin/activate<br>~/workspace/backend (venv) ➜ python -m pip install --upgrade pip<br>~/workspace/backend (venv) ➜ pip install fastapi==0.110.0 uvicorn==0.29.0<br>~/workspace/backend (venv) ➜ pip install ~/workspace/vite-project/tmp/vite-project-0.0.1.tar.gz</pre><p>Note that we installed our client package from a local path that we created earlier. If you uploaded your package to a remote repository, you can install it with:</p><pre>~/workspace/backend (venv) ➜ pip install --extra-index-url https://${USERNAME}:${PASSWORD}@${REPO_URL} vite-project==0.0.1</pre><p>Next, let’s create a simple Python server (2 files):</p><h4><strong>__main__.py</strong></h4><pre>from distutils.sysconfig import get_python_lib<br>from fastapi import FastAPI<br>from fastapi.responses import FileResponse<br>from fastapi.staticfiles import StaticFiles<br>from backend.health_router import router<br>from uvicorn import run<br><br><br>def create_app():<br>    app = FastAPI(<br>        title=&quot;Backend Server&quot;,<br>    )<br>    app.include_router(router)<br><br>    client_path = f&quot;{get_python_lib()}/vite_project&quot;<br>    app.mount(&quot;/assets&quot;, StaticFiles(directory=f&quot;{client_path}/assets&quot;), name=&quot;assets&quot;)<br>    app.mount(&quot;/static&quot;, StaticFiles(directory=f&quot;{client_path}/static&quot;), name=&quot;static&quot;)<br><br>    @app.get(&quot;/{catchall:path}&quot;)<br>    async def serve_react_app(catchall: str):<br>        return FileResponse(f&quot;{client_path}/index.html&quot;)<br><br>    return app<br><br><br>def main():<br>    app = create_app()<br>    run(app, host=&quot;0.0.0.0&quot;, port=8080)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h4>health_router.py</h4><pre>from typing import Literal<br>from typing_extensions import TypedDict<br>from fastapi import APIRouter, status<br><br>STATUS = Literal[&quot;success&quot;, &quot;error&quot;, &quot;partial&quot;, &quot;unknown&quot;]<br><br><br>class ReturnHealthcheckStruct(TypedDict):<br>    status: STATUS<br><br><br>router = APIRouter(<br>    prefix=&quot;/v1/health-check&quot;,<br>    tags=[&quot;Health Check&quot;],<br>)<br><br><br>@router.get(<br>    &quot;/liveness&quot;,<br>    summary=&quot;Perform a Liveness Health Check&quot;,<br>    response_description=&quot;Return HTTP Status Code 200 (OK)&quot;,<br>    status_code=status.HTTP_200_OK,<br>    response_model=ReturnHealthcheckStruct,<br>)<br>async def liveness() -&gt; ReturnHealthcheckStruct:<br>    return {&quot;status&quot;: &quot;success&quot;}</pre><p>In the implementation above, we added support for serving any static file from our client application by mounting the static and assets folders, as well as any other client file to be served by our Python server.</p><p>We also created a simple GET endpoint, v1/health-check/liveness that returns a simple {“status&quot;: “success&quot;} JSON response. That way we can ensure that our server handles both client static files and our server-side RESTful API.</p><p>Now, if we go to <a href="http://localhost:8080/">localhost:8080</a> we can see our client up and running. Pay attention to the <strong>Backend Status</strong> below, it’s now success (rather than unknown).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzhrIyKXAzf5Brybi5y2iw.png" /><figcaption>Running a Python server together with React Application (Image by Author)</figcaption></figure><h3>Summary</h3><p>In this tutorial, we created a simple React Application that does a single call to the backend. We wrapped this client application as a Python package and served it from our FastAPI Python web server.</p><p>Using this approach allows you to leverage the best tools in both worlds: TypeScript and React for the frontend, and Python with FastAPI for the backend. Yet, we want to keep high cohesion and low coupling between those two components. That way, you will get all the benefits:</p><ul><li>Velocity, by separating front-end and backend to different repositories, each part can be developed by a different team.</li><li>Stability and Quality, by locking a versioned client package and bumping it only when the server is ready to support a new client version.</li><li>Safety — The browser interacts with only one backend server. We don’t need to enable CORS or any other security-compromising workarounds.</li><li>Simplicity — By working via a single server</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b087e50c5c1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/packaging-your-typescript-client-into-a-python-backend-b087e50c5c1a">Packaging Your TypeScript Client into a Python Backend</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Truth Behind Black Friday Madness in the B2B E-Commerce Industry]]></title>
            <link>https://medium.com/management-matters/the-truth-behind-black-friday-madness-in-the-b2b-e-commerce-industry-fc0c299a2eaa?source=rss-43233e94ad28------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc0c299a2eaa</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[black-friday]]></category>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[management]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Itay Bittan]]></dc:creator>
            <pubDate>Wed, 14 Feb 2024 14:27:32 GMT</pubDate>
            <atom:updated>2024-02-14T14:27:32.220Z</atom:updated>
            <content:encoded><![CDATA[<h4>Behind the Screens: Insights into Teamwork and Challenges during Black Friday Chaos</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6CZgFC3V6Cb-UgD5" /><figcaption>Photo by <a href="https://unsplash.com/@cardmapr?utm_source=medium&amp;utm_medium=referral">CardMapr.nl</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I bet you love Black Friday. As a customer, it’s a great opportunity to purchase wishlist items at a significant discount. Nowadays, you can do it from the sofa, which is even more comfortable. As you can guess, you’re not the only one who has discovered that trick - your family, friends, and everyone else are doing the same. While you and your buddies are enjoying those sales, someone on the other side is paying the price. E-commerce sites handle two or three times the traffic compared to any other day. Everything may look and feel like any other day, but there’s a big challenge under the hood. A lot of effort is made by engineering teams to ensure that your website won’t get stuck, and you’ll have a great experience while shopping.</p><p>Despite sounding like a win-win situation, if you’ve been working in the e-commerce industry for a while, you might find it frustrating. While it should be the most profitable day of the year, there’s a high probability that your website will be out of service. Too many people rush to buy your goods at the same time, and your system probably won’t handle that. It has a bottleneck somewhere, no matter how much effort you invest to make it auto-scaling. The problem is that we usually discover it when it’s too late. Over the years, we’ve created a checklist with manual preparations to ensure our readiness.</p><p>Having worked at <a href="https://www.dynamicyield.com/">Dynamic Yield</a> for a few years now and survived many Black Fridays, I’ll share the procedures we follow to promise the best for our clients. Dynamic Yield is a B2B company that leverages hundreds of e-commerce businesses every day. In other words, we collect, process, and serve the data of our customer’s customers (end users), handling millions of online users a day, which generates tens of thousands of events every second.</p><p>Black Friday is the time of year that we work for and wait for. It’s a moment of truth for every engineer who has spent time trying to build a state-of-the-art system that can handle such a scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qrjJE9yiya5C-GB1xUgELQ.jpeg" /><figcaption>Black Friday 2023 war room at Dynamic Yield office (Image by author)</figcaption></figure><p>While serving millions of users daily is challenging, handling double or triple the number of users and their requests for a single weekend is not as easy as it seems. Here is what it takes from an engineering perspective:</p><h4>Black Friday Preparations</h4><ul><li><strong>R&amp;D leaders meeting.</strong> Gather together to make sure everyone is aware and aligned. Over the last years, we grew our R&amp;D department rapidly, a lot of new employees joined the ride and a lot of new components were added. We need to make sure that everyone understands and is aware of this big event, and nothing will be missed.</li><li><strong>Mapping all the services.</strong> We maintain a list of all our services, so every team can derive action items as the next step. In addition, we have a list of all shared resources, like Databases, some are managed services (such as <a href="https://redis.com/">Redis</a>, <a href="https://aws.amazon.com/msk/">MSK</a>, <a href="https://www.scylladb.com/">Scylla</a>, etc.) and others are self-managed (<a href="https://www.elastic.co/">Elasticsearch</a>, <a href="https://prometheus.io/">Prometheus</a>, etc.).</li><li><strong>Estimations</strong> - Based on:<br>- Typical loads, utilizations, traffic, etc.<br>- Previous years&#39; Black Friday trends.<br>- Expectations (compared to daily routine) that we get from our customers<br>- Whether the service is already elastic (<a href="https://medium.com/swlh/high-scale-web-server-with-kubernetes-1b35da281dd7">Horizontal Pod Autoscaler in Kubernetes</a>, Auto Scale Group in EC2, etc.) or not.<br>- Cost Consequences <br>We decide on the target numbers and tune (temporary) limitations.</li><li><strong>Scale-out party, assign scale-out tasks to engineers</strong>, for instance: <br>- Increase Elasticsearch coordinating nodes by 150%<br>- Add another replica (shard) for all Elasticsearch indices, for better availability.<br>- Set a new (temporary) maximum threshold for pod/instance replicas in each of our services.</li><li><strong>Contact our 3rd party providers </strong>- sharing estimations details such as expected traffic and required resources (compute, memory, storage, etc.), and ask them to increase those resources one week ahead (most Black Friday sales tend to start a few days before) and reconfigure what we can (like maximum throughput in Redis).</li><li><strong>Polish our monitoring dashboards &amp; ensure that we have visibility for everything</strong> - we are using <a href="https://grafana.com/">Grafana</a> with a variety of data sources such as <a href="https://prometheus.io/">Prometheus</a>, <a href="https://graphiteapp.org/">Graphite</a>, etc., and other observability tools like <a href="https://opensearch.org/">OpenSearch</a>, <a href="https://grafana.com/docs/tempo/latest/">Tempo</a>, etc. With so many code contributors it’s hard to maintain so many Grafana dashboards and one month before Black Friday is a great opportunity to review, cleanup, and update all of our dashboards and make sure everything is up to date and we focus on what matters.</li><li><strong>Reviewing and challenging our disaster recovery plans (DRP).</strong> Over the years we learned (the hard way) what can go wrong and how to bypass the problem. Although we aim to build a robust and resilient system, we want to make sure that if one service is out of order there’s no domino effect and we can live without a single feature for a short time rather than being completely out of service.</li><li><strong>Code freeze</strong> - a few weeks ahead of Black Friday we avoid deployments of new features and deploying only bug fixes or patches. During that period, most of our engineers develop new features locally or in remote development and staging environments, holding off on deployment until December.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-O9R_CZp7tsnMEazAw7pg.png" /><figcaption>The traffic rate (requests/sec) of a random service at Dynamic Yield on typical days vs. Black Friday</figcaption></figure><h4>During Friday</h4><p>On Friday morning/noon, we open a war room - a shared, large meeting space with a representative engineer/leader from each team. That way we can quickly tackle any unplanned scenario, collaborate effectively, and get the most accurate up-to-date picture of what’s going on.</p><p>The atmosphere during that evening has improved over the years. As we grew and gained experience, the atmosphere shifted from tension, alertness, and awareness to excitement and anticipation of achieving new traffic records.</p><p>Imagine one large table (expanding over the years) surrounded by laptop-armed software engineers, chargers, and power splitters scattered around, with at least two huge screens presenting real-time graphs.</p><p>The event is also indulgent, featuring a tremendous variety of snacks, beers, and pizzas.</p><p>We usually turn off the lights a few hours after the peak time of both the US and Europe and sync our on-call supporters in case something goes wrong early in the morning.</p><p>Lastly, our engineering leader sends a proud email with some geeky high records spikes screenshots.</p><h4>Post Black Friday</h4><p>One comfortable fact about Black Friday is that it comes right before Cyber Monday, another big e-commerce event, so we can keep the extra resources for a few more days (after Cyber Monday is over) and then scale in and down again.</p><p>Then, we conduct a postmortem, discussing what went well, what went wrong, and deriving action items, prioritizing them to ensure we learn and improve from year to year.</p><p>We also examine the new high achieved during those days and make sure that our system thresholds are tuned accordingly. We also summarize it for reference in the coming year.</p><p>A few days later, when the data is available, we perform a cost analysis to see how much we spent during this holiday period compared to a typical day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rlxYj6KSjX2zuxIjB-Xfaw.jpeg" /><figcaption>AI-generated image (Image by author)</figcaption></figure><h4>Conclusions</h4><p>There’s no doubt that Black Friday is an exciting, sparkling, and shiny event, with many discounts and presents that bring joy to everyone. This story emphasizes the extensive work behind the scenes to ensure a smooth operation, making Black Friday feel like just another day. Countless efforts were made around the clock to deliver a seamless experience!</p><p>I hope you enjoyed and I would love to learn how you prepare for Black Friday. Please leave a comment below :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc0c299a2eaa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/management-matters/the-truth-behind-black-friday-madness-in-the-b2b-e-commerce-industry-fc0c299a2eaa">The Truth Behind Black Friday Madness in the B2B E-Commerce Industry</a> was originally published in <a href="https://medium.com/management-matters">Management Matters</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test and cover your code today!]]></title>
            <link>https://medium.com/data-science/test-and-cover-your-code-today-e80c27d08dab?source=rss-43233e94ad28------2</link>
            <guid isPermaLink="false">https://medium.com/p/e80c27d08dab</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Itay Bittan]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 08:38:48 GMT</pubDate>
            <atom:updated>2023-12-21T08:38:48.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gs8dkLKb6JitVinr" /><figcaption>Photo by <a href="https://unsplash.com/@yancymin?utm_source=medium&amp;utm_medium=referral">Yancy Min</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Test and Cover Your Code Today!</h3><h4>A hands-on guide for adding a motivational GitHub action to your repository</h4><p>I’ll start with a confession: as a software engineer, I hated and avoided writing tests for years. I came across so many dusty projects — some with no tests at all, others that had tests but those had never run as part of the CI/CD pipelines, and the last ones included really poor test coverage.</p><p>On one hand, there are plenty of reasons why we should write tests but on the other, there are more excuses (or “justifications”) why we skip those.</p><p>While aiming to be a professional, I was always jealous of those shiny 100% test coverage open-source repositories and dreamed about that in my day-to-day repositories out there. Four years ago, while grappling with myself about that matter, I found <a href="https://github.com/Bachmann1234/diff_cover">diff-cover</a>, a great open-source project with a simple mission — cover your <strong>own</strong> changes with tests. Here is how the authors describe it:</p><blockquote>Diff coverage is the percentage of new or modified lines that are covered by tests. This provides a clear and achievable standard for code review: If you touch a line of code, that line should be covered. Code coverage is every developer’s responsibility!</blockquote><p>In a nutshell, diff-cover assumes that you are using <a href="https://git-scm.com/">Git</a> and running a coverage tool. Using git it’s easy to get <strong>your</strong> modified line numbers and compare them with the uncovered line numbers of your favorite coverage tool. Almost all of the coverage tools can yield a unified and generic XML format, no matter what your code language is (Python, JavaScript, etc.)</p><p>To sum up, the process I have been doing until now as part of the CI was:</p><ol><li>Run all tests with a coverage tool, using the <a href="https://pypi.org/project/pytest/">pytest</a> and <a href="https://pypi.org/project/pytest-cov/">pytest-cov</a> packages:</li></ol><pre>py.test -o junit_family=xunit2 --junitxml result.xml -xv --ff --cov-config=.coveragerc --cov=&lt;my_package&gt; --cov-report=xml --cov-report=term &lt;tests_package&gt;</pre><p>(note that it will create <em>coverage.xml</em> and <em>result.xml</em> report files).</p><p>2. Run diff-cover tool, using the <a href="https://pypi.org/project/diff-cover/">diff-cover</a> package:</p><pre>diff-cover coverage.xml --compare-branch=origin/master</pre><p>which will print something like the following output:</p><pre>-------------<br>Diff Coverage<br>Diff: origin/master...HEAD, staged and unstaged changes<br>-------------<br>my_package/connections/snowflake_client.py (100%)<br>my_package/logic/celery_tasks/top_score_task.py (100%)<br>my_package/queries/build_algorithm_studio_dataframes.py (100%)<br>-------------<br>Total:   16 lines<br>Missing: 0 lines<br>Coverage: 100%<br>-------------</pre><p>As you can see from the output above, I’ve made changes in 3 different files, and each of them is fully covered (I had to add some new tests and other existing tests already covered some of my changes).</p><p>Seeing that Diff Coverage report on each PR (Pull Request) has made everyone addicted to achieving that 100%. We want to prove that we are responsible for our changes and can cover them, instead of being perceived as losers and getting a low percentage. Moreover, as a side effect, we have experienced smaller, incremental changes in PRs, which is another <a href="https://www.awesomecodereviews.com/best-practices/code-review-best-practices/#small">best practice</a>. That’s because everyone thinks twice before adding redundant lines of code now.</p><p>After using this methodology for a few years now, we see a constant increase in the overall coverage percentages of our repositories. As a result, there has been an increase in our production stability as well.</p><h4>New GitHub Action</h4><p>A few months ago, my talented colleague <a href="https://medium.com/@asafgallea">Asaf Gallea</a> decided to leverage this success into a simpler yet more powerful <a href="https://github.com/aGallea/tests-coverage-report">new GitHub Action</a>. This Action applies the same idea as diff-cover and also generates a friendly report as a comment in your Pull Request, providing links to uncovered lines in case you missed something. The new action also allows you to set a minimal coverage threshold (default to 80%) — otherwise, the <a href="https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/collaborating-on-repositories-with-code-quality-features/about-status-checks">status check</a> will fail and you won’t be able to merge your changes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J1MxTqr4wEQOD-HYVkwRIA.png" /><figcaption>Test coverage action report (image by author)</figcaption></figure><p>In the image above we see the GitHub Action report example. There is a minimal threshold of 95%, there were 20 lines changed in this Pull Request, with 18 lines covered by tests, and two lines, 505–506 are not covered. Since we achieved only 90% coverage for the changed files, the status check failed and it’s impossible to merge this into the master branch.</p><p>Note that this report says nothing about the total coverage of the repository. It might be low (60%), and yet, any new change has to pass 95% so eventually, the total coverage will increase.</p><h4>Setup tests-coverage-report action in your repository</h4><p>That’s it! Now let’s add this Action to <strong>your</strong> repository within a few steps. I will assume that it’s a Python project but you can add it to projects in different programming languages as well.</p><p>In the repository’s root folder, create the .github/workflows folders if it does not yet exist. Now, within the workflows folder let’s create a new file called <em>test.yml </em>with the following content:</p><pre># This workflow will install Python dependencies, run tests check the coverage<br><br>name: Test with coverage<br><br>on:<br>  pull_request:<br><br>jobs:<br>  test:<br><br>    runs-on: ubuntu-latest<br><br>    steps:<br>    - uses: actions/checkout@v3<br>    - uses: actions/setup-python@v3<br>      with:<br>        python-version: 3.10<br>    - name: Install Dependencies<br>      run: |<br>        python -m pip install --upgrade pip<br>        pip install pytest pytest-cov<br>    - name: Test with pytest<br>      run: py.test -o junit_family=xunit2 --junitxml result.xml -v --ff --cov=&lt;my_package&gt; --cov-report=xml --cov-report=term &lt;my_tests&gt;<br>    - name: Coverage Report<br>      if: always()<br>      uses: aGallea/tests-coverage-report@1.3.1<br>      with:<br>        min-coverage-percentage: &#39;100&#39;<br>        fail-under-coverage-percentage: &#39;true&#39;<br>        cobertura-path: ./coverage.xml<br>        junit-path: ./result.xml</pre><p>make sure to replace the <em>&lt;my_package&gt;</em> and <em>&lt;my_tests&gt;</em> above with your package name and the tests folder accordingly.</p><p>That’s it! if you open a new Pull Request to add this file, the action should be fired automatically and you’ll see the report:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hScmsmcbX4L4l4bd4yZ3Cg.png" /><figcaption>Empty test coverage action report (image by author)</figcaption></figure><p>Note that since there are no changes in the package files (source files), there are no coverage details to present. The image above was taken from <a href="https://github.com/itayB/serversion/pull/14">my Pull Request</a> while adding the test coverage action into one of my public repositories.</p><h3>Summary</h3><p>You have just completed the first action (double meaning) that will change your life and make you a better developer. Our generation is addicted to likes, claps, upvotes, and geeks like us to show off our professionalism with a 100% coverage report as well. We would love to get feedback, suggestions, and feature requests for this action that can enhance your testing experience and motivation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e80c27d08dab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/test-and-cover-your-code-today-e80c27d08dab">Test and cover your code today!</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating Airflow backend database from MySql to PostgreSQL]]></title>
            <link>https://medium.com/apache-airflow/migrating-airflow-backend-database-from-mysql-to-postgres-25eebed59f8d?source=rss-43233e94ad28------2</link>
            <guid isPermaLink="false">https://medium.com/p/25eebed59f8d</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Itay Bittan]]></dc:creator>
            <pubDate>Tue, 13 Dec 2022 20:49:21 GMT</pubDate>
            <atom:updated>2023-03-05T11:53:24.822Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*oFtufjSXiK4Udjl7NFEsrw.png" /></figure><p><a href="https://www.dynamicyield.com/">Dynamic Yield</a> recently completed the migration of our backend database from MySql to PostgreSQL. This post will detail why we migrated and how, and what you should consider in this process.</p><h3>Background</h3><p><a href="https://www.dynamicyield.com/">Dynamic Yield</a> engineers are <a href="https://airflow.apache.org/">Airflow</a> enthusiastic fans! We have several Airflow clusters for managing various data pipelines (building deep-learning models, generating daily reports, etc.). We run four different clusters and try to keep them up to date in order to make sure they are running the latest and greatest features and that they have the proper security and vulnerability fixes. Our journey with Airflow began three years ago at version 1.10.x and we have upgraded it to every other minor version. We have had consistent positive upgrade experiences; the upgrades were fast and smooth.</p><p>We have also learned that Airflow’s vast community is one of its main strengths. There’s an impressive active Slack workspace, a lot of issues on Github, questions and (quick) answers in StackOverflow, and tons of content everywhere.</p><p>Our clusters are running on top of Kubernetes with one scheduler pod, one web-server pod, and a dedicated namespace to run all Kubernetes executors. In addition, we used AWS RDS with MySql 8.30 engine as our Airflow backend database. Choosing MySql back then was a hasty decision, we chose it because we were familiar with it.</p><h4>Migration Failed</h4><p>A few months ago, during our effort to upgrade Airflow (from v2.2.5 to v2.3.2) something changed. For the first time, running the airflow db upgrade command failed in the middle and the migration stopped with a scary <a href="https://github.com/apache/airflow/issues/24526">exception</a>. Luckily, we got fast assistance (via <a href="https://github.com/apache/airflow/discussions/25866">Github discussions</a>) from <a href="https://medium.com/@jarekpotiuk">Jarek Potiuk</a> (PMC member at Airflow), who helped us to solve the problem.</p><p>Together, we managed to pass the upgrade challenge by running some manual SQL commands (collation encoding fixes).</p><p>In the midst of that stressful time, we realized that our decision regarding the backend database was hasty. We chose MySql because we had more experience with it and Airflow supported it. Now we realize that Airflow’s top <a href="https://github.com/apache/airflow/discussions/25866#discussioncomment-3446054">recommendation</a> is PostgreSQL.</p><h4>Motivation</h4><p>Below are some of the reasons that prompted us to make the transition from MySql to PostgreSQL:</p><ol><li>MySQL does <strong>not</strong> provide transactional integrity of migrations, so if a migration fails in the middle, it is half-done, and re-running it again would probably fail.</li><li>We discovered that we are in the minority. According to <a href="https://airflow.apache.org/blog/airflow-survey-2022/#which-metadata-database-do-you-use-single-choice">Airflow Survey 2022</a>, 82% use PostgreSQL and only 16% use MySql as their metadata backend.</li><li>Airflow’s official Docker image for ARM processors has only PostgreSQL and SQLite drivers for(MySQL and MsSQL clients are missing).</li><li>PostgreSQL is located as the first backend database in <a href="https://airflow.apache.org/docs/apache-airflow/stable/howto/set-up-database.html#choosing-database-backend">Airflow documentation</a>.</li><li>Airflow backend schema is relatively tiny. It has only 33 tables (for v2.3.2) and nothing fancy, so it is fairly easy to migrate.</li><li>MySQL doesn’t perform well on ARM so it is hard to run Airflow locally on our Mac M1/M2.</li><li><a href="https://github.com/apache/airflow/pull/25938#discussion_r954956657">Some other</a> implicit signs/gut feeling that MySql won’t be supported by Airflow forever, so we better migrate now before it is too late (our pipelines are not getting smaller).</li></ol><h3>The Migration Process, Let’s Do It!</h3><h4>Warnings — Before You Begin</h4><ol><li>Make sure that you have a fresh backup of your current MySql database. Although we just copy from MySql (read-only), wrong permissions + lack of focus may lead to unexpected results.</li><li>Downtime is required. How long? depends on how much data you have (it took us 18 minutes for 4GB of data). In our case, our processing layer (orchestrated by Airflow) can be down for a short period and we will close the gap right after! To avoid any differentiation between the old MySql database and the new PostgreSQL, we want to make sure that no new writes will be made to the old database while we copy the data.</li><li>local/staging environment comes first. Don’t start with Production! Gain confidence and practice in those environments first. It is better to make mistakes sooner rather than later (in production).</li><li>Be aware of implicit changes. While you’re testing and examining your pipeline with the new PostgreSQL backend you’ll probably trigger your pipelines. Those might generate some new data. In case of a revert, some of the new data require your attention (deletion of output in S3, new models that were built, etc).</li></ol><h4>Create a New PostgreSQL Database</h4><p>We are running on AWS, so we created a fresh new instance in RDS. We choose PostgreSQL 13.7 engine; Notice that PostgreSQL 14 is not yet <a href="https://airflow.apache.org/docs/apache-airflow/stable/howto/set-up-database.html?highlight=postgres#choosing-database-backend">supported</a> by Airflow.</p><p>At this point, we used <a href="https://www.pgcli.com/">pgcli</a> (PostgreSQL CLI tool) to <a href="https://airflow.apache.org/docs/apache-airflow/stable/howto/set-up-database.html#setting-up-a-postgresql-database">create</a> airflow_user with its permissions to the database:</p><pre><strong>CREATE</strong> <strong>DATABASE</strong> airflow_db;<br><strong>CREATE</strong> <strong>USER</strong> airflow_user <strong>WITH</strong> PASSWORD &#39;airflow_pass&#39;;<br><strong>GRANT</strong> <strong>ALL</strong> <strong>PRIVILEGES</strong> <strong>ON</strong> <strong>DATABASE</strong> airflow_db <strong>TO</strong> airflow_user;</pre><p>Note that the airflow_dbdatabase can be made upon RDS initialization.</p><h4>Generate the Schema</h4><p>Although you can migrate the schema from MySql as well, we preferred to generate the schema from scratch. It would be better to have a fresh new “PostgreSQL optimized” schema, generated by the Airflow cli.</p><p>You can do it with Docker:</p><pre>docker run --rm -e AIRFLOW__DATABASE__SQL_ALCHEMY_CONN=&#39;postgresql+psycopg2://airflow_user:&lt;airflow_password&gt;@airflow-backend.my-domain.com/airflow_db&#39; apache/airflow:2.3.2 db init</pre><p>Alternatively, you can install Airflow locally on an empty virtual environment, set the relevant environment variable, and run the init command:</p><pre>pip install apache-airflow==2.3.2 psycopg2-binary==2.9.3<br>...</pre><pre>export AIRFLOW__DATABASE__SQL_ALCHEMY_CONN=&#39;postgresql+psycopg2://airflow_user:&lt;airflow_password&gt;@airflow-backend.my-domain.com/airflow_db&#39;<br>airflow db init</pre><h4>Cleanup (optional)</h4><p>At this point, there’s a new schema in our new PostgreSQL database but there is some data that need to be cleaned up. Airflow init command (and upgrade as well) seeding some data that we want to clean up before copying the data from MySql. We used <a href="https://www.pgcli.com/">pgcli</a> again for that and truncate the non-empty tables:</p><pre>TRUNCATE ab_permission_view_role, alembic_version, connection, log_template, slot_pool CASCADE;</pre><h4>Stop Writes to MySql</h4><p>Take down the scheduler, and the web server, and make sure that there are no running executors. To be on the safe side, verify the current activity of the MySql backend in the AWS console and make sure there are 0 connections to this database.</p><figure><img alt="RDS User interface shows that the “Current activity” has no connections" src="https://cdn-images-1.medium.com/max/372/1*iacpltccWFUbFgtJMmEV7w.png" /><figcaption>AWS RDS Console (Image by author)</figcaption></figure><h4>Copy The Data</h4><p>Lastly, we want to copy the data. There are <a href="https://en.wikibooks.org/wiki/Converting_MySQL_to_PostgreSQL">several ways</a> to do that, we choose <a href="https://github.com/dimitri/pgloader">pgloader</a>, which is a data-loading tool for PostgreSQL. We preferred to use a battle-tested, generic and popular tool rather than writing custom code, so it could help anyone else as well.</p><p>We used the <a href="https://github.com/dimitri/pgloader/pkgs/container/pgloader/36580385?tag=sha256-5518cf30a414a492a08dbcb9cc4fdc1eddf947a62dd5fdabc49a2ebafd82a40d.sig">docker version</a> with the following airflow-db.load configuration file:</p><pre>LOAD DATABASE</pre><pre>FROM      mysql://airflow_user:&lt;airflow_password&gt;@airflow-old-backend.my-domain.com/airflow_db</pre><pre>INTO postgresql://airflow_user:&lt;airflow_password&gt;@airflow-new-backend.my-domain.com/airflow_db</pre><pre>WITH data only, batch size = 15MB, prefetch rows = 8000,<br>     workers = 2, concurrency = 1</pre><pre>SET MySQL PARAMETERS<br>  net_read_timeout  = &#39;500&#39;,<br>  net_write_timeout = &#39;500&#39;</pre><pre>--- excluding table names matching &#39;ab_permission_view_role&#39;, ..</pre><pre>ALTER SCHEMA &#39;airflow&#39; RENAME TO &#39;public&#39;;</pre><p>and run it with pgloader airflow-db.load. If you skipped the “Cleanup” section above, make sure to uncomment (--- ) the exclude tables.</p><p>After a few minutes (depending on your data size) you’ll get a summary report:</p><pre>                   table name     errors       rows      bytes<br>-----------------------------  ---------  ---------  ---------<br>              fetch meta data          0        137           <br>               Create Schemas          0          0           <br>             Create SQL Types          0          0           <br>                Create tables          0         66           <br>               Set Table OIDs          0         33           <br>-----------------------------  ---------  ---------  ---------<br>                   public.log          0    7794904     2.0 GB<br>         public.task_instance          0    2569229   672.6 MB<br>                   public.job          0    2122821   431.9 MB<br>       public.task_reschedule          0     784259   128.5 MB<br>               public.dag_run          0     409071   125.4 MB<br>                  public.xcom          0     319200    83.3 MB<br>             public.task_fail          0     279197    38.5 MB<br>rendered_task_instance_fields          0     269394   596.7 MB<br>              public.sla_miss          0      40008     3.5 MB<br>               public.dag_tag          0      10080   284.2 kB<br>    public.ab_permission_view          0       7507    83.9 kB<br>          public.ab_view_menu          0       2607    69.6 kB<br>                   public.dag          0       2552   632.3 kB<br>        public.serialized_dag          0       2552    31.6 MB<br>               public.session          0        231   294.8 kB<br>ublic.ab_permission_view_role          0        211     1.7 kB<br>         public.ab_permission          0         12     0.1 kB<br>               public.ab_role          0          5     0.0 kB<br>            public.connection          0          3     0.6 kB<br>       public.alembic_version          0          1     0.0 kB<br>      public.ab_register_user          0          0           <br>               public.ab_user          0          1     0.2 kB<br>          public.ab_user_role          0          1     0.0 kB<br>      public.callback_request          0          0           <br>              public.dag_code          0          1    20.9 kB<br>            public.dag_pickle          0          0           <br>          public.import_error          0          0           <br>          public.log_template          0          1     0.2 kB<br>       public.sensor_instance          0          0           <br>             public.slot_pool          0          1     0.0 kB<br>              public.task_map          0          0           <br>               public.trigger          0          0           <br>              public.variable          0          0           <br>-----------------------------  ---------  ---------  ---------<br>      COPY Threads Completion          0          2           <br>               Create Indexes          0         86           <br>       Index Build Completion          0         86           <br>              Reset Sequences          0          0           <br>                 Primary Keys          0         33           <br>          Create Foreign Keys          0         18           <br>              Create Triggers          0          0           <br>             Install Comments          0          0           <br>-----------------------------  ---------  ---------  ---------<br>            Total import time          ✓   14613849     4.0 GB</pre><p>Locally it can be run like this:</p><pre>docker run --rm -v $PWD/airflow-db.load:/airflow-db.load ghcr.io/dimitri/pgloader:3.6.8 pgloader airflow-db.load</pre><h4>Validation</h4><p>Using pgcli you can see that all the tables actually exist by the \dt command:</p><pre>+--------+-------------------------------+-------+--------------+<br>| Schema | Name                          | Type  | Owner        |<br>|--------+-------------------------------+-------+--------------|<br>| public | ab_permission                 | table | airflow_user |<br>| public | ab_permission_view            | table | airflow_user |<br>| public | ab_permission_view_role       | table | airflow_user |<br>| public | ab_register_user              | table | airflow_user |<br>| public | ab_role                       | table | airflow_user |<br>| public | ab_user                       | table | airflow_user |<br>| public | ab_user_role                  | table | airflow_user |<br>| public | ab_view_menu                  | table | airflow_user |<br>| public | alembic_version               | table | airflow_user |<br>| public | callback_request              | table | airflow_user |<br>| public | connection                    | table | airflow_user |<br>| public | dag                           | table | airflow_user |<br>| public | dag_code                      | table | airflow_user |<br>| public | dag_pickle                    | table | airflow_user |<br>| public | dag_run                       | table | airflow_user |<br>| public | dag_tag                       | table | airflow_user |<br>| public | import_error                  | table | airflow_user |<br>| public | job                           | table | airflow_user |<br>| public | log                           | table | airflow_user |<br>| public | log_template                  | table | airflow_user |<br>| public | rendered_task_instance_fields | table | airflow_user |<br>| public | sensor_instance               | table | airflow_user |<br>| public | serialized_dag                | table | airflow_user |<br>| public | session                       | table | airflow_user |<br>| public | sla_miss                      | table | airflow_user |<br>| public | slot_pool                     | table | airflow_user |<br>| public | task_fail                     | table | airflow_user |<br>| public | task_instance                 | table | airflow_user |<br>| public | task_map                      | table | airflow_user |<br>| public | task_reschedule               | table | airflow_user |<br>| public | trigger                       | table | airflow_user |<br>| public | variable                      | table | airflow_user |<br>| public | xcom                          | table | airflow_user |<br>+--------+-------------------------------+-------+--------------+<br>SELECT 33</pre><p>and even better, try it with \dt+ to see the additional Size column that indicates that the data exist.</p><h4>Rewire Airflow’s backend</h4><p>Depending on your setup and configuration, you need to reconfigure Airflow to use the new PostgreSQL database. You should set the <a href="https://airflow.apache.org/docs/apache-airflow/stable/configurations-ref.html#sql-alchemy-conn">sql_alchemy_conn</a> with a new value, something like:</p><pre>postgresql://airflow_user:&lt;airflow_password&gt;@airflow-new-backend.my-domain.com/airflow_db</pre><p>and make that you have updated both the scheduler and web server. Now you can bring up the scheduler and the web server and we are <strong>done!</strong></p><h3>Summary</h3><p>By choosing PostgreSQL as our backend database, we are now in line with the community’s preference and Airflow’s recommendation. I really hope that it looks doable now, although we encountered some issues along the way. I strongly recommend that you read the “caveats” section below to avoid any potential issues and save yourself some time and frustration.</p><p><strong>Update</strong>: we smoothly upgrade Airflow from 2.3.2 to 2.4.2, this time with PostgreSQL as our backend.</p><p>Good luck!</p><h3>Caveats</h3><h4>The “Killed” log</h4><p>pgloader print aKilled log message and crash with no useful information. We tried to add a --debug flag, a — verbose flag but none of them gave a useful clue. Checking the Postgres logs (via RDS console) shows us:</p><pre>FATAL: terminating connection because protocol synchronization was lost</pre><p>Which wasn’t useful as well. Finally, we found that pgloaderhas a minimum requirement of 4GB of memory. Seems like recently it was even <a href="https://github.com/dimitri/pgloader/commit/b24eba972d264b8763943a88ac5e76d6a487c95a">increased to 16GB</a>.</p><h4>“Heap exhausted during garbage collection” log</h4><p>pgloader crash with Heap exhausted during garbage collection log message. We tuned the batch size, prefetch rows and number of workers in the airflow-db.load file to overcome this issue. You can read the <a href="https://pgloader.readthedocs.io/en/latest/pgloader.html?highlight=prefetch#batch-behaviour-options">documentation</a> for more details.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25eebed59f8d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apache-airflow/migrating-airflow-backend-database-from-mysql-to-postgres-25eebed59f8d">Migrating Airflow backend database from MySql to PostgreSQL</a> was originally published in <a href="https://medium.com/apache-airflow">Apache Airflow</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airflow’s Magic Loop]]></title>
            <link>https://medium.com/apache-airflow/airflows-magic-loop-ec424b05b629?source=rss-43233e94ad28------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec424b05b629</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Itay Bittan]]></dc:creator>
            <pubDate>Thu, 07 Jul 2022 08:31:50 GMT</pubDate>
            <atom:updated>2022-07-07T08:31:50.775Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*sesfl3V6mvwVQUb1" /></figure><h4>A simple optimization that saves us a significant running time</h4><p>Here at <a href="https://www.dynamicyield.com/">Dynamic Yield</a>, we use several various <a href="https://airflow.apache.org/">Airflow</a> clusters for managing a lot of different pipelines. Each of those clusters runs tens of thousands of tasks on a daily basis. We run on top of <a href="https://kubernetes.io/">Kubernetes</a> and in a typical cluster we have an Airflow scheduler pod, an Airflow web-server pod, and a dedicated Kubernetes namespace to run all of our <a href="https://airflow.apache.org/docs/apache-airflow/stable/executor/kubernetes.html">Kubernetes executor</a> pods (which handle all of the tasks).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0EP_28dLHgANVAZn1RtEg.png" /><figcaption>Airflow on Kubernetes (image by author)</figcaption></figure><p>In one of our Airflow clusters, we have an isolated pipeline, per customer (business), so each customer has its own DAG (encapsulated). Thus, we have a few thousands of DAGs dynamically created. Let’s assume that we have the following customers&#39; data file:</p><pre>1000,Customer1,e-commerce,2017-30-01<br>1001,Customer2,publisher,2018-12-02<br>1002,Customer3,gaming,2019-20-05<br>...<br>3999,CustomerX,e-commerce,2022-07-07</pre><p>Our dag.py looks like:</p><pre>customers = read_customers_data_file()<br>start_time = default_timer()</pre><pre>for customer_id, name, vertical, creation_date in customers:<br>    dag_id = f&quot;customer_{customer_id}&quot;<br>    dag = DAG(<br>      dag_id,<br>      tags=[name],<br>      ...<br>    )<br>    with dag:<br>        task_1 = PythonOperator(...)<br>        tesk_2 = SparkSubmitOperator(...)<br>        task_3 = S3KeySensor(...)<br>        # more tasks<br>        ...<br>        task_1 &gt;&gt; [task_2, task_3]<br>    globals()[dag_id] = dag</pre><pre>took = default_timer() - start_time<br>logger.info(f&quot;took: {took}&quot;)</pre><p>By measuring the time it takes to load all of those DAGs we found that it can take up to 120 seconds! to ensure that Airflow DAGs load won’t timeout, we set the following configuration:</p><pre>AIRFLOW__CORE__DAGBAG_IMPORT_TIMEOUT=120.0  # default: 30.0</pre><p>Updating the scheduler DAGs every few minutes is good enough for us, as each DAG runs once a day and it can take a few more minutes to add a new customer. On the other hand, after running with this setup for a while we noticed that for each Kubernetes executor (which starts for each task) we load all those DAGs over and over again. That’s because Airflow has a <a href="https://www.astronomer.io/blog/airflow-2-scheduler#single-scheduler-optimization">fast-follow</a> (or “mini-scheduler”) workflow that can trigger the following task. In other words, each and every worker (we have thousands of them going up and down all day long) spends up to 120 seconds loading thousands of DAGs, while only one DAG is relevant. Practically if we have ~4,000 Daily DAGs with 10 tasks each we spend 4,000 X 10 X 120s =4,800,000 seconds (in the worst case), every day!</p><h4>Magic Condition</h4><p>Since each of our dynamic DAGs is totally independent of the others (each DAG represents a different isolated customer pipeline) our loop could load only the relevant DAG, assuming we are on a worker (Kubernetes executor) pod. We used the advantage of the command’s arguments of the pod to figure out whether our code run within the scheduler or within a worker.</p><p>Scheduler args : [&quot;scheduler&quot;]</p><p>Worker args : [&quot;airflow&quot;, &quot;tasks&quot;, &quot;run&quot;, &quot;customer_1000&quot;, &quot;daily&quot;, ..]</p><p>As you can see above, a worker starts with the dag_id as the fourth argument, so here is our updated dag.py :</p><pre>customers = read_customers_data_file()</pre><pre><strong>current_dag = None<br>if len(sys.argv) &gt; 3:<br>    current_dag = sys.argv[3]</strong></pre><pre>start_time = default_timer()</pre><pre>for customer_id, name, vertical, creation_date in customers:<br>    dag_id = f&quot;customer_{customer_id}&quot;<br>    <strong>if current_dag is not None and current_dag != dag_id:<br>        continue</strong></pre><pre>    dag = DAG(<br>      dag_id,<br>      tags=[name],<br>      ...<br>    )<br>    with dag:<br>        task_1 = PythonOperator(...)<br>        task_2 = SparkSubmitOperator(...)<br>        task_3 = S3KeySensor(...)<br>        # more tasks<br>        ...<br>        task_1 &gt;&gt; [task_2, task_3]<br>    globals()[dag_id] = dag</pre><pre>took = default_timer() - start_time<br>logger.info(f&quot;took: {took}&quot;)</pre><p>and now it takes only ~200<strong>ms</strong> to load the DAG in each worker!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EaLyIAp3ih8gkJgr" /><figcaption>Photo by <a href="https://unsplash.com/@veri_ivanova?utm_source=medium&amp;utm_medium=referral">Veri Ivanova</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Observations</h4><ol><li>We use Airflow’s internal behavior (which passes the dag_id in args) for optimizing our loading time. It was tested with Airflow v2.3.2 (at latest as of Jul 7, 2022) but it might be broken in future versions. Pay attention if you upgrade to a newer version.</li><li>dag_id can be also retrieved from the pod’s labels/annotations. Like args, this is something that might break as it’s not documented in Airflow’s official APIs, so be careful with that.</li><li>We pulled the dag_id from args without any validation for the simplicity of this example. In reality, we added more validations to ensure that we lose the optimization in the worse case and nothing more. A quick improvement would be to test that the prefix of the 4th argument meets our expectations: current_dag.startswith(&quot;customer_&quot;) .</li></ol><h4>Summary</h4><p>While our cluster takes Airflow to its limit with thousands of DAGs and tasks, we found that Airflow performs pretty well on that scale. Having said that, there is always a place for improvements as we demonstrate above. For the sake of generalization, Airflow loads all DAGs in the workers all the time. Since a case of isolated DAGs (with no dependency between them) is pretty common, this trick might help others as well, by speeding up their pipelines and making them more efficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec424b05b629" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apache-airflow/airflows-magic-loop-ec424b05b629">Airflow’s Magic Loop</a> was originally published in <a href="https://medium.com/apache-airflow">Apache Airflow</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wrong Spark configuration that cost us $3k/month]]></title>
            <link>https://itnext.io/wrong-spark-configuration-that-cost-us-3k-month-dc21f2a0a113?source=rss-43233e94ad28------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc21f2a0a113</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[spark-history-server]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cost-reduction]]></category>
            <dc:creator><![CDATA[Itay Bittan]]></dc:creator>
            <pubDate>Fri, 17 Jun 2022 11:51:44 GMT</pubDate>
            <atom:updated>2022-06-17T11:51:44.050Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H3nOrnC9P9oL7RR_" /><figcaption>Photo by <a href="https://unsplash.com/@joshappel?utm_source=medium&amp;utm_medium=referral">Josh Appel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Spark version: 3.2.0</p><p>Here at <a href="https://www.dynamicyield.com/">Dynamic Yield</a>, we run thousands of <a href="https://spark.apache.org/">Spark</a> applications every day. Over the last two years, we worked hard to upgrade our infrastructure to run those jobs on <a href="https://kubernetes.io/">Kubernetes</a> and we continuously improve our system.</p><p>One of the innocent configurations that we added a few months ago was:</p><pre>spark.eventLog.rolling.enabled: true<br>spark.eventLog.rolling.maxFileSize: 16m</pre><p>That’s it. Two lines, more than $3,000 per month:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pAIk9YSWYJTqUPGzpkd5iw.jpeg" /><figcaption>AWS Cost Explorer before and after the rolling flag (image by author)</figcaption></figure><p>Assuming you’re using the Spark history server to monitor your Spark applications, make sure that it&#39;s not going to cost you more than it should.</p><h4>Spark History Configuration</h4><p>Spark history server is a great useful tool for monitoring your applications. By adding a few configuration lines to thespark-submit command, application logs saved in your preferable storage (AWS S3 in our case) and being available for exploration later on. The most basic configurations are:</p><pre>spark.eventLog.enabled: true<br>spark.eventLog.dir: s3a://a-team-bucket/history-logs</pre><p>Those will make sure that the application will be available for future exploration.</p><p>While reading the documentation, <a href="https://spark.apache.org/docs/latest/monitoring.html#spark-history-server-configuration-options">Applying compaction on rolling event log files</a> looks promising, especially after suffering from non-responsive UI while monitoring extremely slow applications in the past. Nothing implies the price of this <a href="https://docs.google.com/document/d/12bdCC4nA58uveRxpeo8k7kGOI2NRTXmXyBOweSi4YcY/edit#heading=h.7bmfccqq7ozy">new feature</a>.</p><h4>Implementation Details</h4><p>The history server&#39;s refresh interval is 10 seconds by default and it can be tuned via spark.history.fs.update.interval . Now, let’s say we store the last 50k applications in an S3 bucket and each application is represented by one file. In that case, there are 50 ListBucket operations behind the scene (each returning up to 1,000 objects) every 10 seconds:</p><pre>.<br>├── spark-00079d419d924b4d900a0a27cd6a9ae0<br>├── spark-000af08856194e6e82046bc65237bc78<br>├── ...<br>├── ...<br>└── spark-z01051c66d93409583b17001c34fc21c</pre><p>On the other hand, using the rolling logs will create a folder per application which looks like this:</p><pre>.<br>├── eventlog_v2_spark-00079d419d924b4d900a0a27cd6a9ae0<br>|   ├── appstatus_spark-00079d419d924b4d900a0a27cd6a9ae0<br>│   └── events_1_spark-00079d419d924b4d900a0a27cd6a9ae0<br>├── eventlog_v2_spark-000af08856194e6e82046bc65237bc78<br>|   ├── appstatus_spark-000af08856194e6e82046bc65237bc78<br>│   └── events_1_spark-000af08856194e6e82046bc65237bc78<br>├── ...<br>├── ...<br>└── eventlog_v2_spark-z01051c66d93409583b17001c34fc21c<br>    ├── appstatus_spark-z01051c66d93409583b17001c34fc21c<br>    └── events_1_spark-z01051c66d93409583b17001c34fc21c</pre><p>This time history server performs the same 50 ListBucket operations to get all folders and then another <strong>50,000 ListBucket operations for getting each folder&#39;s content!</strong> In other words, 50,050 ListBucket operations every 10s.</p><p>After debugging the source code I found that for file-system abstraction, where logs can be stored both in a local file system or in hdfs like S3 — tree walking is being used (list all folders and then each folder’s files) although deep tree scan is available.</p><h3>Conclusions</h3><ul><li>Tune the update interval that fits you. If you’re monitoring your applications once a day, 1 minute, 1 hour, or a daily update might be enough for you.</li><li>Don’t hurry up to add configurations when you don’t have problems. Rotate might be useful for monitoring large/heavy applications. If you don’t feel pain while using your history server, you probably don’t need that.</li><li>You can mix between those. The same history server path supports a mix of folders (rotate logs) and files. If you go with the rotate logs configurations, add them only to your biggest applications.</li><li>Don’t forget to monitor the price you pay for storage. While it is perceived as cheap compared to compute resources, you don’t want to waste your budget on redundant operations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rv-0Fb9WN5iLJDkxl-bQMA.jpeg" /><figcaption>Spark History server (image by author)</figcaption></figure><h3>Appendix</h3><p>If you’re interested in running the Spark history server locally and seeing what’s going on, you may find this guide useful.</p><h4>Running spark history server in IntelliJ</h4><ol><li>Clone spark repository from Github.</li><li>Open IntelliJ.</li><li>Search for org.apache.spark.deploy.history.HistoryServerand run it (it will probably fail).</li><li>Edit Run Configurations:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*QXMOZu21qUMhbq3i96euPQ.png" /></figure><p>choose module. I chose thespark-core_2.12 module and we will extend it in a second.</p><p>Tip: If you try to run from the script ( /bin/start-history-server.sh) you will see the run command is printed in the log first line.</p><p>5. Go to Project Structure → Project Settings → Modules and select spark-core_2.12. Click on the Dependencies tab and add all jars from assembly/target/scala-2.12/jars. If you’re testing AWS / Hadoop jars add them as well.</p><p>6. In the conf folder, add spark-defaults.conf file and add your custom configuration, for example:</p><pre>spark.history.fs.logDirectory   s3a://logs-bucket/history<br>spark.hadoop.fs.s3a.aws.credentials.provider    org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider<br>spark.hadoop.fs.s3a.endpoint    http://localhost:9000<br>spark.hadoop.fs.s3a.connection.ssl.enabled  false<br>spark.hadoop.fs.s3a.path.style.access   true<br>spark.history.fs.update.interval    30s</pre><p>If you’re using <a href="https://min.io/">minio</a> (with docker) to simulate S3 you can add the credentials in the Run Configuration (step 4) via environment variables.</p><p>7. If you want to see debug logs, copy the log4j2.properties.template file from theconf directory to log4j2.properties and change the rootLogger.level severity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc21f2a0a113" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/wrong-spark-configuration-that-cost-us-3k-month-dc21f2a0a113">Wrong Spark configuration that cost us $3k/month</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS S3 data-source for Grafana]]></title>
            <link>https://awstip.com/aws-s3-data-source-for-grafana-de68c143a3fa?source=rss-43233e94ad28------2</link>
            <guid isPermaLink="false">https://medium.com/p/de68c143a3fa</guid>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Itay Bittan]]></dc:creator>
            <pubDate>Wed, 29 Dec 2021 11:05:29 GMT</pubDate>
            <atom:updated>2021-12-31T07:30:43.047Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WIRaf7VfTwfypWEW" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=medium&amp;utm_medium=referral">Luke Chesser</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Enhance visibility to your data</h4><p>Here at <a href="https://dynamicyield.com/">Dynamic Yield</a> we use AWS S3 quite a lot! A few months ago we moved our <a href="https://spark.apache.org/">Spark</a> infrastructure from EC2 (in stand-alone mode) to <a href="https://kubernetes.io/">Kubernetes</a> (cluster mode). Because moving ETLs can be risky (it&#39;s the first stage of our deep-learning pipeline), we tried to increase our observability to mitigate errors as much as possible.</p><p>As a B2B company, our data is partitioned by business (clients) and dates and looks like this:</p><pre>.<br>├── client=1000<br>|   ├── date=2021-09-25<br>│   │   └── hour=00<br>│   │       └── partition-00.parquet   102MB<br>│   └── ...<br>├── client=2000<br>│   ├── date=2021-09-25<br>│   │   ├── hour=00<br>│   │   │   ├── partition-00.parquet   103MB<br>│   │   │   ├── partition-01.parquet   110MB<br>│   │   │   ├── partition-02.parquet   100MB<br>│   │   │   └── partition-03.parquet   102MB<br>│   │   ├── hour=01<br>│   │   │   ├── partition-00.parquet   102MB<br>│   │   │   ├── partition-01.parquet   107MB<br>│   │   │   ├── partition-02.parquet   109MB<br>│   │   │   └── partition-03.parquet   101MB<br>│   │   ├── hour=02<br>│   │   ├── ...<br>│   └── ...<br>├── date=2021-09-26<br>└── date=2021-09-27</pre><p>If you ever used S3 via AWS console UI, you know that there’s no tree view and no easy way to ensure that all your data exists. Tree view could help to “feel” two fundamental metrics:</p><ul><li>Total partition size (how much data client 1000 has in 2021–09–25)</li><li>Number of objects (how many files client 1000 has in 2021–09–25)</li></ul><p>While we can easily get those 2 metrics with the <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html">ListObjectV2</a> API, we wanted some visualizations so we could easily detect anomalies/errors while migrating our infrastructure.</p><h4>aws-s3 data source plugin</h4><p>While <a href="https://grafana.com/docs/grafana/latest/datasources/aws-cloudwatch/">AWS CloudWatch data source</a> can show you metrics such as total bucket size, upload/download rates, etc, it doesn’t show statistics per object prefixes, partitioned by time.</p><p>I developed a new <a href="https://github.com/org-insights/aws-s-3">aws-s3 plugin</a> that visualizes your data by your own partitioning. While it’s not officially published in Grafana plugins, it’s fully open-sourced and you can try it now!</p><h4>Try me first — playground</h4><p>The easiest and the fastest way to see the data source in action is to run it locally via docker:</p><ol><li>Clone the Github repository: <a href="https://github.com/org-insights/aws-s-3">https://github.com/org-insights/aws-s-3</a></li><li>In your terminal, run: docker-compose up</li><li>Open your browser and go to <a href="http://localhost:3000/">http://localhost:3000</a></li><li>You can see both s3-example-dashboard and the data source configurations.</li></ol><p>You can tweak the instertion.sh script to add/remove objects to/from S3 (which is simulated locally by <a href="https://min.io/">min.io</a>)</p><h4>Install a new data-source</h4><p>You can download the <a href="https://github.com/org-insights/aws-s-3/releases">latest release</a> to your Grafana’s plugin <a href="https://grafana.com/docs/grafana/latest/administration/configuration/#plugins">folder</a> in:</p><pre>/usr/local/var/lib/grafana/plugins</pre><p>In Grafana Configuration, click “Add data source” and choose aws-s3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*Zp8LX9MkVKyoMqvYK1biuQ.png" /><figcaption>Grafana configuration (image by author)</figcaption></figure><p>Choose authentication provider and fill the relevant configurations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*RVjVsRnqv6YFSYbQyOL9iw.png" /><figcaption>Data source configuration (image by author)</figcaption></figure><p>That’s it - your new data source is ready to use!</p><h4>Adding new graph</h4><p>Graph query consists of several values:</p><ul><li>Bucket: the bucket name (without prefix).</li><li>Prefix: the prefix we want to visualize.</li><li>Metric: Size or Number of keys (objects).</li></ul><p>The prefix supports a special templating using &lt; and &gt; . Within those triangular brackets, you can use special characters such as:</p><ul><li>Year is represented by 2–4 y digits: yyyy, yyy or yy.</li><li>Month is represented by 1–2 M digits: MM or M.</li><li>Day is represented by 1–2 d digits: dd or d.</li><li>Hour is represented by 1–2 h digits: hh or h.</li><li>Minute is represented by 1–2 m digits: mm or m.</li></ul><p>The prefix client=1000/date=&lt;yyyy-MM-dd&gt; for instance, with a time range between 2021–09–01 00:00:00and 2021-09-10 00:00:00 will visualize the following prefixes:</p><ul><li>client=1000/date=2021-09-02</li><li>client=1000/date=2021-09-03</li><li>client=1000/date=2021-09-04</li><li>client=1000/date=2021-09-05</li><li>client=1000/date=2021-09-06</li><li>client=1000/date=2021-09-07</li><li>client=1000/date=2021-09-08</li><li>client=1000/date=2021-09-09</li><li>client=1000/date=2021-09-10</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DzxAWfvhulYS7leazrcDqw.png" /><figcaption>Query Editor (image by author)</figcaption></figure><p>You can switch between the metrics in the bottom right dropdown.</p><h4>Summary</h4><p>AWS-S3 data source helps to visualize our S3 data with two general metrics: size and number of objects. While you can easily extend it to support other metrics as well, I tried to “keep it simple” and generic as much as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*emM4J1CMHloFpuZlVQl33Q.png" /><figcaption>S3 dashboard (image by author)</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de68c143a3fa" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/aws-s3-data-source-for-grafana-de68c143a3fa">AWS S3 data-source for Grafana</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTP Compression - boost your server’s speed]]></title>
            <link>https://itnext.io/http-compression-boost-your-servers-speed-a5bad6403452?source=rss-43233e94ad28------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5bad6403452</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Itay Bittan]]></dc:creator>
            <pubDate>Sat, 20 Mar 2021 20:18:07 GMT</pubDate>
            <atom:updated>2021-03-20T20:18:07.361Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5tMiI1VYJVSGLu-T" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Improve latency and cost by enabling web-server compression</h4><p>We are all working really hard for making an impact and once in a while there’s an opportunity for making a HUGE impact by a really small effort. After reading this post you’ll be able to make a fast impact on your web-servers and improve your site’s performance!</p><p><a href="https://en.wikipedia.org/wiki/Representational_state_transfer">REST</a> API (a subset of HTTP) is one of the most popular APIs. If you are working in a <a href="https://en.wikipedia.org/wiki/Software_as_a_service">SaaS</a> company you probably use it as an external API for communicating with your customers and you might also use it internally across your services. At <a href="https://www.dynamicyield.com/">Dynamic Yield</a> we are serving thousands of HTTP requests per second and we strive for easy wins such as latency improvements and cost optimizations. Compression is one of the ways that helped us by simply reducing the bytes on the wire.</p><p>Most of the modern web browsers today <a href="https://caniuse.com/brotli">support</a> compressions such as gzip and Brotli out of the box and asking for it by default.</p><p>It turns out that most of the web-server frameworks don’t respect “<em>Accept-Encoding: gzip”</em> header by default and we need to actively enable this compression feature. We will cover few frameworks below.</p><p>Enabling compression can help for better latency and cost reduction as fewer bytes are being transferred over the network. Here is what we get:</p><ul><li>Lower latency internally, measured in AWS Load-Balancer by Target Response Time metric.</li><li>Lower round-trip time as fewer bytes need to be transferred to the end-user over the internet.</li><li>Cost reduction: Cloud providers charge for <a href="https://aws.amazon.com/ec2/pricing/on-demand/#Data_Transfer">data transfer</a> IN/OUT/across availability zones etc. fewer bytes means that you save more money.</li></ul><p>If you google for <a href="https://gist.github.com/hellerbarde/2843375">the numbers that every programmer should know</a> you’ll find that compressing data is much faster than sending packets over the network. That implies that compressing the data will save latency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-KMDpyXWOT_cdwYdGyMEtw.png" /><figcaption>Processed Bytes improvement while applying compression (Image by author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WRCGtjEp1OGKG383Q7ffKw.png" /><figcaption>Response Time improvement while applying compression (Image by author)</figcaption></figure><p>You can see in the graphs above that we are processing <strong>~80%</strong> fewer bytes per minute after enabling the compression and our latency was improved by <strong>~15%!</strong></p><h3>Real-World Servers Examples</h3><p>Let see several examples in different frameworks/languages:</p><h4>Tornado (Python)</h4><pre>import tornado.ioloop<br>import tornado.web<br><br>class MainHandler(tornado.web.RequestHandler):<br>    def get(self):<br>        self.write(&quot;x&quot; * 1024)<br><br>def make_app():<br>    return tornado.web.Application([<br>        (r&quot;/&quot;, MainHandler),<br>    ], compress_response=True)<br><br>if __name__ == &quot;__main__&quot;:<br>    app = make_app()<br>    app.listen(8888)<br>    tornado.ioloop.IOLoop.current().start()</pre><p><a href="https://www.tornadoweb.org/">Tornado</a> (tested on version 6.1) is a Python web framework and asynchronous networking library. The snippet above was copied from their “Hello, world” <a href="https://www.tornadoweb.org/en/stable/#hello-world">example</a> with slight changes:</p><ol><li>Tornado applies compression for a content <a href="https://github.com/tornadoweb/tornado/blob/master/tornado/web.py#L3083">length of 1024</a> and above. Thus, the <em>“Hello, world” </em>string replaced by <em>“x” * 1024 </em>for this demonstration.</li><li><em>compress_response=True</em> was added to the Application’s constructor.</li></ol><p>Now let’s test it! first, let’s use <em>curl</em> to send a request without compression:</p><pre>~ $ curl -vs <a href="http://127.0.0.1:8888/">http://127.0.0.1:8888</a><br>&gt; GET / HTTP/1.1<br>&gt; Host: 127.0.0.1:8888<br>&gt;<br>&lt; HTTP/1.1 200 OK<br>&lt; Content-Type: text/html; charset=UTF-8<br>&lt; Content-Length: 1024<br>&lt; Vary: Accept-Encoding<br>&lt;<br>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</pre><p>Now let’s add the <em>compressed</em> flag (to simulate a web browser):</p><pre>~ $ curl -vs --compressed <a href="http://127.0.0.1:8888/">http://127.0.0.1:8888</a><br>&gt; GET / HTTP/1.1<br>&gt; Host: 127.0.0.1:8888<br>&gt; Accept-Encoding: deflate, gzip<br>&gt;<br>&lt; HTTP/1.1 200 OK<br>&lt; Content-Type: text/html; charset=UTF-8<br>&lt; Content-Length: 29<br>&lt; Vary: Accept-Encoding<br>&lt; Content-Encoding: gzip<br>&lt;<br>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</pre><p>As you can see above, the “<em>Accept-Encoding: deflate, gzip”</em> header was added to the request and our server respond with “<em>Content-Encoding: gzip” </em>header. As a result, our content was compressed to “<em>Content-Length: 29”</em> (compared to “<em>Content-Length: 1024”</em> in the first request).</p><h4>Aiohttp (Python)</h4><p><a href="https://docs.aiohttp.org/en/stable/">AIOHTTP</a> (tested on version 3.7.4) is an Asynchronous HTTP Server for <a href="https://docs.aiohttp.org/en/stable/glossary.html#term-asyncio">asyncio</a>. The snippet below was copied from their <a href="https://docs.aiohttp.org/en/stable/#server-example">Server example</a> with a minor change; we added a compression middleware to compress the response before sending it back to the user:</p><pre>from aiohttp import web<br><br>@web.middleware<br>async def compression_middleware(request, handler):<br>    response = await handler(request)<br>    response.enable_compression()<br>    return response<br><br>async def handle(request):<br>    return web.Response(text=&quot;x&quot; * 128)<br><br>app = web.Application(middlewares=[compression_middleware])<br>app.add_routes([web.get(&#39;/&#39;, handle)])<br><br>if __name__ == &#39;__main__&#39;:<br>    web.run_app(app)</pre><p>Note that there’s no minimum content length here and each request will be compressed (you can, however, apply a minimum length rule by adding a condition in the <em>compression_middleware</em> function above).</p><h4>Express (node.js)</h4><p><a href="https://expressjs.com/">Express</a> (tested on version 4.17.1) is a fast, unopinionated, minimalist web framework for node.js. The snippet below was copied from the <a href="https://expressjs.com/en/starter/hello-world.html">hello-world example</a> and adjusted to use the <a href="http://expressjs.com/en/resources/middleware/compression.html">compression middleware</a>. Enabling compression is recommended on express’s <a href="https://expressjs.com/en/advanced/best-practice-performance.html">production best practices page</a>.</p><pre>const compression = require(&#39;compression&#39;)<br>const express = require(&#39;express&#39;)<br>var app = express()<br>app.use(compression())<br>const port = 3000<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>    res.send(&quot;x&quot;.repeat(1024))<br>})<br><br>app.listen(port, () =&gt; {<br>    <strong><em>console</em></strong>.log(`Example app listening at http://localhost:${port}`)<br>})</pre><p>As we saw in the first example (Tornado), express compression has also a minimum <a href="https://github.com/expressjs/compression/blob/3fea81d0eaed1eb872bf3e0405f20d9e175ab2cf/index.js#L56">threshold of 1024</a> which you can tune in the instantiation. As opposed to Tornado’s curl example above, the <em>Content-Length</em> header is missing in the response but we do see the <em>Content-Encoding: gzip</em> header:</p><pre>~ $ curl -vs --compressed <a href="http://127.0.0.1:3000/">http://127.0.0.1:3000</a><br>&gt; Accept-Encoding: deflate, gzip<br>&gt;<br>&lt; HTTP/1.1 200 OK<br>&lt; Content-Type: text/html; charset=utf-8<br>&lt; Content-Encoding: gzip<br>&lt;<br>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</pre><h4>Ruby on Rails</h4><p>Ruby on Rails (tested on version 5.2.4.5) is a server-side web application framework written in Ruby. Adding the <em>Deflater</em> middleware will do the magic here:</p><pre>require_relative &#39;boot&#39;<br>require &#39;rails/all&#39;<br><br>Bundler.require(*Rails.groups)<br><br>module <em>Myapp<br>  </em>class <em>Application </em>&lt; Rails::Application<br>    config.load_defaults 5.2<br>    config.middleware.insert_after ActionDispatch::Static, Rack::Deflater<br>  end<br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nzATaRcEkvqol3aer63dcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIqwQUNrCW33PhtFwA7uoA.png" /><figcaption>Adding compression middleware (Image by author)</figcaption></figure><h3>Real-World Clients Examples</h3><p>Enabling server-side compression is sufficient if your clients are web browsers. If you’re using HTTP to communicate between your other internal components, you need to explicitly ask for a compressed response from the server by adding the “<em>Accept-Encoding: deflate, gzip</em>” request header.</p><h4>Elasticsearch Client (Python)</h4><p><a href="https://www.elastic.co/elasticsearch/">Elasticsearch</a> is a distributed, <strong>RESTful</strong> search and analytics engine. If you are using <a href="https://elasticsearch-py.readthedocs.io/en/stable/">Python Elasticsearch Client</a> you can <a href="https://elasticsearch-py.readthedocs.io/en/stable/#compression">enable</a> the compression in the client instantiation:</p><pre><strong>from</strong> <strong>elasticsearch</strong> <strong>import</strong> Elasticsearch<br>es = Elasticsearch(hosts, http_compress=<strong>True</strong>)</pre><h4>Other clients</h4><p>The simplest way to ask for a compressed response is to add the “<em>Accept-Encoding: deflate, gzip</em>” header field to the request. Some clients are doing that by default and most of them also decompress the response automatically for you.</p><h3>Back to our services after a week</h3><p>A picture is worth a thousand words, so here are some screenshots of our Load Balancers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T-bD6IGLJZfMVzt4-APvmw.png" /><figcaption>(Image by author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXOHHlYTPF-3jaozjk-IMA.png" /><figcaption>(Image by author)</figcaption></figure><h3>Observations</h3><ol><li>Compression level — gzip support compression levels from 1 (minimum compression) to 9 (maximum compression). Tuning that level is a tradeoff between the time it takes to compress and the outcome size. Compression is CPU-intensive work so make sure you’re monitoring CPU utilization as well. In Elasticsearch for instance, you can configure it via <em>http.compression_level</em> in the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-http.html#_http_settings">HTTP settings</a>. All other web-servers allow configuring this value as well.</li><li>Brotli is the (relatively) new kid in town, initially <a href="https://en.wikipedia.org/wiki/Brotli">released in 2013</a>. gzip on the other hand is here since the <a href="https://en.wikipedia.org/wiki/Gzip">early 90’s</a>. While a lot of <a href="https://engineering.linkedin.com/blog/2017/05/boosting-site-speed-using-brotli-compression">benchmarks</a> states that Brotli can improve even further than gzip, configuring Brotli on your web-server framework might be trickier and requires a bit more work.</li><li>We need to distinguish between static-content that can be compressed with a higher compression level in advance and dynamic-content like our RESTful API that generates a different response for each request and needs to be served as fast as we can.</li><li>Compression will be most effective for areas with limited bandwidth or slow internet connection. In such cases, the end-user experience will be optimal!</li><li>If you’re using CDN make sure it configured properly and supports the compression algorithm as well. If you’re using a reverse proxy (<a href="https://www.nginx.com/">nginx</a> for example) you might want to delegate the gzip encoding to it.</li><li>Follow REST principles and best practices and use GET whenever you want to fetch data. In GET method you’ll enjoy HTTP <strong>304 Not Modified</strong> response code that saves data transfer which eventually saves time&amp;money (more details <a href="https://devcenter.heroku.com/articles/increasing-application-performance-with-http-cache-headers#conditional-requests">here</a>).</li></ol><h3>Summary</h3><p>In this post, we saw how easy is to enable compression support for HTTP web-servers and clients. There’s a reason why all modern web browsers ask for a compressed response by default. Although it comes with a cost of higher CPU utilization, there’s nothing like a fast user experience on your website.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5bad6403452" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/http-compression-boost-your-servers-speed-a5bad6403452">HTTP Compression - boost your server’s speed</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>