<?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 Sergii Onufriienko on Medium]]></title>
        <description><![CDATA[Stories by Sergii Onufriienko on Medium]]></description>
        <link>https://medium.com/@sonufrienko?source=rss-b3c1df38836------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7HIhZErFFJImxXTuij5lbw.jpeg</url>
            <title>Stories by Sergii Onufriienko on Medium</title>
            <link>https://medium.com/@sonufrienko?source=rss-b3c1df38836------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 11:26:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sonufrienko/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[How Much AI Training Bots Really Cost You]]></title>
            <link>https://medium.com/@sonufrienko/how-much-ai-training-bots-really-cost-you-482fac2e841c?source=rss-b3c1df38836------2</link>
            <guid isPermaLink="false">https://medium.com/p/482fac2e841c</guid>
            <category><![CDATA[ai-train-bots]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[cloud-cost-optimization]]></category>
            <category><![CDATA[internet]]></category>
            <dc:creator><![CDATA[Sergii Onufriienko]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 07:20:18 GMT</pubDate>
            <atom:updated>2026-08-18T07:20:18.107Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J-xpiWuaRosu_DNUxZoLfQ.jpeg" /></figure><p><em>Our biggest “user” was a robot. It read two terabytes of our data every day, paid us nothing, and nearly took the site down. Here’s how we caught it — and the one rule that’s saving about $140,000 a year.</em></p><p><em>(Names, domains and identifying details have been changed. Every number is real and was measured, not guessed.)</em></p><p>It started, as these things usually do, with a message from management: <strong>“The traffic bill jumped 49% in four days. Is it our own bots?”</strong></p><p>Fair question. The platform — an international rental-listings marketplace — runs its own data-collection crawlers (let’s call them Project Magpie) that gather listings from partner sites around the world. When traffic spikes, the call comes from inside the house often enough that you check.</p><p>So I checked. Properly. Not a dashboard glance — I parsed <strong>every single request the site served for four straight days</strong>. 342 million log lines, a full census, cross-checked against two independent data sources until they agreed to within 0.05%.</p><p>The suspect walked free. Project Magpie was running 14% <em>below</em> its normal level. Zero requests — literally zero out of 100 million — came from our own network addresses. Our bots and the mystery traffic were actually <em>negatively</em> correlated: when ours slowed down, the bill went up.</p><p>Whoever was eating our lunch, it wasn’t us.</p><h3>The reveal</h3><p>It was one crawler.</p><p>A single bot, introducing itself with the name of one of the largest tech companies on Earth, was making <strong>54 million requests a day</strong> — more than every human visitor combined. It was consuming 42% of everything we served and driving 76% of the recent cost increase. Its appetite had doubled in three days and grown tenfold in ten. Four of the five biggest traffic days in the site’s entire recorded history happened that week, back to back.</p><p>Picture a restaurant where one guest eats 42% of the food, brings 53 million friends, and never orders anything.</p><p>(One caveat worth its own sentence: a name in a web request is a costume, not an ID card. Anyone can claim to be anyone. What we measured was traffic <em>wearing</em> the badge — verifying the badge is a separate job.)</p><p>And here’s the part I find genuinely funny. The famous AI crawlers everyone worries about — the ones from the big-name AI labs — cost us about <strong>$6 a day, combined</strong>. The one nobody was talking about cost <strong>$155 a day</strong> in bandwidth alone, before counting the extra servers scrambling to feed it.</p><h3>The embarrassing part</h3><p>It broke no rules. Because we had no rules.</p><p>Our robots.txt — the little file that tells crawlers what they may and may not do — was <strong>139 bytes</strong> long and politely allowed almost everything. No crawl limits. No bot-specific rules. No firewall, no rate limiting, no bot protection. Anywhere. In 600+ days of logs, we had never once asked this traffic to stop.</p><p>That’s the honest version of most “AI bots are killing my website” stories. It’s less an invasion than an open buffet with no prices on the menu.</p><h3>Why it costs so much</h3><p>Two mechanisms, both simple.</p><p>First, <strong>bots pay full price on every page</strong>. A human loads one page, then clicks around in tiny, cheap increments. A crawler downloads the complete document on every single hop. Result: bots averaged 56 KB per request against 22 KB for humans, and took 85% of our total bandwidth.</p><p>Second, the damage doesn’t stay on the bandwidth line. Our server fleet auto-scales with load, and it had been <strong>pinned at its hard maximum of 200 machines for four consecutive days</strong>. We weren’t just losing money — we were one traffic spike away from an outage, and no invoice anywhere says “bots” next to the cost of those extra servers.</p><p>One more thing your cloud console won’t tell you: <strong>it lies about yesterday</strong>. The billing dashboard was under-reporting the newest day by about 10%, because charges land late. Trusting it, you’d conclude the fire was going out while it spread. We corrected for the lag and predicted the true daily cost: $437. When the invoice finally closed days later, it read <strong>$436.28</strong>. Off by 0.2%. That’s the level of confidence you want <em>before</em> walking into a leadership meeting.</p><h3>The fix took 35 minutes</h3><p>Once you can prove <em>who</em> and <em>how much</em>, the fix is almost boring: one rule at the edge (Cloudflare, in our case) turning AI-training crawlers away before they ever reach — or bill — our servers. We watched the traffic curve bend 35 minutes after the toggle.</p><p>The first full day with the block on:</p><ul><li><strong>AI-crawler traffic:</strong> 1.68 TB/day → 59 GB/day (−96.5%)</li><li><strong>Total requests:</strong> 96M/day → 43M/day (−55%)</li><li><strong>Servers running:</strong> 192 → 110 (−43%)</li><li><strong>Database load:</strong> 2,860 writes/s → 1,815 writes/s (−37%)</li><li><strong>Human traffic:</strong> steady → +12.8%</li><li><strong>Daily cloud spend:</strong> ~$2,030 → ~$1,650</li></ul><p>And the number everyone actually cares about: <strong>zero collateral damage</strong>. Google kept crawling. Real users were unaffected — human traffic came in <em>higher</em> than the same day a week earlier, confirmed by three independent controls. The monthly cloud bill landed below where it was before the crisis began.</p><p>Total saving: roughly <strong>$390 a day — call it $140,000 a year</strong> — from one afternoon of blocking, made possible by a week of careful measurement.</p><h3>The twist</h3><p>Two days later I re-measured, because a blocked crawler is a motivated crawler.</p><p>It had found a side door. One of our country domains wasn’t covered by the rule, and within 24 hours <strong>98.5% of the crawler’s surviving traffic had concentrated onto that single domain</strong> — growing 39% a day. That same afternoon, a brand-new crawler with no name and a generic software signature showed up and quietly started working through the site.</p><p>The lesson: blocking bots is not an event. It’s a practice. You measure, you block, you re-measure, and you keep an alarm on your traffic so a quiet reversal shows up in hours — not on next month’s invoice.</p><h3>Five things to steal from this story</h3><ol><li><strong>Ask your team one question this week:</strong> “What share of our traffic is bots, and what does it cost us?” If the answer is a shrug, the shrug has a price. Ours was about $12,000 a month.</li><li><strong>Measure before you block.</strong> An early spot-check of one sampled hour told us the increase was “broad-based, no single culprit.” The full census showed one crawler was 76% of it. Bad data produces wrong villains — and wrong fixes.</li><li><strong>Don’t trust your billing console’s newest days.</strong> They’re systematically understated. Cross-check against raw usage metrics, or you’ll make decisions on numbers that are 10% too kind.</li><li><strong>Bandwidth is only half the bill.</strong> This crawler also burned over half its share of our computing power on millions of tiny requests, and pushed the fleet into an availability risk that never appears as a line item.</li><li><strong>Prove no collateral damage.</strong> The scariest part of blocking is accidentally hitting Google or real customers. Build the verification into the plan — for us, human traffic going <em>up</em> was the fact that turned “we think it worked” into “it worked.”</li></ol><h3>What comes next: don’t just block — charge</h3><p>The endgame is more interesting than a wall. Cloudflare has opened the waitlist for its Monetization Gateway and is running Pay Per Crawl in beta — built on x402, an HTTP standard that lets a website answer a bot with “402 Payment Required,” a price, and a way to pay per request, settled in under a second. AI companies clearly want the data. The infrastructure to <em>sell</em> it to them at machine speed is arriving right now.</p><p>Which reframes this whole story. That crawler wasn’t just a $140,000-a-year cost. It was $140,000 of unpriced demand knocking on the door. The companies that figure out metering first won’t be writing posts like this one — they’ll be sending invoices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=482fac2e841c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I cut our staging AWS bill by 75% — and only broke it once]]></title>
            <link>https://medium.com/@sonufrienko/how-i-cut-our-staging-aws-bill-by-75-and-only-broke-it-once-ea01762a4f25?source=rss-b3c1df38836------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea01762a4f25</guid>
            <category><![CDATA[aws-ecs]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-cost-optimization]]></category>
            <category><![CDATA[aws-rds]]></category>
            <dc:creator><![CDATA[Sergii Onufriienko]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 11:04:06 GMT</pubDate>
            <atom:updated>2026-08-10T11:04:06.686Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A 29-day story about zombie databases, a bucket with a hoarding problem, and an autoscaler that was paying for an empty chair.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V3fr-hJ1jla1Hz7nf_Rm1g.png" /></figure><p>Some context first. I run the infrastructure at Magpie, a data platform — a web app, an API, background workers, and an ingestion fleet that never sleeps. In mid-June we stood up a fresh staging environment the way most staging environments get stood up: by cloning production and promising ourselves we’d right-size it later.</p><p>On July 2nd, “later” arrived. I opened Cost Explorer.</p><p><strong>$147. For one day.</strong> Of staging.</p><p>That’s roughly $4,400 a month — $53,000 a year — for an environment whose entire job is to let a handful of engineers find out whether their code works before it meets real users. It had no traffic to speak of. It had no SLA. What it had was production’s instance classes, production’s replica counts, production’s monitoring add-ons, and production’s appetite.</p><p>Twenty-nine days later it cost <strong>$36 a day</strong>. Same services, same 24/7 uptime, no scheduled shutdowns, nothing switched off at night. A 75% cut, worth about <strong>$40,000 a year</strong> — and along the way, the same playbook got rehearsed for our ~200-host production fleet, where the zeros are bigger.</p><h3>Round one: the zombies</h3><p>The first pass didn’t require cleverness. It required looking.</p><p>The single largest line on the bill was <strong>three database clusters named old-*</strong> — leftovers from the environment build-out, restored from snapshots as a “temporary” migration step and never deleted. Three memory-optimized instances, running around the clock, serving exactly zero queries.</p><p><strong>$25 a day</strong> for databases nobody could name a purpose for. They weren’t even in Terraform; they existed only in the console and in the bill.</p><p>I’ve come to believe <em>temporary</em> is the most expensive word in cloud computing.</p><p>The rest of round one was right-sizing what the production clone had inherited: the main Postgres writer dropped two sizes, the ingestion database and the country-data cluster moved to Graviton burstable instances, a read replica that staging absolutely did not need was removed, and every cache node shrank. Applied on Friday, July 3rd — the classic Friday deploy, except the only thing at risk was money.</p><p>Result: <strong>$129/day → $91/day.</strong></p><p>One honesty note, because cost work is full of flattering lies: the day-over-day drop actually showed −$60, and I only claimed −$44. The other ~$20 was one-off data-transfer from the build-out finishing on the same day. It was going away whether I showed up to work or not. If you’re going to take credit, take credit for the steady state — not for noise that happened to coincide with your commit.</p><h3>The zombies rise</h3><p>A footnote that earned its own heading. To kill the old-* clusters I had <em>stopped</em> them, which stops the instance charges immediately. What I’d half-forgotten is that <strong>RDS auto-starts a stopped cluster after seven days</strong>. On the morning of day seven, all three quietly turned themselves back on and resumed billing.</p><p>They were deleted for real nine minutes later. But the lesson stuck: <strong>stopped is not deleted</strong>. If you stop something to save money, put its execution date in your calendar, because AWS has already put the resurrection date in theirs.</p><h3>Round two: reading the bill like a document</h3><p>After round one the environment plateaued at ~$90/day for two weeks (I had actual features to ship). The easy 30% is easy. The next 40% came from treating the bill as a text to be read line by line — Cost Explorer grouped by usage type is the closest thing AWS has to a confession.</p><p>Some of what it confessed, the week of July 20th:</p><p><strong>A global database with one member</strong>. The main Aurora cluster was paying <strong>~$10/day in storage I/O</strong> — 425 million reads a day, in an environment where maybe six humans click around. Root cause, three layers down: the cluster was attached to an Aurora <em>Global</em> Database that had exactly one region in it. A global database of one. That membership was the only thing forbidding cheaper Graviton burstable instances and the I/O-Optimized storage tier. Detach the pointless global wrapper → downsize the writer → flip to I/O-Optimized → the $10/day line became <strong>$0.07</strong>. Seven cents.</p><p><strong>The nostalgia tax.</strong> The ingestion database was still on Postgres 13, which had slipped into paid extended support: <strong>$5.86/day, about $180/month, purely for running an old major version.</strong> One rehearsed upgrade to Postgres 15 later, the line is zero. AWS charges rent for nostalgia now. Check your engine versions.</p><p><strong>The bucket with a hoarding problem.</strong> An S3 bucket that stores pipeline output files had versioning enabled with a 30-day retention of old versions. The files are rewritten constantly, so the bucket was 99.6% dead versions — <strong>5.8 terabytes</strong>, growing by <strong>200 GB every day</strong>, of data whose useful lifetime is measured in hours. Here’s the trap: no storage class can save you there. Objects that live three days can’t benefit from any cheaper tier, because every tier has a 30/90/180-day minimum — Intelligent-Tiering never even gets a chance to demote them. The only real lever was version retention: 30 days → 3 days, plus an abort rule for incomplete uploads. Overnight the bucket went from 5.8 TB to ~440 GB and stopped growing.</p><p><strong>The grab bag</strong>. OpenSearch went from two nodes to one (a YELLOW cluster is a perfectly acceptable lifestyle for staging), an ML-powered anomaly-detection service nobody had read a finding from was switched off, Container Insights likewise, one of two NAT gateways retired, and autoscaling ceilings across every ECS service came down to staging-sized numbers, which drained the container fleet from a dozen hosts toward seven.</p><p>By July 25th: <strong>$39/day.</strong> Target met. But I wasn’t done, because two experiments were still open — one that failed, and one that’s my favorite find of the month.</p><h3>The part where I broke it</h3><p>Every host in the ECS fleet boots with a 30 GB root volume and uses about 3 GB of it. Shrinking to 20 GB looked like the most boring, safest win imaginable. I shipped it in the launch template.</p><p>Every single instance launch after that failed:</p><pre>InvalidBlockDeviceMapping — Volume of size 20GB is smaller than snapshot &#39;snap-0ae…&#39;, expect size &gt;= 30GB. Launching EC2 instance failed.</pre><p>The ECS-optimized AMI’s root snapshot is 30 GB, and <strong>EBS will never create a boot volume smaller than its snapshot</strong> — a constraint I’d have told you about confidently in an interview and still walked straight into. The fleet couldn’t scale out or replace a lost spot instance for a weekend: six consecutive failed launches before I caught it Monday morning.</p><p>The fix was the humble kind: revert to 30 GB, and leave a comment on the variable explaining the constraint to the next optimizer (who is statistically me, in six months). The “proper” fix — building and maintaining a custom shrunken AMI — would save $0.22/day. A maintained custom AMI is a pet. $0.22 a day does not feed a pet.</p><p>I’m including this because a cost-cutting story with no failure in it is a story about someone who wasn’t pushing. This one cost nothing precisely <em>because</em> it happened in staging — which is the entire argument for rehearsing there before touching 200 production hosts.</p><h3>Round three: the empty chair</h3><p>The last round, Monday July 27th, was inside the ECS cluster and its autoscaling group — the connoisseur stuff. Three finds:</p><p><strong>We were bin-packing on the wrong dimension.</strong> Every service was configured to binpack tasks by <em>memory</em>. But the workload is CPU-bound: CPU reservation ran at 46% while memory reservation sat at 29%. The result, live and measurable: one host with <strong>0 CPU units free and 6.4 GB of RAM stranded</strong> behind a single CPU-hungry task — a whole instance’s memory, unusable. Hand-packing the same tasks by CPU fit the entire environment on 4 hosts instead of 6. One-line change per service: binpack on cpu.</p><p><strong>The autoscaler was paying for an empty chair.</strong> One host sat permanently idle — zero tasks. Not a bug: the capacity provider’s targetCapacity was 90, which literally means “always keep ~10% of the fleet empty as headroom.” Sensible for production. On staging, where the cost of a cold scale-out is somebody waiting three minutes, it’s a chair nobody sits in. Set to 100.</p><p><strong>Spot shopping without looking at the price tag.</strong> The spot allocation strategy was capacity-optimized, which optimizes for interruption risk and <em>ignores price entirely</em>. It had dutifully parked us on the single most expensive instance type in our own allow-list — $0.0577/hour while near-identical types sat at $0.041–0.051. A 17% premium for nothing, chosen by a strategy doing exactly what it says on the tin. Switched to price-capacity-optimized, fixed the instance-type weights (two xlarge types were counted as equal to a large — a footgun waiting for its moment), and rebuilt the pool around instance families whose memory-per-CPU actually fits the workload. The “cheaper” compute-optimized families turn out to be a trap here: 20% less per hour, less than half the usable memory, so you need more hosts and come out behind. Arithmetic beats instinct.</p><p>Applied at 13:07. At 13:21, ECS looked at the new numbers and <strong>terminated the idle host on its own</strong> — which happened to also be the overpriced spot instance. Two findings closed by one eviction, fourteen minutes after apply. The most satisfying terraform apply is the one where AWS starts deleting things for you.</p><p><strong>Where it started (July 2) → where it ended (July 31)</strong></p><ul><li><strong>Daily cost</strong>: $147 → $36</li><li><strong>Monthly run rate</strong>: ~$4,400 → ~$1,100</li><li>ECS hosts: 12 → 5</li><li>Database instances: 8 → 3 (all Graviton, all current-gen Postgres)</li><li>Cache nodes: 4 × medium → 4 × micro</li><li>OpenSearch: 2 nodes, 100 GB → 1 node, 50 GB</li><li>That S3 bucket: 5.8 TB and growing 200 GB/day → 0.44 TB, flat</li><li>NAT gateways: 2 → 1</li><li>Scheduled downtime used: none → none</li></ul><p>And the part that doesn’t fit in the table: staging was the dress rehearsal. The bin-packing fix, the spot strategy, the capacity-provider tuning — all of it shipped to the ~200-host production fleet days later, pre-validated, where the same levers are worth hundreds of dollars a day. (Production billing has its own plot twists — Savings Plans make some savings invisible on the sub-account invoice while still being real money to the org — but that’s a story for another post.)</p><h3>What I’d tell you over coffee</h3><ul><li><strong>The bill is a document.</strong> Read it. Not the dashboard — the usage types. Every line is a sentence someone’s infrastructure wrote about itself, and some of those sentences are confessions.</li><li><strong>“Temporary” needs a deletion date</strong>, or it’s just “permanent” with better PR.</li><li><strong>Stopped is not deleted</strong>. Some things auto-resurrect. Diary the funeral.</li><li><strong>Defaults are priced for production</strong>. Headroom percentages, monitoring add-ons, version retention, log retention set to <em>forever</em> — each one is a small ongoing decision someone made for you.</li><li><strong>Claim steady state, not coincidence</strong>. Your credibility is worth more than a flattering day-over-day delta.</li><li><strong>Break staging proudly</strong>. A $0 failure that inoculates production is the cheapest education money can buy.</li></ul><p>Total hands-on time across the month: about four working days. The rest was waiting — cost work has a feedback loop measured in billing days, and the discipline is changing one lever per bill line per window, or you’ll never know what actually worked.</p><p>The environment still has no users. But now, at least, it costs like it knows that.</p><p><em>Numbers are real, from Cost Explorer. Names, and nothing else, have been changed.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea01762a4f25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatic and manual Website configuration on AWS]]></title>
            <link>https://medium.com/@sonufrienko/automatic-and-manual-website-configuration-on-aws-af64302af175?source=rss-b3c1df38836------2</link>
            <guid isPermaLink="false">https://medium.com/p/af64302af175</guid>
            <category><![CDATA[website]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-cloudfront]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <dc:creator><![CDATA[Sergii Onufriienko]]></dc:creator>
            <pubDate>Wed, 26 Feb 2020 09:19:44 GMT</pubDate>
            <atom:updated>2020-02-26T09:19:44.955Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPaW1d9Zb_YDunwQnEJs8g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nate_dumlao?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nathan Dumlao</a> on <a href="https://unsplash.com/s/photos/clark-young-fqxmgkyxqfu-unsplash?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>What you’ll learn?</h4><ol><li>How to setup static and dynamic website with AWS S3 and CloudFront</li><li>How to use<strong> AWS CDK</strong> to automate it</li></ol><h4>Website requirements</h4><ul><li>Handle static and dynamic routes (SPA, Create React App, Gatsby, etc.)</li><li>Public access to S3 Bucket should be blocked</li><li>Should use CloudFront</li><li>Compression with Gzip</li><li>Should support HTTP/2 protocol</li></ul><h4>We have two options for origins on CloudFront</h4><ol><li>S3 Bucket — can’t handle dynamic routes (file not exists)</li><li><strong>S3 Buckets Configured as Website Endpoints</strong> (custom origin) — meet our requirements</li></ol><p>More details about these options <a href="https://aws.amazon.com/premiumsupport/knowledge-center/cloudfront-serve-static-website/">here</a>.</p><p>To secure S3 Bucked from public access, we’ll use Referer header. CloudFront will send a request to S3 with this header and the S3 Bucket Policy will validate it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*fhysWaDFVSw3vd59bWJR1w.png" /><figcaption>CloudFront with custom origin (S3 Static Website) and custom header</figcaption></figure><h3>Manual setup</h3><p>1. Let’s create a bucket <strong>react-website-01</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WFFkA8hEiNxO0TTHoAnhtg.png" /></figure><p>Upload files app to S3</p><pre>aws s3 sync build s3://react-website-01 --delete</pre><p>2. Enable <strong>Static Website Hosting</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3qlV_S1hUPo5zxUus9zY5A.png" /></figure><p>3. Set <strong>Index</strong> and <strong>Error document</strong> to index.html</p><p>It allows us to handle dynamic routes. In the Single Page Application, all routes handle by a single index.html page.</p><p>Copy endpoint URL — your Website URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5S2v7cZf7Pr_rL0YJWnBGA.png" /></figure><p>4. Now, let’s create a CloudFront Web Distribution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4EAxSRq4gGGX9RPCLzqgJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rDa7CuR4YrX1CCMUeGvKEw.png" /></figure><ul><li><strong>Origin Domain Name — </strong>paste your Website URL</li><li>Check <strong>Redirect HTTP to HTTPS</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AoYRlOC9O2BCMpzSjOEhEQ.png" /></figure><p>Make sure you enabled HTTP/2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IFEPxmDCRfufDvTNPw_1LQ.png" /></figure><p>Turn on Gzip compression</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5u3XlQkMc6Im3Tss5fyJuQ.png" /></figure><p>Now click — <strong>Create Distribution.</strong></p><p>Go to <strong>Origins and Origin Groups</strong> and click <strong>Edit</strong> on your Origin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzZlJ9OG5sgZX-DX4xG_Pg.png" /></figure><p>Add a custom header which CloudFront will send to our origin</p><p>Name = <strong>Referer</strong></p><p>Value = <em>&lt;any secret key&gt;</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sn1naVY6tCmZQFqfIvntrg.png" /></figure><p>Go to S3 &gt; Your bucket &gt; Permissions &gt; <strong>Bucket Policy</strong></p><p>And paste this policy which allows reading objects from a specific bucket where the request has Referer header equals to this secret key.</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Id&quot;: &quot;Policy1581942769255&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;AllowByRefererHeader&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::&lt;YOUR BUCKET NAME&gt;/*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringEquals&quot;: {<br>                    &quot;aws:Referer&quot;: &quot;&lt;YOUR SECRET KEY&gt;&quot;<br>                }<br>            }<br>        }<br>    ]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBHfNNtMvt5pG3PJXw_6yg.png" /></figure><p>Also, we need to uncheck <strong>Block all public access</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tLS4_YHoRhV99FdCIngerg.png" /></figure><p>Finally, we have a solution for any SPA with dynamic routes or static websites. We use CloudFront and S3 Buckets Configured as Website Endpoints secured by a custom header.</p><p><a href="https://d2z4qluysqj4wh.cloudfront.net/">Gatsby demo</a>.</p><p><a href="https://dmupu59jidl37.cloudfront.net/">Create React App demo</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*l_oYAmFBA6LiZzltc4XB8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*mhgRDgoR0uMbMZPCAIrwOA.png" /><figcaption>Gatsby and Create React App</figcaption></figure><h3>Automation with AWS CDK</h3><p>Now, let’s automate it with AWS CDK. You’ll write code once and can repeat it as much as you need it. You can configure one website or one hundred websites.</p><p>Create an S3 bucket and turn on Static Website</p><pre>const hostingBucket = new s3.Bucket(this, &#39;website&#39;{<br>   websiteIndexDocument: &#39;index.html&#39;,      <br>   websiteErrorDocument: &#39;index.html&#39;    <br>});</pre><p>Here we allow Public Access and create a Bucket Policy.</p><pre>const grant = hostingBucket.grantPublicAccess(&#39;*&#39;, &#39;s3:GetObject&#39;);</pre><pre>grant.resourceStatement!.addResources(hostingBucket.bucketArn);    grant.resourceStatement!.sid = &quot;AllowByRefererHeader&quot;;    grant.resourceStatement!.addCondition(&quot;StringEquals&quot;, {<br>   &quot;aws:Referer&quot;: refererHeaderValue<br>});</pre><p>Now, let’s create a CloudFront distribution.</p><p>Keep in mind that our origin (S3 Static Website) uses HTTP protocol, so we need to set it explicitly.</p><pre>const distribution = new CloudFrontWebDistribution(this, &#39;WebsiteDistribution&#39;, {</pre><pre>  originConfigs: [{<br>    customOriginSource: {<br>      <strong>domainName</strong>: bucketWebsiteDomainName,<br>      <strong>originProtocolPolicy</strong>: OriginProtocolPolicy.HTTP_ONLY<br>    },</pre><pre>    behaviors: [{<br>      <strong>isDefaultBehavior</strong>: true,<br>      <strong>compress</strong>: true<br>    }],</pre><pre>    originHeaders: {<br>      <strong>Referer</strong>: refererHeaderValue<br>    }<br>  }]<br>});</pre><p>That’s it. We automated our infrastructure for the website.</p><p>Source code you can find in my GitHub repository.</p><p><a href="https://github.com/sonufrienko/aws-cdk-static-website">sonufrienko/aws-cdk-static-website</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af64302af175" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitHub Actions with Docker-Compose, Node.js, and MongoDB]]></title>
            <link>https://medium.com/@sonufrienko/github-actions-with-docker-compose-node-js-and-mongodb-d59bf7e20867?source=rss-b3c1df38836------2</link>
            <guid isPermaLink="false">https://medium.com/p/d59bf7e20867</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Sergii Onufriienko]]></dc:creator>
            <pubDate>Sun, 22 Sep 2019 15:30:59 GMT</pubDate>
            <atom:updated>2019-09-22T15:30:59.654Z</atom:updated>
            <content:encoded><![CDATA[<p>I use GitHub Actions for unit tests, but how to run integration tests with MongoDB. Let’s find out.</p><h3>Docker-Compose</h3><ol><li>Let’s create a docker-compose.yml file to connect Node.js and MongoDB containers</li><li>Purpose of this Docker Compose file just to run tests and then exit</li></ol><p>3. To stop MongoDB container when Node.js app exit, we need to use a trick</p><pre>docker-compose up --exit-code-from web</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*yKCnQdi_86u_SahCPdJyxQ.png" /></figure><h3>GitHub Actions</h3><p>Create <strong>.github/workflows/test-integration.yml</strong> file to your repository.</p><p>The last step in this demo will start tests in Docker Compose which connects Node.js and MongoDB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*2xrUxHr0_TfkHUa0MYyQjg.png" /></figure><h3>Conclusion</h3><p>With GitHub Actions, and Docker Compose we can run many scenarios for integration tests. With other microservices, cache layer, load tests, security tests, etc.</p><p>Now our PR is tested and we can merge it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*ik7HZIk6wbytMZZOcGU4jw.png" /></figure><p>You can check source code here.</p><p><a href="https://github.com/sonufrienko/microservice">sonufrienko/microservice</a></p><p>Good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d59bf7e20867" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create AppSync DataLoader]]></title>
            <link>https://medium.com/@sonufrienko/how-to-create-appsync-dataloader-b6b1c5e5178c?source=rss-b3c1df38836------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6b1c5e5178c</guid>
            <category><![CDATA[aws-appsync]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[amplify]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dynamodb]]></category>
            <dc:creator><![CDATA[Sergii Onufriienko]]></dc:creator>
            <pubDate>Thu, 05 Sep 2019 21:07:11 GMT</pubDate>
            <atom:updated>2019-09-05T21:07:11.767Z</atom:updated>
            <content:encoded><![CDATA[<p>I am working on a project with Serverless Architecture using AWS Amplify, AppSync, DynamoDB, Cognito, Lambda, Node.js, React, and React Native.</p><p>Let me show how you can fetch data for GraphQL query with a nested list using AWS AppSync, DynamoDB and Lambda functions.</p><p>When you work with GraphQL server, you can use <a href="https://github.com/graphql/dataloader">DataLoader</a> — utility to reduce requests to the database via batching. But we can’t use it in AppSync. So let’s figure out what batching mechanisms provide AppSync to replace DataLoader.</p><h3>DynamoDB</h3><p>We’ll use one DynamoDB table with one-to-many relationships. Countries and cities stored in a single table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*1Yzunjb5gh0YTFlEJd4ShQ.png" /></figure><h3>AppSync schema</h3><p>For example, I’ll use this GraphQL schema.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*vmYtShrR5PiTZnV-Gf0IyA.png" /></figure><p>The query for countries will invoke a Lambda function which will return countries and an empty array of cities. Source of function is <a href="https://github.com/sonufrienko/demo-appsync/blob/master/amplify/backend/function/listCitiesDemo/src/index.js">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*Sfbd6dM8XZDh-riIn-EWJA.png" /></figure><p>This is our response for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3Nw9-Lf41W9l5N1a1xPkg.png" /></figure><h3>Lambda function for cities</h3><p>Now we need a new Lambda function which will fetch cities by an array of countries. Source of function is <a href="https://github.com/sonufrienko/demo-appsync/blob/master/amplify/backend/function/listCountriesDemo/src/index.js">here</a>. This is what our function will receive as arguments.</p><pre>[<br>  {<br><strong>    &quot;countryID&quot;: &quot;NL&quot;,</strong><br>    &quot;countryName&quot;: &quot;-&quot;,<br>    ...<br>  }, {<br><strong>    &quot;countryID&quot;: &quot;DE&quot;,</strong><br>    &quot;countryName&quot;: &quot;-&quot;,<br>    ...<br>  }, {<br><strong>    &quot;countryID&quot;: &quot;IT&quot;,</strong><br>    &quot;countryName&quot;: &quot;-&quot;,<br>    ...<br>  }<br>]</pre><p>Let’s create a query for cities where countryID is in our array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*YIJS1ZEROCfXZ6X2GlReuA.png" /></figure><p>Please, keep in mind that DynamoDB operator <strong>IN</strong> limited to 100 values, separated by commas. More <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html">here</a>.</p><p>The response should be in the same order as an array of countries.</p><pre>[<br>  [ <strong>// for NL</strong><br>    {<br>      &quot;cityID&quot;: &quot;-&quot;,<br>      &quot;cityName&quot;: &quot;-&quot;<br>    }, {<br>      &quot;cityID&quot;: &quot;-&quot;,<br>      &quot;cityName&quot;: &quot;-&quot;<br>    },<br>  ],<br>  [ <strong>// for DE</strong><br>    {<br>      &quot;cityID&quot;: &quot;-&quot;,<br>      &quot;cityName&quot;: &quot;-&quot;<br>    }, {<br>      &quot;cityID&quot;: &quot;-&quot;,<br>      &quot;cityName&quot;: &quot;-&quot;<br>    },<br>  ],<br>  [ <strong>// for IT</strong><br>    {<br>      &quot;cityID&quot;: &quot;-&quot;,<br>      &quot;cityName&quot;: &quot;-&quot;<br>    }, {<br>      &quot;cityID&quot;: &quot;-&quot;,<br>      &quot;cityName&quot;: &quot;-&quot;<br>    },<br>  ]<br>]</pre><h3>Add a resolver</h3><p>Now we need to use our Lambda function with cities as a resolver for field <strong>cities</strong>. Let’s move to AppSync and create a new Data Source from the Lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F5EZklFXAUK5yIeXEJV2Rw.png" /></figure><p>Let’s found our function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pE-uBay9cQ8NBxMnsy6oSw.png" /></figure><p>Now, let’s open our Schema and attach a Resolver to field <strong>cities</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-1gtPijOic5RFV7KecRdHg.png" /></figure><ol><li>Choose our newly created Data Source</li><li>Select <strong>BatchInvoke and forward arguments</strong></li><li>Set <a href="https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-lambda.html"><strong>Request mapping template</strong></a><strong> </strong>to</li></ol><pre>{<br>    &quot;version&quot; : &quot;2017-02-28&quot;,<br>    &quot;operation&quot;: &quot;BatchInvoke&quot;,<br>    &quot;payload&quot;: $util.toJson($ctx.source)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQVV66T3MjDPwimVPb8CaQ.png" /></figure><p>Let’s check our query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jh-3mlwUgixVRHTcoQpIIQ.png" /></figure><p>Yes, we did it! Now let’s check query with filter. And, yes, it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rUedjehZ-IEg8-LHemO2Kg.png" /></figure><p>AppSync will invoke a Lambda function to fetch cities only when our query has this field. If not, we’ll fetch only countries from the database.</p><p>AWS AppSync is fantastic service. Hope you like it like me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6b1c5e5178c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Node.js app to the Google Kubernetes Engine (GKE)]]></title>
            <link>https://itnext.io/deploying-a-node-js-app-to-the-google-kubernetes-engine-gke-d6af1f3a954c?source=rss-b3c1df38836------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6af1f3a954c</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[gke]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Sergii Onufriienko]]></dc:creator>
            <pubDate>Sat, 29 Jun 2019 21:17:03 GMT</pubDate>
            <atom:updated>2019-07-03T10:11:20.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0H_XuoRSInNqzP14loJuPg.png" /></figure><p>I wanna show you how quickly and easily you can deploy your app to the Kubernetes on Google Kubernetes Engine (GKE).</p><h3>Create a new Kubernetes cluster</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*ARmNlow2g-aRV3T1eicpDA.png" /></figure><p>Enter a name for your cluster, location, number of nodes and machine type. Then click <strong>More Options</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*TEZk_XIZQx6ikjYuGIxN7w.png" /></figure><p>If you need to automatically add new nodes to the cluster, then click <strong>Enable autoscaling</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*vwzY1cFG_NVrpf0YHSF2UA.png" /></figure><p>You can allow access to some APIs from the cluster. For example, I allow access to Google Cloud Storage (GCS).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*Dd1E4gijeqsBGsClTUK7hw.png" /></figure><p>After your cluster has been created, click <strong>Connect</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*64OZtw8uJl9HZLqC4nFqeg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*y1ILYx9xWjD53ljLAUCTLw.png" /></figure><p>Now you’ll see a Cloud Shell with the command, press Enter to execute it and get GKE credentials. After that, you can execute any commands with <strong>kubectl</strong>.</p><p>For example, let’s check the nodes of a cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*ncrqEYHH9hqUi6_9lwMOOA.png" /></figure><h3>Push docker image to Google Container Registry</h3><p>I’ll use my GitHub repo which includes a simple Node.js app, Dockerfile, and deployment.yaml. All these commands I’ll enter in Cloud Shell.</p><pre>git clone <a href="https://github.com/sonufrienko/gke-simple-app">https://github.com/sonufrienko/gke-simple-app</a></pre><pre>cd gke-simple-app</pre><p>Replace [PROJECT_ID] in <strong>deployment.yaml</strong> with your GCP project ID.</p><p>Get credentials to Google Container Registry</p><pre>gcloud auth configure-docker</pre><p>Build and push the docker image to Google Container Registry</p><pre>docker build -t gcr.io/[PROJECT_ID]/app:v1 .<br>docker push gcr.io/[PROJECT_ID]/app:v1</pre><h3>Deploy docker image to Kubernetes</h3><p>Deployment YAML file contains two parts:</p><ul><li>Deployment - describe containers to be deployed</li><li>Service - will create a LoadBalancer to expose our containers to the internet</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*LV8pcGsPKIlmNbqpZEvaJg.png" /></figure><p>Create deployment and service.</p><pre>kubectl apply -f deployment.yaml --record</pre><p>Check deployment process</p><pre>kubectl get deployments</pre><p>Check pods (containers)</p><pre>kubectl get pods</pre><p>Check service and copy external IP address (LoadBalancer)</p><pre>kubectl get services</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*fFD_c3tTOLc0QDk7DRh3bg.png" /></figure><p>Now, you can open in your browser this URL</p><pre>http://&lt;EXTERNAL-IP&gt;/encrypt?secret=abc&amp;message=i-love-you</pre><h3>How to release a new version?</h3><p>Push a new version of docker image to the Container Registry, change docker image version in <strong>deployment.yaml</strong> and then run this command to set desired deployment state.</p><pre>kubectl apply -f deployment.yaml --record</pre><h3>How to rollback new release?</h3><pre>kubectl rollout undo deployment/my-app-deployment</pre><h3>Useful tips</h3><p>Check container logs</p><pre>kubectl logs &lt;POD NAME&gt;</pre><p>Go inside container</p><pre>kubectl exec -it &lt;POD NAME&gt; bash</pre><p>Delete a whole deployment</p><pre>kubectl delete deployment my-app-deployment</pre><p>Set horizontal pod autoscaling policy for deployment</p><pre>kubectl autoscale deployment &lt;DEPLOYMENT_NAME&gt; --max 6 --min 1 --cpu-percent 60</pre><p>Check horizontal pod autoscaling policy (HorizontalPodAutoscaler object)</p><pre>kubectl get hpa</pre><p>Check pod Events to investigate issues with pods deployment, polling docker image, etc.</p><pre>kubectl get pods<br>kubectl describe pods/&lt;POD_NAME&gt;</pre><h3>What’s next?</h3><p>Now you know how to create a GKE cluster, deploy containers, release a new version and rollback, set autoscale policy and how to investigate problems.</p><p>You can also read more about these topics:</p><ol><li>Manage Secrets</li><li>Labels</li><li>Namespace</li><li>Application health check</li><li>other Service types (ClusterIP, NodePort, ExternalName)</li><li>Ingress</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6af1f3a954c" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/deploying-a-node-js-app-to-the-google-kubernetes-engine-gke-d6af1f3a954c">Deploying a Node.js app to the Google Kubernetes Engine (GKE)</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[Scaling Amazon Aurora MySQL]]></title>
            <link>https://medium.com/@sonufrienko/scaling-amazon-aurora-mysql-256c30737822?source=rss-b3c1df38836------2</link>
            <guid isPermaLink="false">https://medium.com/p/256c30737822</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[aws-rds]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aurora]]></category>
            <category><![CDATA[scale]]></category>
            <dc:creator><![CDATA[Sergii Onufriienko]]></dc:creator>
            <pubDate>Thu, 25 Apr 2019 11:19:04 GMT</pubDate>
            <atom:updated>2019-04-25T11:19:04.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RZQrr3TGqMG7PoQi8lQX4g.png" /></figure><p>The goal of this article is to share my experience of how to scale Amazon Aurora MySQL to handle 5M requests per minute on REST API.</p><h3>Query profiling</h3><p>I have an existing database on Amazon Aurora MySQL and REST API application on Amazon ECS (Node.js). My work will be focused on the single most used API endpoint.</p><p>First of all, I need to find all queries which use our app. I’ll do it on the local environment and MySQL on the Docker container.</p><ol><li>Turn on database logs for all queries</li></ol><pre>SET global general_log = 1;</pre><pre>SET global log_output = &#39;table&#39;;</pre><p>2. Send a request to our REST API endpoint</p><pre>curl http://localhost:4000/test-endpoint</pre><p>3. Fetch all queries for the last 60 seconds and filter some noise</p><pre>select argument from mysql.general_log</pre><pre>where  event_time  &gt; (now() - INTERVAL 60 SECOND)</pre><pre>and command_type = &quot;Query&quot;</pre><pre>and argument &lt;&gt; &quot;&quot;</pre><pre>and argument &lt;&gt; &quot;SET NAMES &#39;UTF8&#39;&quot;</pre><pre>and argument &lt;&gt; &quot;SET time_zone = &#39;+00:00&#39;&quot;</pre><pre>and argument &lt;&gt; &quot;SET PROFILING=1&quot;</pre><pre>and argument &lt;&gt; &quot;SHOW STATUS&quot;</pre><pre>and argument NOT LIKE &#39;%general_log%&#39;;</pre><h3>Query optimizations</h3><p>Now I can analyze each query filters and check indexes on the table. Also, I can execute the query in MySQL Workbench and check the execution plan to figure out which indexes we actually use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*bkt7Klycya6Eur3r_KOqfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*bkt7Klycya6Eur3r_KOqfw.png" /><figcaption>How indexes impact insert queries</figcaption></figure><h4>Some tips</h4><ul><li>Update by Primary key where possible.</li><li>Replace couple inserts with <strong>Bulk Inserts</strong> — a single transaction.</li><li>Replace couple selects with a single select and filter data on the <strong>server side</strong>.</li><li>Remove as much write queries as possible. If you can, delay them with a message queue. Write operations will limit your scalability with a single master cluster.</li><li>Use <strong>Stored Procedures</strong> — precompiled (not for MySQL), less data transfer between app and database server, a better place for complex logic, less round trip, more secure, reusable.</li></ul><h3>Upgrade RDS Aurora</h3><p>Once I was needed to change instance type for RDS from db.t2.medium to db.r4.xlarge. But I can’t. Before it, I need to upgrade my Aurora v1.14.1 to a newer version of Aurora (v2.03). The problem was that I can’t upgrade the major version without downtime.</p><p>The only possible solution was to create a new RDS cluster from the snapshot, choose new Aurora version and new instance type. I can’t avoid downtime for 15 min. But in the future, I can change instance type with zero downtime. This was required only for the new major version of Aurora.</p><h3>Connection pool</h3><p>The maximum size of the connection pool plays a critical role. Pool size depends on many factors like instance type (hardware performance) and execution time of queries.</p><p>In my case, the connection pool size was limited by 5 connections. This means that if 5 connections are busy new requests will waiting for a free one. I have increased the connection pool max size to 200. This means that the application can keep up to 200 connections open if necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*G_gXMaRGbNUGG8SuA2v_Hg.png" /><figcaption>How to determine the connection pool size?</figcaption></figure><h3>RDS Read Replicas</h3><p>We can increase the performance of the read queries by adding more Read Replicas. RDS is a single master cluster. We can have only one server to handle write queries and up to 15 (only for Aurora engine) replicas to handle read queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*JgY12xIGRNVFK8Qd18Xn5w.png" /></figure><h3>Sequelize Replication</h3><p>Now we need to configure Sequalize (ORM for Node.js) to split read and write queries. We should send read queries to any read replica and write queries only to our master.</p><p>RDS provides two cluster endpoints. Write — to single master and Read to any Read Replica with round-robin load balancing.</p><p>Sequelize config to use replication</p><pre>replication: {</pre><pre>   read: [{ host: &#39;my-database-ro.rds.amazonaws.com&#39;}],</pre><pre>   write: { host: &#39;my-database.rds.amazonaws.com&#39;}</pre><pre>}</pre><h3>RDS Auto-Scaling</h3><p>Auto-Scaling for RDS means we can create a policy to automatically add more Read Replicas when we need it. But we can’t scale master. So, we can scale read queries to huge values (up to 15 instances) but write queries are limited to the single most powerful instance for master.</p><p>We need to create two Auto Scaling policy:</p><ol><li>Avg CPU = 60% (for example)</li><li>Avg connections = 3500 (4000 max for my instance type)</li></ol><p>Second policy measure connections ONLY over replicas, so you need to have at least 1 replica.</p><h3>Conclusion</h3><ol><li>Find your Connection pool size (bear in mind, RDS have database connection limits depends on instance type but you can change it).</li><li>RDS is a single-master cluster. You can easily scale Read queries by changing the instance type or add more Read Replicas. But Write queries can be scaled only by changing the instance type. So keep in mind that your write queries are limited to the most powerful instance from AWS.</li><li>Use RDS Read Replicas with Sequelize Replication.</li><li>Different microservices has different data storage requirements. For example, some database should be ACID (SQL dbs) and some can be BASE (NoSQL, MongoDB, Cassandra) to be more scaleable.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=256c30737822" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling Node.js microservices on AWS to handle 5M requests per minute]]></title>
            <link>https://medium.com/@sonufrienko/scaling-node-js-microservices-on-aws-to-handle-5m-requests-per-minute-ac02d3d17bab?source=rss-b3c1df38836------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac02d3d17bab</guid>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Sergii Onufriienko]]></dc:creator>
            <pubDate>Fri, 29 Mar 2019 19:28:05 GMT</pubDate>
            <atom:updated>2019-03-29T19:28:05.655Z</atom:updated>
            <content:encoded><![CDATA[<p>The goal of this article is to share my experience of how to scale cloud to handle 5M requests per minute (83K req/sec).</p><h3>Load Testing</h3><p>To find bottlenecks I have used load tests. I did more than 50 tests. Every test was started with minimum resources on the cloud to monitor how it will scale.</p><p>I use <strong>Apache Bench</strong> and <strong>WRK</strong> to load testing and <strong>Ansible</strong> to control bombers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzRJ7Wrtu_BRgymj8vUg4Q.png" /></figure><h4>Metrics</h4><p>Each test I put to the Google Sheet with metrics, changes, and description of bottlenecks. CloudWatch gives every metrics I need.</p><p>ELB/ALB</p><ul><li>HealthyHostCount</li><li>RequestCount</li></ul><p>RDS</p><ul><li>CPUUtilization</li><li>DatabaseConnections</li><li>Queries</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*BHJJt_Egp5h4px2tnUOYSQ.png" /></figure><h3>Microservices on EC2</h3><p>Let’s start with a simple Microservice Architecture on EC2 instances (without ECS). Each microservice placed on a single EC2 instance. ELB and Auto Scale Group was used for load balancing between instances and adding new instances on high load.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GaXVjNIsh_QMdGOj2bkI-Q.png" /></figure><p>In the test, I used 3 Node.js microservices with 3 RDS cluster for each service. Microservice 1 receives all requests, authorize users with Microservice 2 and fetch some data from Microservice 3.</p><p>Here some bottlenecks I have found.</p><h4>Babel — JavaScript compiler</h4><p>Some microservices uses Babel (babel-node) to compile and execute files. It already uses the latest Node.js version which supports everything I need. I just added ESM to leave ES modules.</p><h4>AWS stolen CPU</h4><p>On constant load, CloudWatch shows that CPU load drops from 90% to 40% but Htop shows 100% CPU load. Auto-Scale policy can’t handle it because of the incorrect metric.</p><p>This problem called “AWS stolen CPU”. If your service depends on constant high CPU load you should move away from T2 (CPU Credits and Burstable Performance) to instances like C4 or C5 (Compute Intensive).</p><h4>AWS Limits</h4><p>I was used 657 instances of c4.large type to reach 82.000 req/sec. Then I found this was a limit of a subnet size. The easiest solution is to use a more powerful instance type like c4.4xlarge.</p><h4>Inter-service communication</h4><p>On c4.4xlarge I run Node.js with PM2 cluster mode and 16 processes. But I can’t reach even 40% CPU load.</p><p>Communications between microservices were REST API over HTTP/1.1. The problem was due to the extra overhead caused by the TCP protocol.</p><p>The solution was to use KeepAlive flag and reuse TCP connection for HTTP requests. Also, possible solutions were to use REST over HTTP/2 or gRPC (HTTP/2 under the hood).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*ZRhVwFRQEm-ZqIJ9Z_sBHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*51Ko46uBzjmg5SqLLmu-wQ.png" /></figure><p>I have successfully reached the goal with microservices on EC2. Now let’s try serverless microservices with ECS Fargate.</p><h3>Microservices on ECS Fargate</h3><p>ECS is a container orchestration service managed by AWS. Fargate is a compute engine which allows us to set resources for each service and forget about servers. This is a Serverless Microservices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*BMEerQk31r9FniDxAmYQFw.jpeg" /></figure><p>Example of Serverless Microservice Architecture on ECS Fargate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*03W13si1jM3EG1Qqqt44TQ.png" /></figure><h4>ECS Fargate</h4><p>Pros</p><ul><li>Easy to start with a simple configuration.</li><li>You don’t care about OS, security patch, support, AWS configuration.</li><li>Container Image Repository.</li></ul><p>Cons</p><ul><li>One task (container) is limited to 4 vCPU and 30 GB RAM.</li><li>Lower performance compared to EC2.</li><li>Increasing Fargate limits in our case take a couple of weeks.</li></ul><h4>EC2 vs Fargate performance and const</h4><p>EC2</p><ul><li>82,000 req/sec</li><li>657 c4.large (2 vCPU)</li><li>2 vCPU, 7.5 GB (c4.xlarge), $0.199 per Hour</li></ul><p>Fargate</p><ul><li>58,667 req/sec</li><li>724 tasks (4 vCPU)</li><li>4 vCPU, 8 GB, $0.197 per Hour</li></ul><p>Fargate gives us a serverless microservices but it has a performance penalty and more expensive in comparison to EC2 instance.</p><h3>Conclusion</h3><ul><li>Your AWS VPC subnet should support your future workloads.</li><li>Check your AWS EC2 and Fargate limits up front.</li><li>Enable KeepAlive for all interservice communications (can dramatically increase requests performance).</li><li>Never use Babel for production backend (can add bottlenecks to asynchronous operations and memory leaks).</li><li>Don’t use T2/T3 for CPU intensive tasks.</li><li>Don’t use Nginx in front of microservice — extra layer which you need to properly configure — can slow down your req/sec.</li><li>Use JWT where you can.</li></ul><p>Next time, I will share my experience with database optimizations and scaling MySQL on AWS RDS Aurora.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac02d3d17bab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking performance gRPC vs REST on Node.js]]></title>
            <link>https://medium.com/@sonufrienko/benchmarking-performance-grpc-vs-rest-on-node-js-bf766127f170?source=rss-b3c1df38836------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf766127f170</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[rpc]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Sergii Onufriienko]]></dc:creator>
            <pubDate>Wed, 23 Jan 2019 21:49:34 GMT</pubDate>
            <atom:updated>2019-01-23T21:57:36.436Z</atom:updated>
            <content:encoded><![CDATA[<p>I love REST and JSON for its simplicity. But let’s try something new. Let’s try gRPC and Protobuf for inter-service communication on Node.js.</p><h4>Why use gRPC and Protobuf?</h4><ol><li>PRC</li><li>HTTP/2 for transport</li><li>Streaming (server-side, client-side or bidirectional)</li><li>Deadline propagation</li><li>Auto-generated client for many languages</li><li>Efficient binary serialization</li><li>Strongly typed</li></ol><p>gRPC have features that REST with JSON can’t give you. I have created a simple application with two microservices and gPRC as communication between them.</p><p><a href="https://github.com/sonufrienko/grpc-example">sonufrienko/grpc-example</a></p><p>I really like features what gRPC and Protobuf give us. But what about performance? Let’s test it.</p><h4>How I test</h4><p>I did tests with c5.large AWS instances. I use two instances in the same region and the same AZ. Each instance starts Node.js app in a single process. Service-A (client) sends 1M of sequential requests to the Service-B (server).</p><p>I will measure time to execute 1 million requests by</p><ol><li>REST HTTP1.1 (JSON)</li><li>REST HTTP1.1 + Keep-Alive (JSON)</li><li>gRPC (Protobuf)</li></ol><h4>Source Code</h4><p><a href="https://github.com/sonufrienko/grpc-vs-rest">sonufrienko/grpc-vs-rest</a></p><h4>Results</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*xERz5f0ztNNWMv2gDKoyOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*kgW9w8n1sHZjrJE720Zevg.png" /></figure><h4>Conclusion</h4><p>In my <a href="https://medium.com/@onufrienkos/keep-alive-connection-on-inter-service-http-requests-3f2de73ffa1">previous experimennt</a>, we find that keep-alive requests are very fast. They reuse the connection and save a lot of time and resources.</p><p>So, if you use keep-alive connection you’ll have great performance improvement. Otherwise, you’ll don’t see a huge improvement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf766127f170" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keep-Alive connection on inter-service HTTP requests]]></title>
            <link>https://medium.com/@sonufrienko/keep-alive-connection-on-inter-service-http-requests-3f2de73ffa1?source=rss-b3c1df38836------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f2de73ffa1</guid>
            <category><![CDATA[keep-alive]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[http-request]]></category>
            <dc:creator><![CDATA[Sergii Onufriienko]]></dc:creator>
            <pubDate>Thu, 17 Jan 2019 10:15:41 GMT</pubDate>
            <atom:updated>2019-01-17T10:18:53.639Z</atom:updated>
            <content:encoded><![CDATA[<p>Each HTTP request to the server we’ll 1) open a connection to the server 2) send a request to the server 3) receive data 4) close this connection.</p><p>If we use HTTP request as communication between microservices this can be a bottleneck. Server spends some time and resources to open and close a connection. What if we can use a persistent connection for it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*3OdzTks0sJQI6Owwgm1Vcw.png" /><figcaption>Schema of multiple vs. persistent connection. [wikipedia.org]</figcaption></figure><blockquote><strong>HTTP persistent connection</strong>, also called <strong>HTTP keep-alive</strong>, or <strong>HTTP connection reuse</strong>, is the idea of using a single TCP connection to send and receive multiple HTTP requests/responses, as opposed to opening a new connection for every single request/response pair. The newer HTTP/2 protocol uses the same idea and takes it further to allow multiple concurrent requests/responses to be multiplexed over a single connection. [wikipedia.org]</blockquote><h4>Let’s test it on Node.js</h4><p>I did two tests with small (c5.large — 2 vCPU) and big AWS instances (c5.4xlarge-16 vCPU). I use three instances in the same region and the same AZ.</p><p><strong>Microservice</strong></p><ul><li>Ubuntu Server 18.04 LTS</li><li>Node.js (without Nginx)</li><li>Node v10.15.0 LTS</li><li>PM2</li><li>Express 4.16.4</li></ul><p><strong>Load testing server</strong></p><ul><li>Ubuntu Server 18.04 LTS</li><li><a href="https://github.com/wg/wrk">wrk</a></li></ul><p>I use WRK with 1000 open connections to send GET requests to Service A. Service-A send a request to the Service-B and return JSON data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*HM1geSb53ka0GSbHNMH5Qg.png" /><figcaption>Communication schema</figcaption></figure><h4>Source Code</h4><p><a href="https://github.com/sonufrienko/keepalive-request">sonufrienko/keepalive-request</a></p><h4>Results</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*mWfHYhNivppppf1c__w7yw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*SDHfUMYlA68D7Cab4IPycA.png" /></figure><p>So, by using keep-alive we save resources and speed up requests. Huge difference you’ll see with fast/lightweight requests and powerful servers.</p><p>This is how we can <strong>enable keep-alive in Node.js</strong> for all request with a single line of code.</p><pre>const http = require(‘http’);</pre><pre>http.globalAgent.keepAlive = true;</pre><p>I hope you like this experiment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f2de73ffa1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>