<?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 Ohad Finkelstein on Medium]]></title>
        <description><![CDATA[Stories by Ohad Finkelstein on Medium]]></description>
        <link>https://medium.com/@ohad2712?source=rss-899df3d1f52b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*79cLQ9H4FMy7flQUBaRf0w.jpeg</url>
            <title>Stories by Ohad Finkelstein on Medium</title>
            <link>https://medium.com/@ohad2712?source=rss-899df3d1f52b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:43:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ohad2712/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 I Tracked Down and Fixed a Memory Leak in a Node.js API]]></title>
            <link>https://medium.com/@ohad2712/how-i-tracked-down-and-fixed-a-memory-leak-in-a-node-js-api-4ef63abddd6e?source=rss-899df3d1f52b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ef63abddd6e</guid>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[benchmark]]></category>
            <dc:creator><![CDATA[Ohad Finkelstein]]></dc:creator>
            <pubDate>Thu, 01 Oct 2026 13:25:32 GMT</pubDate>
            <atom:updated>2026-10-01T13:25:32.154Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*RGlvlGaTPRFgSBWec5IUhg.jpeg" /></figure><p>Managing high-throughput Node services usually means dealing with memory quirks sooner or later. Local tests might look clean, but sustained traffic can expose subtle retention issues that slowly push container memory up until Kubernetes restarts the pod.</p><p>On a service handling high-volume API payloads, I ran into a memory leak that didn’t crash the server outright, but steadily dragged down RSS memory under load.</p><p>Here is how I tracked the issue down with heap snapshots, isolated the root cause in V8 memory, and fixed the stream pipeline.</p><p><em>(Note: Code samples below use simplified, anonymized logic to respect NDA and company privacy).</em></p><h3>The issue</h3><p>During peak traffic, container RSS memory started climbing predictably.</p><p>Unlike a sudden burst that clears up after a garbage collection run, this memory growth stuck around:</p><ul><li>RSS grew by about 15 to 20 MB every hour under steady traffic.</li><li>V8 garbage collection ran as expected, but baseline heap usage never dropped back down.</li><li>After roughly 12 hours, the container hit its 512 MB memory limit and restarted.</li></ul><h3>Taking heap snapshots</h3><p>To confirm whether this was an issue in a native module or uncollected V8 heap memory, I added a quick debugging route to write heap snapshots straight to disk:</p><pre>import v8 from &#39;node:v8&#39;;<br>import fs from &#39;node:fs&#39;;<br><br>app.get(&#39;/admin/heap-snapshot&#39;, (req, res) =&gt; {<br>  const fileName = `/tmp/heap-${Date.now()}.heapsnapshot`;<br>  const stream = v8.getHeapSnapshot();<br>  const writeStream = fs.createWriteStream(fileName);<br>  <br>  stream.pipe(writeStream);<br>  writeStream.on(&#39;finish&#39;, () =&gt; {<br>    res.json({ status: &#39;created&#39;, path: fileName });<br>  });<br>});</pre><p>I generated one snapshot at startup and a second snapshot 15 minutes into a load test, then compared both in Chrome DevTools (inspect or F12).</p><p>The memory diff showed thousands of Buffer and Uint8Array instances pinned in memory through an active closure scope.</p><h3>Locating the leak</h3><p>The issue came from custom logging middleware attached to incoming request streams.</p><p>Here is a simplified view of the problematic code:</p><pre>const requestLogCache = new Set();<br><br>export function proxyMiddleware(req, res, next) {<br>  const chunks = [];<br><br>  req.on(&#39;data&#39;, (chunk) =&gt; {<br>    chunks.push(chunk);<br>  });<br>  <br>  req.on(&#39;end&#39;, () =&gt; {<br>    // Pushing &#39;chunks&#39; into a outer scope kept V8 from collecting the underlying buffers<br>    requestLogCache.add({<br>      timestamp: Date.now(),<br>      payload: chunks,<br>    });<br><br>    next();<br>  });<br>}</pre><p>Because requestLogCache retained references to chunks, V8 could not mark the underlying ArrayBuffer allocations for garbage collection. Every incoming request pinned more memory to the heap.</p><h3>Fixing the stream pipeline</h3><p>I replaced the manual buffer aggregation with Node’s built-in stream/promises and pipeline utilities. This processes incoming data on the fly and lets Node handle stream destruction automatically when the request completes.</p><pre>import { pipeline } from &#39;node:stream/promises&#39;;<br>import { Transform } from &#39;node:stream&#39;;<br><br>export async function optimizedProxyHandler(req, res) {<br>  const metricsTransform = new Transform({<br>    transform(chunk, encoding, callback) {<br>      this.bytesProcessed = (this.bytesProcessed || 0) + chunk.length;<br>      <br>      callback(null, chunk);<br>    }<br>  });<br><br>  try {<br>    await pipeline(<br>      req,<br>      metricsTransform,<br>      res<br>    );<br>  } catch (err) {<br>    console.error(&#39;Stream pipeline error:&#39;, err);<br>    res.statusCode = 500;<br>    res.end(&#39;Proxy Error&#39;);<br>  }<br>}</pre><h3>Load test results</h3><p>I ran a benchmark with autocannon (50 persistent connections, 10,000 requests, 10KB payloads) against both implementations to verify the fix.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/305872c55cede606db114f7a103643d5/href">https://medium.com/media/305872c55cede606db114f7a103643d5/href</a></iframe><h3>What the numbers mean</h3><p>1. <strong>At first glance, </strong><strong>/leak appears faster</strong> simply because it buffers payload chunks in memory without piping them to the response.<br>2. <strong>Process RSS inflated to ~1.98 GB in 10 seconds</strong>, which would trigger an instant OOM kill in a 512 MB Kubernetes pod.<br>3. <strong>Heap memory stayed stranded at 122.8 MB</strong> after stopping traffic on /leak, whereas the streaming /fixed handler dropped straight back to 40.4 MB after GC ran.</p><h3>Code reproduction</h3><p>I put together a runnable script on GitHub to reproduce the leak and test both server implementations locally:</p><p><a href="https://github.com/ohad2712/node-memory-leak-benchmark">https://github.com/ohad2712/node-memory-leak-benchmark</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ef63abddd6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hono vs. Fastify on NodeJS (2026): Performance, Developer Experience, and Architecture Benchmark]]></title>
            <link>https://medium.com/@ohad2712/hono-vs-fastify-on-nodejs-2026-performance-developer-experience-and-architecture-benchmark-278edc46a733?source=rss-899df3d1f52b------2</link>
            <guid isPermaLink="false">https://medium.com/p/278edc46a733</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[hono]]></category>
            <category><![CDATA[fastify]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ohad Finkelstein]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 18:22:34 GMT</pubDate>
            <atom:updated>2026-09-27T18:22:34.743Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*mePXQVXhIxo1C59sIz1t3Q.jpeg" /></figure><p><a href="https://fastify.dev/"><strong>Fastify</strong></a> has been my default choice for NodeJS microservices for years. But with <a href="https://hono.dev/"><strong>Hono</strong></a> gaining traction beyond edge runtimes, I wanted to see if @hono/node-server is ready to replace Fastify for traditional Node deployments, specifically for high-concurrency API proxies and web scraping pipelines.</p><p>Fastify earned its reputation through its radix-tree router (<a href="https://github.com/delvedor/find-my-way">find-my-way</a>) and <a href="https://github.com/fastify/fast-json-stringify">fast-json-stringify</a> integration. Hono, on the other hand, was built from the ground up on Web Standards for runtimes like <a href="https://www.cloudflare.com/products/workers/">Cloudflare Workers</a> and <a href="https://bun.com/">Bun</a>. Bringing Hono to NodeJS requires an adapter layer, which historically meant performance tradeoffs.</p><p>To see where things stand today, I benchmarked <strong>Fastify v5 (v6 is currently in Alpha) </strong>and <strong>Hono v4</strong> on NodeJS LTS using <a href="https://github.com/mcollina/autocannon">autocannon</a>. I looked at raw throughput (req/sec), tail latency (p99), memory behavior, and streaming performance under load.</p><h3>Key Differences at a Glance</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65b413fee6f7f33b60cf8d806f1ee7de/href">https://medium.com/media/65b413fee6f7f33b60cf8d806f1ee7de/href</a></iframe><h3>Benchmark Setup &amp; Methodology</h3><p>To mirror real-world proxy and scraping workloads, I tested both frameworks under identical concurrency limits across two routes:</p><ol><li><strong>Standard JSON Route (</strong><strong>/api/search):</strong> Serving a standard structured payload.</li><li><strong>Response Stream Route (</strong><strong>/api/stream):</strong> Pushing chunked response payloads (simulating scrapers, data pipelines, and LLM output streams).</li></ol><h3>Environment Specs</h3><ul><li><strong>NodeJS Version:</strong> v26.x</li><li><strong>Benchmarking Tool:</strong> <a href="https://github.com/mcollina/autocannon">autocannon</a></li><li><strong>Concurrency:</strong> 100 concurrent connections</li><li><strong>Test Duration:</strong> 10 seconds per framework</li><li><strong>Pipelining:</strong> 1</li></ul><h3>Test Environment Code Snippet</h3><p>Both servers were instantiated in a single runner script executing isolated benchmark rounds:</p><pre>// Fastify Routes<br>fastify.get(&#39;/api/search&#39;, async (req, reply) =&gt; {<br>  return {<br>    status: &#39;success&#39;,<br>    timestamp: Date.now(),<br>    results: [<br>      { id: 1, title: &#39;NodeJS Performance Optimization&#39;, category: &#39;Engineering&#39; },<br>      { id: 2, title: &#39;Hono vs Fastify Benchmark&#39;, category: &#39;APIs&#39; }<br>    ]<br>  };<br>});<br><br>fastify.get(&#39;/api/stream&#39;, (req, reply) =&gt; {<br>  reply.raw.writeHead(200, {<br>    &#39;Content-Type&#39;: &#39;text/plain; charset=utf-8&#39;,<br>    &#39;Transfer-Encoding&#39;: &#39;chunked&#39;<br>  });<br>  reply.raw.write(&#39;Initializing streaming pipeline...\n&#39;);<br>  reply.raw.write(&#39;Chunk 1: Data extraction processing\n&#39;);<br>  reply.raw.write(&#39;Chunk 2: Stream complete\n&#39;);<br>  reply.raw.end();<br>});<br><br>// Hono Routes<br>app.get(&#39;/api/search&#39;, (c) =&gt; {<br>  return c.json({<br>    status: &#39;success&#39;,<br>    timestamp: Date.now(),<br>    results: [<br>      { id: 1, title: &#39;NodeJS Performance Optimization&#39;, category: &#39;Engineering&#39; },<br>      { id: 2, title: &#39;Hono vs Fastify Benchmark&#39;, category: &#39;APIs&#39; }<br>    ]<br>  });<br>});<br><br>app.get(&#39;/api/stream&#39;, (c) =&gt; {<br>  return streamText(c, async (stream) =&gt; {<br>    await stream.writeln(&#39;Initializing streaming pipeline...&#39;);<br>    await stream.writeln(&#39;Chunk 1: Data extraction processing&#39;);<br>    await stream.writeln(&#39;Chunk 2: Stream complete&#39;);<br>  });<br>});</pre><h3>Benchmark Results: Performance Comparison</h3><blockquote>Note: The data below reflects empirical test runs executed under synthetic local load.</blockquote><p>Below are the empirical metrics generated by autocannon across both JSON and streaming workloads:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27d9240e6d7aa8896bbc1288d6ee1b63/href">https://medium.com/media/27d9240e6d7aa8896bbc1288d6ee1b63/href</a></iframe><h3>Architectural Deep Dive</h3><h3>1. JSON Routing is a Wash</h3><p>For standard REST endpoints, Hono runs at <strong>~99.2%</strong> of Fastify’s speed (16,088 vs. 16,207 RPS) with identical p99 latency (8.00 ms).</p><p>Historically, converting Node’s native <a href="https://www.w3schools.com/nodejs/obj_http_incomingmessage.asp">http.IncomingMessage</a> and <a href="https://www.w3schools.com/nodejs/obj_http_serverresponse.asp">http.ServerResponse</a> objects into <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">Fetch API</a> <a href="https://developer.mozilla.org/en-US/docs/Web/API/Request">Request</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/Response">Response</a> instances caused heavy garbage collection spikes. <br>Recent V8 and Node runtime optimizations have effectively eliminated this penalty for basic JSON responses.</p><h3>2. Streaming Reveals the Abstraction Tax</h3><p>If you build LLM proxies or scrapers that stream data back over chunked HTTP, this gap matters. Fastify handles streaming nearly twice as fast as Hono (14,988 vs. 8,075 RPS) with half the p99 latency (8.00 ms vs. 20.00 ms).</p><ul><li><strong>Fastify’s approach:</strong> Bypasses framework abstractions and writes directly to Node’s native socket via reply.raw.write().</li><li><strong>Hono’s tradeoff:</strong> Uses Web Standard <a href="https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream">ReadableStream</a> primitives (streamText). Under <a href="https://github.com/honojs/node-server">@hono/node-server</a>, these streams are adapted to Node’s writable streams on the fly, adding microtask queuing and object allocations per chunk.</li></ul><h3>Real-World Workload Considerations</h3><ul><li><strong>Massive Payloads:</strong> Fastify’s schema pre-compilation (<a href="https://github.com/fastify/fast-json-stringify">fast-json-stringify</a>) still wins when serializing huge HTML parse trees or large API responses, saving significant CPU during serialization.</li><li><strong>Stream Heavy Services:</strong> For SSE or high-frequency chunked proxies running on Node containers, Fastify’s direct socket access keeps tail latencies flat under load.</li><li><strong>Edge &amp; Micro-Services:</strong> Hono’s lower idle footprint (~18 MB RSS) and instant cold starts (~12 ms) make it much cheaper to run in serverless or container-per-tenant architectures.</li></ul><h3>Developer Experience &amp; Type Safety</h3><p>Raw speed aside, DX is usually where frameworks win or lose in team settings.</p><ul><li><strong>End-to-End Type Safety:</strong> Hono’s <a href="https://github.com/honojs/hc">hc (Hono Client)</a> RPC model lets frontend code or client SDKs import server route types directly. You get full type safety on requests and responses without generating OpenAPI specs or running code generators.</li><li><strong>Portability:</strong> The exact same Hono route handler runs on NodeJS, A<a href="https://aws.amazon.com/lambda/">WS Lambda</a>, <a href="https://www.cloudflare.com/products/workers/">Cloudflare Workers</a>, or <a href="https://bun.com/">Bun</a> without changing a single line of code.</li><li><strong>Ecosystem Maturity:</strong> Fastify’s plugin encapsulation model (<a href="https://github.com/fastify/fastify-cors">@fastify/cors</a>, <a href="https://github.com/fastify/fastify-jwt">@fastify/jwt</a>, <a href="https://github.com/fastify/fastify-swagger">@fastify/swagger</a>) remains unmatched for large monoliths or complex enterprise setups where scope isolation is critical.</li></ul><h3>My Production Recommendation</h3><p>If I’m building a dedicated NodeJS service focused on raw throughput, heavy data streaming, or complex JSON schemas, I’m sticking with <strong>Fastify</strong>.</p><p>However, for greenfield microservices, proxy layers that require end-to-end TypeScript RPC without build steps, or services designed to run across hybrid runtimes (NodeJS, <a href="https://www.cloudflare.com/products/workers/">Cloudflare Workers</a>, <a href="https://vercel.com/">Vercel</a> or <a href="https://bun.com/">Bun</a>), <strong>Hono is now a completely production-ready choice on NodeJS</strong>.</p><h3>Reproduction</h3><p>To run these benchmarks locally and inspect the raw output:</p><pre>git clone https://github.com/ohad2712/api-benchmark<br>cd api-benchmark<br>npm install<br>npm start</pre><p><em>The script runs both benchmarks sequentially and dumps raw metrics to </em><em>benchmark-results.json.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=278edc46a733" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Simple Design Patterns You Should Know (And Use)]]></title>
            <link>https://medium.com/@ohad2712/3-simple-design-patterns-you-should-know-and-use-node-js-929c8c51c1a1?source=rss-899df3d1f52b------2</link>
            <guid isPermaLink="false">https://medium.com/p/929c8c51c1a1</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ohad Finkelstein]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 17:50:58 GMT</pubDate>
            <atom:updated>2025-08-11T17:54:28.905Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*BBZpD3-o-9XVvpudJ4R_5w@2x.jpeg" /></figure><h4>Enhance your code’s reusability, scalability and maintainability, and become a much better engineer using three simple but powerful design patterns</h4><p>In this article, we’ll explore three of my go-to design patterns, when dealing with <strong>real world problems</strong>, and provide simple implementations for them using TypeScript (and ECAMScript 6).</p><h3>What are Design Patterns?</h3><p>Design patterns are tried and tested solutions to recurring software design problems. They provide a common language for developers, making code more readable and maintainable. Using design patterns in Node.js applications can help you avoid common pitfalls, improve code quality, and make your codebase more robust.</p><h3>What’s in it for me?</h3><p>Easy! It makes your code better. It becomes more maintainable and readable.</p><blockquote>“The wheel has already been invented. Why not use it?”, everyone (duh)</blockquote><p>Now let’s dive into some of my favorite and useful design patterns and their implementations, from my experience.</p><h3>1. Singleton Pattern</h3><p>The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It’s often used for creating shared resources, such as configuration managers.</p><h4>Implementation in TypeScript (two versions):</h4><pre>// First version - Similar to other languages<br>export class Singleton {<br>    // Holds the single instance — initialized lazily.<br>    private static instance?: Singleton;<br><br>    // Prevent external instantiation and subclassing.<br>    private constructor() {<br>        Object.freeze(this); // Optional: this makes the instance immutable<br>    }<br><br>    /**<br>     * Returns the single Singleton instance, creating it if necessary.<br>     */<br>    public static getInstance(): Singleton {<br>        if (!Singleton.instance) {<br>            Singleton.instance = new Singleton();<br>        }<br><br>        return Singleton.instance;<br>    }<br><br>    public doSomething(): void {<br>        console.log(&quot;Singleton is doing something.&quot;);<br>    }<br>}<br><br><br>// --- Usage Example ---  <br>const s1 = Singleton.getInstance();<br>const s2 = Singleton.getInstance();<br>console.log(s1 === s2); // true<br><br>// =================================================<br><br>// Second version - Safest and tree-shake-friendly version <br>// to literally disable the creation of another instance<br><br>// singleton.ts<br>class Singleton {<br>    private constructor() {}<br><br>    public doSomething(): void {<br>        console.log(&quot;Singleton is doing something.&quot;);<br>    }<br>}<br><br>export const singleton = Object.freeze(new Singleton());<br><br>// main.ts<br>// --- Usage Example ---<br>import { singleton } from &#39;./singleton&#39;;<br><br>const sA = singleton;<br>const sB = singleton;<br><br>console.log(sA === sB); // true</pre><h4>Implementation in ECMAScript 6:</h4><pre>class Singleton {<br>    static #instance; // Using a static #privateField to hide the instance<br><br>    constructor() {<br>        if (Singleton.#instance) {<br>            return Singleton.#instance;<br>        }<br>        Singleton.#instance = this;<br>    }<br><br>    doSomething() {<br>        console.log(&quot;Singleton is doing something.&quot;);<br>    }<br>}<br><br>// --- Usage Example ---<br>const s1 = new Singleton();<br>const s2 = new Singleton();<br>console.log(s1 === s2); // true</pre><h3>2. Factory Pattern</h3><p>The Factory pattern provides an interface for creating objects while allowing subclasses to alter the type of objects created. It promotes loose coupling and flexibility in object creation.</p><h4>Implementation in TypeScript:</h4><pre>/**<br> * The Product interface declares the operations<br> * that all concrete products must implement.<br> */<br>interface Product {<br>    operation(): string;<br>}<br><br>/**<br> * ConcreteProductA provides a specific implementation<br> * of the Product interface.<br> */<br>class ConcreteProductA implements Product {<br>    public operation(): string {<br>        return &quot;Product A is created.&quot;;<br>    }<br>}<br><br>/**<br> * ConcreteProductB provides a different implementation<br> * of the Product interface.<br> */<br>class ConcreteProductB implements Product {<br>    public operation(): string {<br>        return &quot;Product B is created.&quot;;<br>    }<br>}<br><br>// =================================================<br><br>/**<br> * The Creator class declares the factory method that returns<br> * objects of the Product type. Subclasses override this method<br> * to create different types of products.<br> */<br>abstract class Creator {<br>    /**<br>     * Factory Method — creates and returns a product instance.<br>     * Subclasses will override this to return specific products.<br>     */<br>    public abstract factoryMethod(): Product;<br><br>    /**<br>     * A helper method that uses the product returned by factoryMethod.<br>     * Demonstrates how Creator can work with any Product without<br>     * knowing its concrete class.<br>     */<br>    public someOperation(): string {<br>        const product = this.factoryMethod();<br>        return `Creator: Working with -&gt; ${product.operation()}`;<br>    }<br>}<br><br>/**<br> * ConcreteCreatorA overrides the factory method to produce Product A.<br> */<br>class ConcreteCreatorA extends Creator {<br>    public factoryMethod(): Product {<br>        return new ConcreteProductA();<br>    }<br>}<br><br>/**<br> * ConcreteCreatorB overrides the factory method to produce Product B.<br> */<br>class ConcreteCreatorB extends Creator {<br>    public factoryMethod(): Product {<br>        return new ConcreteProductB();<br>    }<br>}<br><br><br>// --- Usage Example ---<br>function clientCode(creator: Creator) {<br>    console.log(creator.someOperation());<br>}<br><br>console.log(&quot;Using ConcreteCreatorA:&quot;);<br>clientCode(new ConcreteCreatorA());<br><br>console.log(&quot;Using ConcreteCreatorB:&quot;);<br>clientCode(new ConcreteCreatorB());</pre><h4>Implementation in ECMAScript 6:</h4><pre>class Product {<br>    operation() {<br>        throw new Error(&quot;Method &#39;operation()&#39; must be implemented.&quot;);<br>    }<br>}<br><br>class ConcreteProductA extends Product {<br>    operation() {<br>        return &quot;Product A is created.&quot;;<br>    }<br>}<br><br>class ConcreteProductB extends Product {<br>    operation() {<br>        return &quot;Product B is created.&quot;;<br>    }<br>}<br><br>// =================================================<br><br>class Creator {<br>    factoryMethod() {<br>        throw new Error(&quot;Method &#39;factoryMethod()&#39; must be implemented.&quot;);<br>    }<br><br>    someOperation() {<br>        const product = this.factoryMethod();<br>        return `Creator: Working with -&gt; ${product.operation()}`;<br>    }<br>}<br><br>class ConcreteCreatorA extends Creator {<br>    factoryMethod() {<br>        return new ConcreteProductA();<br>    }<br>}<br><br>class ConcreteCreatorB extends Creator {<br>    factoryMethod() {<br>        return new ConcreteProductB();<br>    }<br>}<br><br>// --- Usage Example ---<br>function clientCode(creator) {<br>    console.log(creator.someOperation());<br>}<br><br>console.log(&quot;Using ConcreteCreatorA:&quot;);<br>clientCode(new ConcreteCreatorA());<br><br>console.log(&quot;Using ConcreteCreatorB:&quot;);<br>clientCode(new ConcreteCreatorB());</pre><h3>3. Observer Pattern</h3><p>The Observer pattern defines a one-to-many dependency between objects. When one object changes state, all its dependents are notified and updated automatically. This is useful for building event-driven systems.</p><h4>Implementation in TypeScript:</h4><pre>/**<br> * The Observer interface declares the update method that all<br> * concrete observers must implement to receive notifications.<br> */<br>interface Observer {<br>    update(message: string): void;<br>}<br><br>/**<br> * A Concrete Observer reacts to updates from the Subject.<br> */<br>class ConcreteObserver implements Observer {<br>    private id: number;<br><br>    constructor(id: number) {<br>        this.id = id;<br>    }<br><br>    public update(message: string): void {<br>        console.log(`Observer ${this.id} received message: ${message}`);<br>    }<br>}<br><br>/**<br> * The Subject (or Publisher) maintains a list of observers<br> * and notifies them of any state changes.<br> */<br>class Subject {<br>    private observers: Observer[] = [];<br><br>    /**<br>     * Attach a new observer to the subject.<br>     */<br>    public attach(observer: Observer): void {<br>        this.observers.push(observer);<br>    }<br><br>    /**<br>     * Detach an existing observer from the subject.<br>     */<br>    public detach(observer: Observer): void {<br>        this.observers = this.observers.filter(obs =&gt; obs !== observer);<br>    }<br><br>    /**<br>     * Notify all observers about an event or state change.<br>     */<br>    public notify(message: string): void {<br>        for (const observer of this.observers) {<br>            observer.update(message);<br>        }<br>    }<br>}<br><br><br>// --- Usage Example ---<br>const subject = new Subject();<br><br>const observer1 = new ConcreteObserver(1);<br>const observer2 = new ConcreteObserver(2);<br><br>subject.attach(observer1);<br>subject.attach(observer2);<br><br>subject.notify(&quot;Hello, Observers!&quot;); <br>// Observer 1 received message: Hello, Observers!<br>// Observer 2 received message: Hello, Observers!<br><br>subject.detach(observer1);<br>subject.notify(&quot;Only Observer 2 should get this&quot;);<br>// Observer 2 received message: Only Observer 2 should get this</pre><h4>Implementation in ECMAScript 6:</h4><pre>class Observer {<br>    update(message) {<br>        throw new Error(&quot;Method &#39;update()&#39; must be implemented.&quot;);<br>    }<br>}<br><br>class ConcreteObserver extends Observer {<br>    constructor(id) {<br>        super();<br>        this.id = id;<br>    }<br><br>    update(message) {<br>        console.log(`Observer ${this.id} received message: ${message}`);<br>    }<br>}<br><br>class Subject {<br>    constructor() {<br>        this.observers = [];<br>    }<br><br>    attach(observer) {<br>        this.observers.push(observer);<br>    }<br><br>    detach(observer) {<br>        this.observers = this.observers.filter(obs =&gt; obs !== observer);<br>    }<br><br>    notify(message) {<br>        for (const observer of this.observers) {<br>            observer.update(message);<br>        }<br>    }<br>}<br><br>// --- Usage Example ---<br>const subject = new Subject();<br><br>const observer1 = new ConcreteObserver(1);<br>const observer2 = new ConcreteObserver(2);<br><br>subject.attach(observer1);<br>subject.attach(observer2);<br><br>subject.notify(&quot;Hello, Observers!&quot;);<br>subject.detach(observer1);<br>subject.notify(&quot;Only Observer 2 should get this&quot;);</pre><h3>Conclusion</h3><p>Design patterns play a crucial role in building robust and maintainable Node.js applications. They provide well-established solutions to common problems, making it easier for developers to understand and enhance the codebase. <br>In this article, we’ve explored the Singleton, Factory, and Observer patterns and provided implementations using TypeScript and ECMAScript 6. <br>By incorporating these patterns into your Node.js projects, you can write more organized and scalable code, ultimately leading to more efficient and maintainable applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=929c8c51c1a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The story of how Ahab and Moby-Dick worked together (for you)]]></title>
            <link>https://medium.com/@ohad2712/the-story-of-how-ahab-and-moby-dick-worked-together-for-you-060dae7382b4?source=rss-899df3d1f52b------2</link>
            <guid isPermaLink="false">https://medium.com/p/060dae7382b4</guid>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[Ohad Finkelstein]]></dc:creator>
            <pubDate>Sun, 11 Aug 2024 01:47:43 GMT</pubDate>
            <atom:updated>2024-08-11T01:47:43.324Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*V_wMP_Z-o7y1IBB0eDxZXA.png" /></figure><h4>Kubernetes and Docker are your great friends to help making your Node.js app scalable</h4><p>In the ever-evolving ocean of web development, you’re the captain of your ship, steering your Node.js application toward success. But as your app gains momentum, you might find yourself facing the enormous challenge of <strong>scalability</strong>. <br>Enter Docker and Kubernetes, the dynamic duo akin to Captain Ahab and the mighty Moby-Dick — working together to make your Node.js app not only survive but thrive in the vast programming sea.</p><h3>Why Scaling Matters?</h3><p>Before we dive into the technical depths, let’s understand why scaling is crucial for your Node.js applications:</p><p>1. <strong>Rising Tide of Traffic</strong>: As your app gains popularity, the waves of user traffic will inevitably rise. Scaling ensures your app can ride these waves without sinking under the pressure of downtime or performance issues.</p><p>2. <strong>Resource Optimization</strong>: Scaling allows you to allocate resources efficiently, ensuring that you’re not over-provisioning or under-utilizing the infrastructure at your disposal.</p><p>3. <strong>Enhanced Reliability</strong>: By distributing workloads across multiple containers and nodes, your application becomes more reliable, with failover mechanisms in place to handle unexpected failures.</p><h3>Setting Sail with Docker: Containerizing Your Node.js Application</h3><p>Docker is your trusty harpoon, helping you capture and package your application into isolated, portable containers. This approach ensures consistency across different environments, whether you’re testing in a local harbor or deploying in the wild ocean of production.</p><h4>Step 1: Dockerizing Your Node.js App</h4><p>Let’s assume you have a Node.js application named “AhabApp.” Here’s how you create a Dockerfile to containerize it:</p><pre># Dockerfile<br><br># Use the latest Node.js LTS version as the base image<br>FROM node:22-alpine<br><br># Set the working directory inside the container<br>WORKDIR /usr/src/app<br><br># Copy package.json and package-lock.json<br>COPY package*.json ./<br><br># Install dependencies with a production flag to optimize the image size<br>RUN npm install - production<br><br># Copy the rest of the application source code<br>COPY . .<br><br># Expose the port your application will use<br>EXPOSE 4000<br><br># Define the command to start your application<br>CMD [&quot;node&quot;, &quot;index.js&quot;]</pre><p>This Dockerfile uses the latest Node.js LTS version and the lightweight Alpine Linux distribution to keep the image slim and efficient. It installs only production dependencies, making the container faster and more secure.</p><h4>Step 2: Building the Docker Image<br>With your Dockerfile ready, you can build the Docker image:</h4><pre>docker build -t ahab-app .</pre><p>This command creates an image named “ahab-app,” which is your application encapsulated with all its dependencies.</p><h4>Step 3: Running Your Dockerized Node.js App</h4><p>To set sail, launch a container from the image you just built:</p><pre>docker run -p 4000:4000 ahab-app</pre><p>Your Node.js app is now running inside a Docker container, accessible on port 4000. It’s a self-contained ship, ready to navigate any environment.</p><h3>Enter Kubernetes: The Orchestrator of Your Fleet</h3><p>While Docker gives you the ability to containerize your application, Kubernetes is the admiral that orchestrates your fleet of containers. Kubernetes manages the deployment, scaling, and operation of your app, ensuring smooth sailing even in stormy seas.</p><h4>Step 1: Installing and Configuring Kubernetes</h4><p>To get started with Kubernetes, follow the <a href="https://kubernetes.io/docs/home/">official Kubernetes documentation</a> to install and configure Kubernetes on your platform of choice.</p><h4>Step 2: Defining Your Kubernetes Deployment</h4><p>Create a Kubernetes deployment file (e.g., <em>ahab-app-deployment.yaml</em>) to define how your Node.js application should be deployed across the Kubernetes fleet:</p><pre># ahab-app-deployment.yaml<br><br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br> name: ahab-app-deployment<br>spec:<br> replicas: 3 # Number of copies (replicas) of your application<br> selector:<br> matchLabels:<br> app: ahab-app<br> template:<br> metadata:<br> labels:<br> app: ahab-app<br> spec:<br> containers:<br> - name: ahab-app-container<br> image: ahab-app:latest<br> ports:<br> - containerPort: 4000</pre><p>This YAML file instructs Kubernetes to deploy three replicas of your application, ensuring redundancy and load balancing.</p><h4>Step 3: Deploying Your Application</h4><p>Deploy your application to Kubernetes using the following command:</p><pre>kubectl apply -f ahab-app-deployment.yaml</pre><p>Kubernetes will ensure that three replicas of your Node.js app are running, and will distribute incoming traffic across them, providing reliability and scalability.</p><h3>Scaling Your Node.js App: Adding More Ships to the Fleet</h3><p>As your app continues to grow, you may need to scale it up to handle more traffic. Scaling your app with Kubernetes is as simple as adjusting the number of replicas:</p><pre>kubectl scale deployment ahab-app-deployment - replicas=5</pre><p>With this command, Kubernetes will deploy additional replicas, increasing your app’s capacity to handle incoming requests. It’s like adding more ships to your fleet to tackle the rising tide of users.</p><h3>Conclusion: Navigating the Digital Seas with Confidence</h3><p>In the story of Ahab and Moby-Dick, the pursuit was fraught with challenges, but with Docker and Kubernetes at your side, you’re equipped to navigate the complex waters of scalability with confidence.</p><p>By containerizing your Node.js app with Docker and orchestrating it with Kubernetes, you can handle increased traffic, optimize resource usage, and ensure your app remains reliable and performant.</p><p>So, set sail with Docker and Kubernetes, and watch your Node.js application conquer the digital seas. Happy coding, and may your app scale to new heights with ease!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=060dae7382b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moving from JavaScript/TypeScript to Python?]]></title>
            <link>https://medium.com/@ohad2712/moving-from-javascript-typescript-to-python-f4a982328d1b?source=rss-899df3d1f52b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4a982328d1b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Ohad Finkelstein]]></dc:creator>
            <pubDate>Wed, 08 May 2024 16:32:02 GMT</pubDate>
            <atom:updated>2024-05-08T16:32:02.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*LRiNWwJUA4Jzky1Cd1TYGQ.jpeg" /></figure><h4>Top hidden differences you should know to avoid unwanted mistakes</h4><p>Transitioning between programming languages can be both exciting and challenging. If you’re moving from JavaScript or TypeScript to Python, it’s essential to understand some more hidden-from-the-eye key differences between these languages to avoid common pitfalls. Let’s explore some important distinctions that you should be aware of.</p><h3>1. Async-Await Antics</h3><p>In JavaScript or TypeScript, <em>async-await</em> allows for seamless chaining of asynchronous functions:</p><pre>async function asyncFunc(): Promise&lt;string&gt; {<br> return &quot;Hello&quot;;<br>}<br><br>async function foo(): Promise&lt;string&gt; {<br> return asyncFunc();<br>}<br><br>async function main(): Promise&lt;void&gt; {<br> console.log(await foo()); // Output: Hello<br>}<br><br>main();</pre><p>However, in Python, <em>async-await</em> behaves differently; you need to explicitly <em>await</em> each asynchronous function call:</p><pre>import asyncio<br><br>async def async_func():<br> return &quot;Hello&quot;<br><br>async def foo():<br> return async_func() # This won&#39;t work as expected!<br><br>async def main():<br> print(await foo()) # Output: &lt;coroutine …&gt;<br><br>asyncio.run(main())</pre><p>To achieve the expected behavior, use <em>await</em> inside the <em>foo</em> function:</p><pre>async def foo():<br> return await async_func()<br><br>asyncio.run(main()) # Output: Hello</pre><h3>2. The Mysterious Case of `a.b`</h3><p>JavaScript/TypeScript is forgiving when accessing <em>undefined</em> properties:</p><pre>let a = [];<br><br>console.log(a.b); // Output: undefined</pre><p>Python, on the other hand, raises an error for undefined attributes:</p><pre>a = []<br><br>print(a.b) # Error: &#39;list&#39; object has no attribute &#39;b&#39;</pre><p>Python prioritizes clarity and explicitness in attribute access.</p><h3>3. OOP: Classes and Prototypes</h3><h4>JavaScript (with Prototypes):</h4><blockquote><em>(This example uses the function syntax for classes, although there is a syntactic-sugar option to use the class keyword. I just like to show things as they truly are, and classes in JS are essentially functions.)</em></blockquote><pre>function Animal(species) {<br> this.species = species;<br>}<br><br>Animal.prototype.makeSound = function() {<br> // Placeholder for method implementation<br>};<br><br>function Dog(species) {<br> Animal.call(this, species);<br>}<br><br>Dog.prototype = Object.create(Animal.prototype);<br>Dog.prototype.constructor = Dog;<br>Dog.prototype.makeSound = function() {<br> return &quot;Woof!&quot;;<br>};<br><br>let myDog = new Dog(&quot;Canine&quot;);<br><br>console.log(myDog.species); // Output: Canine<br>console.log(myDog.makeSound()); // Output: Woof!</pre><h4>Python (with Classes):</h4><pre>class Animal:<br>  def __init__(self, species):<br>   self.species = species<br>  <br>  def make_sound(self):<br>   pass # Placeholder for method implementation<br><br>class Dog(Animal):<br> def make_sound(self):<br>   return &quot;Woof!&quot;<br><br><br>my_dog = Dog(&quot;Canine&quot;)<br><br>print(my_dog.species) # Output: Canine<br>print(my_dog.make_sound()) # Output: Woof!</pre><p>Python’s <em>class</em> keyword offers a more structured approach to object-oriented programming compared to JavaScript’s prototype-based inheritance.</p><blockquote><em>Always remember, you should not automatically use the OOP pattern in JS. Read more </em><a href="https://medium.com/@araujjohnny/stop-using-javascript-classes-d0b6890ef097"><em>here</em></a><em>.</em></blockquote><h3>4. Conditional Statements: `if a:`</h3><p>JavaScript and Python differ in their interpretation of truthy and falsy values:</p><pre>let a = [];<br><br>if (a) {<br> console.log(&quot;Truthy!&quot;); // Output: Truthy!<br>}</pre><pre>a = []<br><br>if a:<br>  print(&quot;Truthy!&quot;)<br>else:<br>  print(&quot;Falsy!&quot;) # Output: Falsy!</pre><p>In Python, only explicitly falsy values are considered falsy, including empty lists (<em>[]</em>).</p><p>This comparison highlights some hidden key differences between JavaScript/TypeScript and Python, emphasizing important aspects of each language’s syntax and behavior. <br>Transitioning between these languages requires a nuanced understanding of their unique characteristics and approaches to programming. <br>Happy coding everyone! 🐍🌐</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4a982328d1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Up your game with Python’s asyncio]]></title>
            <link>https://medium.com/@ohad2712/up-your-game-with-pythons-asyncio-817e1a96a799?source=rss-899df3d1f52b------2</link>
            <guid isPermaLink="false">https://medium.com/p/817e1a96a799</guid>
            <category><![CDATA[asyncio]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ohad Finkelstein]]></dc:creator>
            <pubDate>Fri, 10 Nov 2023 13:21:27 GMT</pubDate>
            <atom:updated>2023-11-10T13:21:27.203Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*BRSjp6myoql0HcK75LA4RA.png" /></figure><h4>Exploring the significance of Python’s asyncio module in concurrent programming</h4><p>Greetings, fellow Python enthusiasts! In this article we embark on an exhilarating journey into the heart of Python’s async world — brace yourselves for the wild and wonderful ride that is the asyncio module. Hold on to your hats as we explore the ins and outs of this powerhouse, uncovering its secrets, and understanding why it&#39;s the coolest kid on the asynchronous programming block.</p><blockquote>This article uses Python ≥3.7. asyncio has evolved swiftly, so in order to be on the safe side, leveraging all the cool asyncio features it is advised to use version 3.7 or higher.</blockquote><h3>Asyncio Unmasked</h3><p>Picture this: you’re at a party, and everyone’s talking at once. Instead of waiting for one person to finish before moving on to the next, wouldn’t it be awesome to chat with multiple folks simultaneously? Well, that’s precisely what <a href="https://docs.python.org/3/library/asyncio.html"><em>asyncio</em></a> does for your Python programs! It’s like giving your code a VIP pass to the multitasking party.</p><h3>Setting common ground</h3><p>This article assumes basic knowledge in Python, including the more fundamental parts of how Python works under the hood.<br>Despite that, just before we dive into some code samples and more in-depth explanations, let’s set a brief common ground with the two core concepts of asyncio, the event loop and coroutines.</p><h4>Event Loop</h4><p>“(Event loop is) the main coordinator of tasks in an asynchronous program. An event loop keeps track of all of the tasks that are to be run asynchronously, and decides which of those tasks should be executed at a given moment. In other words, event loops handle the task switching aspect (or the execution flow) of asynchronous programming.” (<a href="https://www.oreilly.com/library/view/mastering-concurrency-in/9781789343052/a426acb5-23fe-4735-9d71-e880629776f2.xhtml">O’Reilly</a>)</p><h4>Coroutines</h4><p>Coroutines are a special type of function that wrap around specific tasks, so that they can be executed asynchronously. They are like building blocks that can be controlled in a way where they can be paused or resumed during their execution.</p><h4>How Coroutines work together with the Event Loop?</h4><p>Once we await a coroutine, then the control over executing this coroutine is yielded back to the event loop, which allows the concurrent processing to continue.</p><h3>Simple Code Example- Just to get things going</h3><pre>import asyncio<br><br>async def task_one():<br>    print(&quot;Task 1 is starting&quot;)<br>    await asyncio.sleep(2)  # Simulating some asynchronous work<br>    print(&quot;Task 1 is done&quot;)<br>    return &quot;Result from Task 1&quot;<br><br>async def task_two():<br>    print(&quot;Task 2 is starting&quot;)<br>    await asyncio.sleep(3)  # Simulating some asynchronous work<br>    print(&quot;Task 2 is done&quot;)<br>    return &quot;Result from Task 2&quot;<br><br>async def main():<br>    print(&quot;Let the async tasks begin!&quot;)<br><br>    # Using asyncio.gather to run tasks concurrently<br>    results = await asyncio.gather(task_one(), task_two())<br><br>    # Results will be a list containing the results of each task<br>    print(&quot;Results:&quot;, results)<br><br>    print(&quot;All async tasks completed!&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><p>Output:</p><pre>Let the async tasks begin!<br>Task 1 is starting<br>Task 2 is starting<br>Task 1 is done<br>Task 2 is done<br>Results: [&#39;Result from Task 1&#39;, &#39;Result from Task 2&#39;]<br>All async tasks completed!</pre><p>In this piece of code, we have two asynchronous tasks (task_one and task_two) that each simulate some I/O or async work using asyncio.sleep. The main function orchestrates these tasks using the asyncio.gather function.</p><h3>Concurrent I/O Operations — Mastering the Art of Juggling</h3><p>Imagine you’re a code circus performer juggling multiple I/O tasks: fetching data from APIs, dancing with databases, and serenading HTTP requests. Enter asyncio, the ringmaster that turns this chaotic juggling act into a synchronized spectacle.</p><p>For the sake of our next code example, let’s introduce <a href="https://docs.aiohttp.org/en/stable/"><em>aiohttp</em></a><em> </em>which will allow us perform HTTP requests to APIs.</p><p>Take a look at this example:</p><pre>import asyncio<br>import aiohttp<br><br>async def fetch_data(url):<br>    async with aiohttp.ClientSession() as session:<br>        async with session.get(url) as response:<br>            return await response.text()<br><br>async def main():<br>    urls = [&quot;https://api.example.com/data1&quot;, &quot;https://api.example.com/data2&quot;]<br>    tasks = [fetch_data(url) for url in urls]<br>    results = await asyncio.gather(*tasks)<br>    print(results)<br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><p>Output will include the returned data from the different URLs in the order they arrive, rather than the order they are requested.</p><p>The asyncio.gather function lets us synchronize our async tasks (AKA coroutines), making sure your juggling act doesn&#39;t drop a single data ball.<br>To better understand asyncio.gather here’s an even simpler example:</p><pre>import asyncio<br><br>async def first_called_function():<br>    print(&#39;In first called function&#39;)<br>    await asyncio.sleep(5)<br>    print(&#39;1&#39;)<br>    <br>async def second_called_function():<br>    print(&#39;In second called function&#39;)<br>    await asyncio.sleep(3)<br>    print(&#39;2&#39;)<br>    <br>async def third_called_function():<br>    print(&#39;In third called function&#39;)<br>    await asyncio.sleep(1)<br>    print(&#39;3&#39;)<br><br>async def main():<br>    await asyncio.gather(<br>        first_called_function(), # Called first, but has the greatest sleep time<br>        second_called_function(), # Called second, and has the second greatest sleep time <br>        third_called_function(), # Called last, but has the lowest sleep time<br>    )<br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><p>Output:</p><pre>In first called function<br>In second called function<br>In third called function<br>3<br>2<br>1</pre><h3>Asynchronous File I/O — Where Files Dance to Your Tune</h3><p>File I/O operations, traditionally synchronous, can impede program execution. asyncioextends its utility to asynchronous file operations, mitigating the wait time associated with reading and writing files. With asyncio, we practically get a choreographer that orchestrates the asynchronous file I/O ballet easily.</p><pre>import asyncio<br>import aiofiles<br><br>async def write_to_file(filename, content):<br>    async with aiofiles.open(filename, &quot;w&quot;) as file:<br>        await file.write(content)<br><br>async def main():<br>    tasks = [<br>        write_to_file(&quot;file1.txt&quot;, &quot;Content for file 1&quot;),<br>        write_to_file(&quot;file2.txt&quot;, &quot;Content for file 2&quot;),<br>    ]<br>    await asyncio.gather(*tasks)<br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><p>This example shows how our program doesn’t have to wait idle until it writes data to files. It all happens concurrently.</p><h3>Benefits of Asyncio — A Potion of Performance and Scalability</h3><ol><li><strong>Improved Performance:</strong> asyncio bestows upon you the gift of speed. It leverages asynchronous programming paradigms to enhance the performance of programs, particularly those with high I/O demands.</li><li><strong>Scalability:</strong> With asyncio, your applications can handle a multitude of concurrent connections without breaking a sweat.</li><li><strong>Concise and Readable Code:</strong> The adoption of the async/await syntax fosters code readability, reducing complexity and making code maintenance more straightforward.</li><li><strong>Responsive I/O Operations:</strong> asyncioensures the responsiveness of I/O operations, enabling programs to remain agile and efficient.</li></ol><h3>Best Practices</h3><ol><li>You have asynchronous code? Define that function with async def, and don’t forget to await the returned coroutine values.</li><li>Want to run multiple coroutines concurrently? Use asyncio.gather or asyncio.create_task.</li><li>Want to control the event loop when running your program? Use asyncio.run. It will get the event loop to run tasks until they are marked as complete, and then close the event loop. It is mainly used to call your main function (the entry point) this way: asyncio.run(main()). This function basically schedules the main() coroutine for execution on the event loop.</li><li>Need to wait a certain time before proceeding? Use asyncio.sleep. <strong>However</strong>, pay attention for misusage of this function. Use it carefully and only when absolutely necessary.</li><li>Need to set a timeout for a coroutine? Use asyncio.wait_for.</li><li>Try to always pick modules and libraries that support asyncio. It will make your code run much more efficiently.</li></ol><h3>Conclusion:</h3><p>In the mystical realm of Python, the asyncio module stands tall as a beacon of efficiency, scalability, and responsiveness.</p><p>Mastering this not only enhances your programming prowess, but unlocks a realm of possibilities for handling concurrent tasks with finesse. Go ahead and implement it in your existing code, and in your future code.</p><p>May your code be swift, your I/O responsive, and your programs dance to the beat of concurrency!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=817e1a96a799" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to HTTP in Python3]]></title>
            <link>https://medium.com/@ohad2712/introduction-to-http-in-python3-6df69362c8f4?source=rss-899df3d1f52b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6df69362c8f4</guid>
            <category><![CDATA[http-server]]></category>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Ohad Finkelstein]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 12:13:31 GMT</pubDate>
            <atom:updated>2025-05-18T16:40:41.885Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_oSOvBmwwO0XXx5r9-Z4A.jpeg" /></figure><h4>What do TCP and UDP have anything to do with it all?</h4><p>In this article we will dive into the world of web protocols, specifically HTTP, and explore how it relates to TCP and UDP in Python. It is a Python version of my last article, that introduced the same topics for Node.js. If this is more what you are after feel free to check it out <a href="https://medium.com/@ohad2712/introduction-to-http-in-node-js-0011e49bd718">here</a>.</p><h3>Starting with HTTP</h3><p>HTTP (<strong>H</strong>yper<strong>t</strong>ext <strong>T</strong>ransfer <strong>P</strong>rotocol) is the foundation of the web world. When you visit a website, your browser sends HTTP requests to a server, which then responds with web pages. It’s like a conversation between your browser and the server.</p><p>For instance, if you send a request that says “Joe” the server might reply with “Hi there, Joe”.<br>Below there is a basic example of how such HTTP server would work in Python3. We will use the <a href="https://docs.python.org/3/library/http.client.html#module-http.client"><em>http.client</em></a> and the <a href="https://docs.python.org/3/library/http.server.html#module-http.server"><em>http.server</em></a> built-in modules for that.<br>It’s a simple example so it doesn’t strictly follows HTTP standards and as the <em>http.server</em> module states, it is not recommended for production usage as it only implements <a href="https://docs.python.org/3/library/http.server.html#http-server-security">basic security checks</a>, but that’s fine for the time being.</p><pre>import http.server<br>import http.client<br><br>PORT = 8001<br><br>class Store:<br>    def __init__(self):<br>        self.requestBody = &#39;&#39;<br>        self.responseBody = &#39;&#39;<br><br>store = Store()<br><br>class MyHTTPRequestHandler(http.server.BaseHTTPRequestHandler):<br>    def do_POST(self):<br>        content_length = int(self.headers[&#39;Content-Length&#39;])<br>        content = self.rfile.read(content_length).decode(&#39;utf-8&#39;)<br>        store.requestBody = content<br><br>        response_content = f&#39;Hi there, {content}&#39;.encode(&#39;utf-8&#39;)<br>        self.send_response(200)<br>        self.send_header(&#39;Content-Type&#39;, &#39;text/plain&#39;)<br>        self.send_header(&#39;Content-Length&#39;, len(response_content))<br>        self.end_headers()<br>        self.wfile.write(response_content)<br><br>def server_listen():<br>    with http.server.HTTPServer((&#39;localhost&#39;, PORT), MyHTTPRequestHandler) as server:<br>        print(f&#39;HTTP server listening on {PORT}&#39;)<br>        http_request()<br><br>def http_request():<br>    conn = http.client.HTTPConnection(&#39;localhost&#39;, PORT)<br>    content = &#39;Joe&#39;<br>    headers = {<br>        &#39;Content-Type&#39;: &#39;text/plain&#39;,<br>        &#39;Content-Length&#39;: str(len(content))<br>    }<br>    conn.request(&#39;POST&#39;, &#39;/greet&#39;, body=content, headers=headers)<br>    response = conn.getresponse()<br>    data = response.read().decode(&#39;utf-8&#39;)<br>    store.responseBody = data<br>    close_connections()<br><br>def close_connections():<br>    server.server_close()<br><br>    print(store.requestBody)  # Joe<br>    print(store.responseBody)  # Hi there, Joe<br><br>server_listen()</pre><h3>The TCP Connection</h3><p>Now, let’s introduce <a href="https://en.wikipedia.org/wiki/Transmission_Control_Protocol">TCP</a> (<strong>T</strong>ransmission <strong>C</strong>ontrol <strong>P</strong>rotocol). TCP is the underlying protocol that HTTP is built upon, as can be seen in <a href="https://www.w3.org/Protocols/Specs.html">the HTTP official specs</a>.<br>Despite the fact we now know that, I’m going to ask you to pretend you don’t know that yet. Let’s prove it! Science, right? :)</p><p>In Python, we have a built-in modules called <a href="https://docs.python.org/3/library/threading.html"><em>threading</em></a><em> </em>and <a href="https://docs.python.org/3/library/socket.html"><em>socket</em></a> that help us create TCP clients and servers.</p><p>It is worth knowing that TCP differs from HTTP by several aspects:</p><ul><li>Requests can’t be sent spontaneously. A connection must be established first.</li><li>Once connected, messages can flow in both directions.</li><li>An established connection must be manually closed.</li></ul><p>Below is a simple implementation of a TCP client that wishes to be greeted by a server:</p><pre>import socket<br>import threading<br><br>PORT = 8001<br>MAXIMUM_BYTES_RECEIVABLE = 1024<br><br>class Store:<br>    def __init__(self):<br>        self.requestBody = &#39;&#39;<br>        self.responseBody = &#39;&#39;<br><br>store = Store()<br><br>def handle_client(client_socket):<br>    request_data = client_socket.recv(MAXIMUM_BYTES_RECEIVABLE).decode(&#39;utf-8&#39;)<br>    store.requestBody = request_data<br><br>    response_data = f&#39;Hi there, {request_data}&#39;.encode(&#39;utf-8&#39;)<br>    client_socket.send(response_data)<br><br>    response = client_socket.recv(MAXIMUM_BYTES_RECEIVABLE).decode(&#39;utf-8&#39;)<br>    store.responseBody = response<br><br>    client_socket.close()<br><br>def server_listen():<br>    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # When the socket type is socket.SOCK_STREAM the protocol being used is TCP by default.<br>    server.bind((&#39;0.0.0.0&#39;, PORT))<br>    server.listen(5)<br>    print(f&#39;TCP server listening on {PORT}&#39;)<br><br>    while True:<br>        client_socket, addr = server.accept() # Blocks execution and waits for an incoming connection.<br>        client_handler = threading.Thread(target=handle_client, args=(client_socket,))<br>        client_handler.start()<br><br>def http_request():<br>    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>    client.connect((&#39;localhost&#39;, PORT))<br>    content = &#39;Joe&#39;<br>    client.send(content.encode(&#39;utf-8&#39;))<br>    client.shutdown(socket.SHUT_WR)<br>    response = client.recv(MAXIMUM_BYTES_RECEIVABLE).decode(&#39;utf-8&#39;)<br>    store.responseBody = response<br>    client.close()<br>    close_connections()<br><br>def close_connections():<br>    server.close()<br><br>    print(store.requestBody)  # Joe<br>    print(store.responseBody)  # Hi there, Joe<br><br>if __name__ == &#39;__main__&#39;:<br>    server_listen()<br>    http_request()</pre><p>Now, imagine having a TCP proxy that can pass messages between HTTP clients and servers. Even though this proxy doesn’t understand HTTP, it can still transmit requests and responses.</p><p>Here’s how the implementation for this will look like:</p><pre>import socket<br>import http.client<br>import threading<br><br>HTTP_PORT = 8001<br>PROXY_TCP_PORT = 8002<br>MAXIMUM_BYTES_RECEIVABLE = 1024<br><br>class Store:<br>    def __init__(self):<br>        self.requestBody = &#39;&#39;<br>        self.responseBody = &#39;&#39;<br><br>store = Store()<br><br>def proxy_handler(local_socket):<br>    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as remote_socket:<br>        remote_socket.connect((&#39;localhost&#39;, HTTP_PORT))<br>        <br>        def forward(src, dst):<br>            while True:<br>                data = src.recv(MAXIMUM_BYTES_RECEIVABLE)<br>                if not data:<br>                    break<br>                dst.send(data)<br>        <br>        threading.Thread(target=forward, args=(local_socket, remote_socket)).start()<br>        threading.Thread(target=forward, args=(remote_socket, local_socket)).start()<br><br>def http_server_handler(client_socket):<br>    data = client_socket.recv(MAXIMUM_BYTES_RECEIVABLE).decode(&#39;utf-8&#39;)<br>    store.requestBody = data<br><br>    response_data = f&#39;Hi there, {data}&#39;.encode(&#39;utf-8&#39;)<br>    client_socket.send(response_data)<br><br>    response = client_socket.recv(MAXIMUM_BYTES_RECEIVABLE).decode(&#39;utf-8&#39;)<br>    store.responseBody = response<br><br>def http_server_listen():<br>    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:<br>        server.bind((&#39;0.0.0.0&#39;, HTTP_PORT)<br>        server.listen(5)<br>        print(f&#39;HTTP server listening on {HTTP_PORT}&#39;)<br><br>        while True:<br>            client_socket, addr = server.accept()<br>            threading.Thread(target=http_server_handler, args=(client_socket,)).start()<br><br>def proxy_listen():<br>    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as proxy_server:<br>        proxy_server.bind((&#39;0.0.0.0&#39;, PROXY_TCP_PORT))<br>        proxy_server.listen(5)<br>        print(f&#39;TCP proxy listening on {PROXY_TCP_PORT}&#39;)<br><br>        while True:<br>            local_socket, addr = proxy_server.accept()<br>            threading.Thread(target=proxy_handler, args=(local_socket,)).start()<br><br>def http_request():<br>    conn = http.client.HTTPConnection(&#39;localhost&#39;, PROXY_TCP_PORT)<br>    content = &#39;Joe&#39;<br>    headers = {<br>        &#39;Content-Type&#39;: &#39;text/plain&#39;,<br>        &#39;Content-Length&#39;: str(len(content))<br>    }<br>    conn.request(&#39;POST&#39;, &#39;/greet&#39;, body=content, headers=headers)<br>    response = conn.getresponse()<br>    data = response.read().decode(&#39;utf-8&#39;)<br>    close_connections()<br><br>def close_connections():<br>    http_server_listen_thread.join()<br>    proxy_listen_thread.join()<br><br>    print(store.requestBody)  # Joe<br>    print(store.responseBody)  # Hi there, Joe<br><br>if __name__ == &#39;__main__&#39;:<br>    http_server_listen_thread = threading.Thread(target=http_server_listen)<br>    proxy_listen_thread = threading.Thread(target=proxy_listen)<br>    http_server_listen_thread.start()<br>    http_server_listen_thread.join()<br>    proxy_listen_thread.start()<br>    http_request()</pre><p>As mentioned before, it can be seen that although the TCP proxy server does not know what HTTP is the requests and responses completely go through.</p><h4>Understanding TCP’s Characteristics</h4><p>Before we go any further, a couple of facts on TCP:</p><ul><li>It’s reliable, meaning it ensures that messages are acknowledged, retransmitted if needed, and timed out if necessary.</li><li>It guarantees that data arrives in the correct order.</li></ul><p>This is quite amazing. No wonder TCP is so common.</p><p>However….</p><p>You knew it’s coming, right?</p><p>TCP can be a bit heavy — it requires setting up three packets for a socket connection to be able to allow data sending.</p><p>In the world of HTTP, this means that parallel HTTP/1.1 requests require multiple TCP connections, which can be resource-intensive.</p><p><a href="https://en.wikipedia.org/wiki/HTTP/2">HTTP/2</a> tries to improve this by handling parallel requests over a single connection. However, it faces challenges when a single packet times out or arrives out of order, causing all requests to stall.</p><p>Now, imagine there’s an alternative to TCP that allows parallel HTTP messages without these collective consequences. Sounds good, right?<br>That alternative is called <a href="https://en.wikipedia.org/wiki/User_Datagram_Protocol">UDP</a> (<strong>U</strong>ser <strong>D</strong>atagram <strong>P</strong>rotocol).</p><h3>The UDP Connection</h3><p>Let’s begin with how UDP differs from TCP:</p><ul><li>There’s no concept of a connection; you send data, and you hope someone receives it.</li><li>You can only send small chunks of data which do not necessarily represent a whole message (read more about <a href="https://en.wikipedia.org/wiki/Maximum_transmission_unit">MTU</a>), and there are no built-in delimiters unless explicitly included.</li><li>As a result, creating even a basic request/response mechanism is more complex (but still possible).</li></ul><p>Let’s dive in into an example of a UDP client that wants to communicate with a server.<br>This time, we will define our socket to be of a <em>SOCK_DGRAM </em>type:</p><pre>import socket<br><br>PORT = 8001<br>EOS = b&#39;\0&#39;  # End of stream<br>MAXIMUM_BYTES_RECEIVABLE = 1024<br><br>class Store:<br>    def __init__(self):<br>        self.requestBody = &#39;&#39;<br>        self.responseBody = &#39;&#39;<br><br>store = Store()<br><br>def slice_but_last(data, encoding=&#39;utf-8&#39;):<br>    return data[:-1].decode(encoding)<br><br>def server_listen():<br>    sender = None<br><br>    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server:<br>        server.bind((&#39;0.0.0.0&#39;, PORT))<br>        print(f&#39;UDP server listening on {PORT}&#39;)<br><br>        while True:<br>            chunk, addr = server.recvfrom(MAXIMUM_BYTES_RECEIVABLE)<br>            sender = addr if sender is None else sender<br>            store.requestBody += slice_but_last(chunk)<br><br>            if chunk[-1:] == EOS:<br>                response_data = f&#39;Hi there, {store.requestBody}&#39;.encode(&#39;utf-8&#39;) + EOS<br>                server.sendto(response_data, sender)<br><br>                # Note: You can choose to close the server here if needed<br>                break<br><br>def http_request():<br>    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as client:<br>        content = &#39;Joe&#39;.encode(&#39;utf-8&#39;) + EOS<br>        client.sendto(content, (&#39;localhost&#39;, PORT))<br>        response_data, _ = client.recvfrom(MAXIMUM_BYTES_RECEIVABLE)<br>        store.responseBody = slice_but_last(response_data)<br><br>        close_connections()<br><br>def close_connections():<br>    print(store.requestBody)  # Joe<br>    print(store.responseBody)  # Hi there, Joe<br><br>if __name__ == &#39;__main__&#39;:<br>    server_listen()<br>    http_request()</pre><p>So given that we have an HTTP parser (<a href="https://pypi.org/project/http-parser/"><em>http-parser</em></a>, for example), this is how an HTTP solution can be implemented over UDP:</p><pre>import socket<br>from http_parser.parser import HttpParser<br><br>PORT = 8001<br>CRLF = &#39;\r\n&#39;<br>MAXIMUM_BYTES_RECEIVABLE = 1024<br><br>class Store:<br>    def __init__(self):<br>        self.requestBody = &#39;&#39;<br>        self.responseBody = &#39;&#39;<br><br>store = Store()<br><br>def server_listen():<br>    parser = HttpParser()<br><br>    def on_body(data):<br>        store.requestBody += data<br><br>    def on_message_complete():<br>        content = f&#39;Hi there, {store.requestBody}&#39;<br>        response = f&#39;HTTP/1.1 200 OK{CRLF}&#39; \<br>                   f&#39;Content-Type: text/plain{CRLF}&#39; \<br>                   f&#39;Content-Length: {len(content)}{CRLF}&#39; \<br>                   f&#39;{CRLF}&#39; \<br>                   f&#39;{content}&#39;<br>        server.sendto(response.encode(&#39;utf-8&#39;), sender)<br><br>    parser.on_body = on_body<br>    parser.on_message_complete = on_message_complete<br><br>    sender = None<br><br>    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server:<br>        server.bind((&#39;0.0.0.0&#39;, PORT))<br>        print(f&#39;UDP server listening on {PORT}&#39;)<br><br>        while True:<br>            chunk, sender = server.recvfrom(MAXIMUM_BYTES_RECEIVABLE)<br>            parser.execute(chunk)<br><br>def http_request():<br>    parser = HttpParser()<br><br>    def on_body(data):<br>        store.responseBody += data<br><br>    def on_message_complete():<br>        close_connections()<br><br>    parser.on_body = on_body<br>    parser.on_message_complete = on_message_complete<br><br>    content = &#39;Joe&#39;<br>    request = f&#39;POST /greet HTTP/1.1{CRLF}&#39; \<br>              f&#39;Content-Type: text/plain{CRLF}&#39; \<br>              f&#39;Content-Length: {len(content)}{CRLF}&#39; \<br>              f&#39;{CRLF}&#39; \<br>              f&#39;{content}&#39;<br><br>    client.sendto(request.encode(&#39;utf-8&#39;), (&#39;localhost&#39;, PORT))<br><br>def close_connections():<br>    server.close()<br>    client.close()<br><br>    print(store.requestBody)  # Joe<br>    print(store.responseBody)  # Hi there, Joe<br><br>if __name__ == &#39;__main__&#39;:<br>    client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)<br>    server_listen()<br>    http_request()</pre><p>Okay… looks good. We have a full implementation using UDP.<br>But we shouldn’t get too excited about UDP just yet. It has some significant drawbacks:</p><ul><li>It’s unreliable, meaning you can’t be sure if your message will reach its destination.</li><li>Packets don’t arrive in order, so you can’t guarantee the order of messages.</li></ul><h4>The Rise of QUIC and HTTP/3</h4><p>To address UDP’s limitations, a new protocol called <a href="https://en.wikipedia.org/wiki/QUIC">QUIC</a> was created. QUIC is built on top of UDP and uses clever algorithms to make it:</p><ul><li>Reliable</li><li>Ensure ordered packet delivery</li><li>Keep things lightweight</li></ul><p>This leads us straight into <a href="https://en.wikipedia.org/wiki/HTTP/3">HTTP/3</a>, which is still relatively new and experimental. It uses QUIC to fix the issues presented by HTTP/2. In HTTP/3, there are no connections, so sessions aren’t affected by each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/0*be3ZhipdgWA2owYx.png" /><figcaption>Taken from <a href="https://en.wikipedia.org/wiki/File:HTTP-1.1_vs._HTTP-2_vs._HTTP-3_Protocol_Stack.svg">Wikipedia</a></figcaption></figure><p>HTTP/3 is a promising advancement in web protocols, taking advantage of QUIC and UDP’s strengths.</p><p>While there is no built-in support for the QUIC protocol, one can use the <a href="https://github.com/aiortc/aioquic"><em>aioquic</em></a> module that supports both QUIC and HTTP/3 implementations.</p><h4>Example using the QUIC protocol</h4><p>See this simple example for a server using QUIC:</p><pre>import asyncio<br>import ssl<br>from aioquic.asyncio import connect, connect_udp, Connection, serve<br>from aioquic.asyncio.protocol import BaseProtocol, DatagramProtocol<br>from aioquic.asyncio.protocol.stream import DataReceived<br><br>class HTTPServerProtocol(BaseProtocol):<br>    def __init__(self, *args, **kwargs):<br>        super().__init__(*args, **kwargs)<br><br>    async def data_received(self, data):<br>        await super().data_received(data)<br>        if isinstance(self._quic, Connection):<br>            for stream_id, buffer in self._quic._events[DataReceived]:<br>                data = buffer.read()<br>                response = f&#39;HTTP/1.1 200 OK\r\nContent-Length: {len(data)}\r\n\r\n{data.decode(&quot;utf-8&quot;)}&#39;<br>                self._quic.send_stream_data(stream_id, response.encode(&#39;utf-8&#39;))<br><br>async def main():<br>    loop = asyncio.get_event_loop()<br><br>    # Create QUIC server context<br>    quic_server = await loop.create_server(HTTPServerProtocol, &#39;localhost&#39;, 8001)<br><br>    async with quic_server:<br>        await quic_server.serve_forever()<br><br>if __name__ == &#39;__main__&#39;:<br>    loop = asyncio.get_event_loop()<br>    loop.run_until_complete(main())</pre><p>And this is the client:</p><pre>import asyncio<br>import ssl<br>from aioquic.asyncio import connect, connect_udp, Connection<br>from aioquic.asyncio.protocol import BaseProtocol<br><br>class HTTPClientProtocol(BaseProtocol):<br>    def __init__(self, *args, **kwargs):<br>        super().__init__(*args, **kwargs)<br>        self.connected_event = asyncio.Event()<br><br>    def quic_event_received(self, event):<br>        super().quic_event_received(event)<br>        if event.matches(&#39;connected&#39;):<br>            self.connected_event.set()<br><br>    async def request(self, path, data=None):<br>        stream_id = self._quic.get_next_available_stream_id()<br>        self._quic.send_stream_data(stream_id, data)<br>        await self.connected_event.wait()<br>        response = await self._quic.receive_data(stream_id)<br>        return response<br><br>async def main():<br>    loop = asyncio.get_event_loop()<br><br>    # Create QUIC client context<br>    quic = connect(&#39;localhost&#39;, 8001)<br><br>    async with quic as protocol:<br>        client_protocol = HTTPClientProtocol(quic, protocol._session_id, None)<br>        await client_protocol.connected_event.wait()<br>        <br>        data = &#39;Hello, Joe!&#39;<br>        response = await client_protocol.request(&#39;/greet&#39;, data.encode(&#39;utf-8&#39;))<br>        print(response.decode(&#39;utf-8&#39;))<br><br>if __name__ == &#39;__main__&#39;:<br>    loop = asyncio.get_event_loop()<br>    loop.run_until_complete(main())</pre><h4>Example for a QUIC bidirectional node</h4><pre>import asyncio<br>import ssl<br>from aioquic.asyncio import connect, serve<br>from aioquic.asyncio.protocol import QuicConnectionProtocol<br>from aioquic.quic.configuration import QuicConfiguration<br>from aioquic.quic.events import StreamDataReceived, ProtocolNegotiated<br><br># Common QUIC configuration<br># Pay attention that you would to generate a self-signed certificate for testing:<br># `openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes -subj &quot;/CN=localhost&quot;`<br>def get_quic_config(is_server=False):<br>    config = QuicConfiguration(is_client=not is_server)<br>    config.alpn_protocols = [&quot;echo&quot;]<br>    config.verify_mode = ssl.CERT_NONE<br>    config.load_cert_chain(&quot;cert.pem&quot;, &quot;key.pem&quot;) if is_server else None<br>    return config<br><br># Protocol used by both server &amp; client<br>class EchoProtocol(QuicConnectionProtocol):<br>    def __init__(self, *args, node_name=&quot;Node&quot;, **kwargs):<br>        super().__init__(*args, **kwargs)<br>        self.node_name = node_name<br><br>    def quic_event_received(self, event):<br>        if isinstance(event, ProtocolNegotiated):<br>            print(f&quot;{self.node_name} negotiated protocol.&quot;)<br>        elif isinstance(event, StreamDataReceived):<br>            message = event.data.decode(&quot;utf-8&quot;)<br>            print(f&quot;{self.node_name} received: {message}&quot;)<br><br>            if event.end_stream:<br>                response = f&quot;{self.node_name} echoes: {message}&quot;<br>                self._quic.send_stream_data(event.stream_id, response.encode(&quot;utf-8&quot;), end_stream=True)<br><br># The bidirectional node<br>class QuicNode:<br>    def __init__(self, name, host=&#39;127.0.0.1&#39;, port=4433):<br>        self.name = name<br>        self.host = host<br>        self.port = port<br>        self.config = get_quic_config(is_server=True)<br><br>    async def start_server(self):<br>        await serve(self.host, self.port, configuration=self.config,<br>                    create_protocol=lambda conn, _: EchoProtocol(conn, node_name=self.name))<br>        <br>        print(f&quot;{self.name} server running at {self.host}:{self.port}&quot;)<br><br>    async def send_message(self, target_host, target_port, message):<br>        config = get_quic_config(is_server=False)<br>        async with connect(target_host, target_port, configuration=config,<br>                           create_protocol=lambda conn, _: EchoProtocol(conn, node_name=self.name)) as protocol:<br>            <br>            stream_id = protocol._quic.get_next_available_stream_id()<br>            protocol._quic.send_stream_data(stream_id, message.encode(&quot;utf-8&quot;), end_stream=True)<br>            <br>            await protocol._stream_send_buffer[stream_id].drain()<br>            await asyncio.sleep(1)  # Wait for response<br><br>    async def run(self):<br>        # Start the server part<br>        asyncio.create_task(self.start_server())<br><br>        # Delay before acting as a client<br>        await asyncio.sleep(3)<br><br>        # Send a message as a client<br>        await self.send_message(<br>          &quot;127.0.0.1&quot;, <br>          4434 if self.port == 4433 else 4433,<br>          f&quot;Hello from {self.name}!&quot;<br>        )<br><br>if __name__ == &quot;__main__&quot;:<br>    node1 = QuicNode(name=&quot;Node A&quot;, port=4433)<br>    node2 = QuicNode(name=&quot;Node B&quot;, port=4434)<br><br>    asyncio.run(asyncio.gather(<br>        node1.run(),<br>        node2.run()<br>    ))</pre><ul><li>Each <em>QuicNode</em> instance acts as both a QUIC server and client.</li><li><em>EchoProtocol</em> handles both receiving and replying.</li><li><em>send_message()</em> lets a node act as a client sending data to another node.</li></ul><h4>Example using the HTTP/3 protocol</h4><p>And just to have a complete picture of all examples, here is an example using the HTTP/3 protocol (with the help of the <a href="https://github.com/aiortc/aioquic"><em>aioquic</em></a> module).<br>The server:</p><pre>import asyncio<br>from aioquic.asyncio.protocol import connect, connect_udp, serve, QuicProtocol<br>from aioquic.asyncio.protocol.stream import DataReceived<br>from h11 import Response, Connection<br>from h11._events import Data<br><br>class HTTP3ServerProtocol(QuicProtocol):<br>    def __init__(self, *args, **kwargs):<br>        super().__init__(*args, **kwargs)<br>        self.conn = Connection()<br><br>    def quic_event_received(self, event):<br>        super().quic_event_received(event)<br>        if event.matches(&#39;handshake_completed&#39;):<br>            self.conn.initiate_upgrade_for_http2()<br><br>    async def data_received(self, data):<br>        await super().data_received(data)<br>        if isinstance(self._quic, QuicProtocol):<br>            for stream_id, buffer in self._quic._events[DataReceived]:<br>                data = buffer.read()<br>                response = Response(status_code=200, headers=[(&#39;content-length&#39;, str(len(data)))], content=data)<br>                data = self.conn.send(response)<br>                self._quic.transmit_data(stream_id, data)<br><br>async def main():<br>    loop = asyncio.get_event_loop()<br><br>    # Create QUIC server context<br>    quic_server = await loop.create_server(HTTP3ServerProtocol, &#39;localhost&#39;, 8001)<br><br>    async with quic_server:<br>        await quic_server.serve_forever()<br><br>if __name__ == &#39;__main__&#39;:<br>    loop = asyncio.get_event_loop()<br>    loop.run_until_complete(main())</pre><p>And the client:</p><pre>import asyncio<br>from aioquic.asyncio.protocol import connect, connect_udp, QuicProtocol<br>from h11 import Request, Response, Connection<br>from h11._events import Data<br><br>class HTTP3ClientProtocol(QuicProtocol):<br>    def __init__(self, *args, **kwargs):<br>        super().__init__(*args, **kwargs)<br>        self.conn = Connection()<br><br>    async def request(self, path, data=None):<br>        stream_id = self._quic.get_next_available_stream_id()<br>        request = Request(method=&#39;POST&#39;, target=path, headers=[(&#39;content-length&#39;, str(len(data)))]<br>            if data else [])<br>        data = self.conn.send(request)<br>        self._quic.transmit_data(stream_id, data)<br><br>        while True:<br>            event = self.conn.next_event()<br>            if isinstance(event, Data):<br>                self._quic.transmit_data(stream_id, event.data)<br>            elif event == h11.EndOfMessage():<br>                break<br><br>        response = await self._quic.receive_data(stream_id)<br>        return response<br><br>async def main():<br>    loop = asyncio.get_event_loop()<br><br>    # Create QUIC client context<br>    quic = connect(&#39;localhost&#39;, 8001)<br><br>    async with quic as protocol:<br>        client_protocol = HTTP3ClientProtocol(quic, protocol._session_id, None)<br>        <br>        data = &#39;Hello, Joe!&#39;<br>        response = await client_protocol.request(&#39;/greet&#39;, data.encode(&#39;utf-8&#39;))<br>        print(response.content.decode(&#39;utf-8&#39;))<br><br>if __name__ == &#39;__main__&#39;:<br>    loop = asyncio.get_event_loop()<br>    loop.run_until_complete(main())</pre><h3>Final words</h3><p>This evolution raises the question of whether we might say goodbye to TCP in the future, but that’s a topic for another article and maybe for the future to say.</p><p>And that’s a wrap on our journey through HTTP, TCP, and UDP in Python3! It might seem complex, but it’s a fascinating world of web communication beneath the surface of every website you visit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6df69362c8f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to HTTP in Node.js]]></title>
            <link>https://medium.com/@ohad2712/introduction-to-http-in-node-js-0011e49bd718?source=rss-899df3d1f52b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0011e49bd718</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[udp]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nodejs-httpserver]]></category>
            <category><![CDATA[tcp]]></category>
            <dc:creator><![CDATA[Ohad Finkelstein]]></dc:creator>
            <pubDate>Fri, 03 Nov 2023 12:57:05 GMT</pubDate>
            <atom:updated>2024-06-27T14:57:49.441Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dB4wl4G2fYYfgKba_XLog.png" /></figure><h4>What do TCP and UDP have anything to do with it all?</h4><p>In this article we’re going to dive into the world of web protocols, specifically HTTP, and explore how it relates to TCP and UDP in Node.js. It might sound a bit technical, but don’t worry; we’ll keep it simple and easy to understand.</p><p>It is worth mentioning though, that in the following code samples we will use Typescript by ECMA6 standards, so familiarity with these is recommended. If you are only familiar with Javascript don’t worry; it will still be quite easy to get the idea.</p><h3>Starting with HTTP</h3><p>HTTP (<strong>H</strong>yper<strong>t</strong>ext <strong>T</strong>ransfer <strong>P</strong>rotocol) is the foundation of the web world. When you visit a website, your browser sends HTTP requests to a server, which then responds with web pages. It’s like a conversation between your browser and the server.</p><p>For instance, if you send a request that says “Joe” the server might reply with “Hi there, Joe”. <br>Below there is a basic example of how such HTTP server would work in Node.js. We will use the <a href="https://nodejs.org/api/http.html"><em>http</em></a> built-in module for that. <br>It’s simple so it doesn’t strictly follows HTTP standards, but that’s fine for the time being.</p><pre>import { createServer, IncomingMessage, ServerResponse } from &#39;http&#39;;<br><br>const PORT: number = 8001;<br><br>interface Store {<br>  requestBody: string;<br>  responseBody: string;<br>}<br><br>const store: Store = {<br>  requestBody: &#39;&#39;,<br>  responseBody: &#39;&#39;,<br>};<br><br>const server = createServer((req: IncomingMessage, res: ServerResponse) =&gt; {<br>  let data: str = &#39;&#39;;<br><br>  req.on(&#39;data&#39;, (chunk: string) =&gt; {<br>    data += chunk;<br>  });<br><br>  req.on(&#39;end&#39;, () =&gt; {<br>    store.requestBody = data;<br><br>    const content: string = `Hi there, ${data}`;<br>    res.statusCode = 200;<br>    res.setHeader(&#39;Content-Type&#39;, &#39;text/plain&#39;);<br>    res.setHeader(&#39;Content-Length&#39;, content.length.toString());<br>    res.write(content);<br>    res.end();<br>  });<br>});<br><br>const serverListen = () =&gt; {<br>  server.listen(PORT, () =&gt; {<br>    console.log(`HTTP server listening on ${PORT}`);<br><br>    httpRequest();<br>  });<br>};<br><br>const httpRequest = () =&gt; {<br>  const req = createServer({<br>    port: PORT,<br>    method: &#39;POST&#39;,<br>    path: &#39;/greet&#39;,<br>  }, (res: IncomingMessage) =&gt; {<br>    let data: str = &#39;&#39;;<br><br>    res.on(&#39;data&#39;, (chunk: string) =&gt; {<br>      data += chunk;<br>    });<br><br>    res.on(&#39;end&#39;, () =&gt; {<br>      store.responseBody = data;<br>      closeConnections();<br>    });<br>  });<br><br>  const content: string = &#39;Joe&#39;;<br>  req.setHeader(&#39;Content-Type&#39;, &#39;text/plain&#39;);<br>  req.setHeader(&#39;Content-Length&#39;, content.length.toString());<br>  req.write(content);<br>  req.end();<br>};<br><br>const closeConnections = () =&gt; {<br>  server.close();<br><br>  console.log(store.requestBody); // Joe<br><br>  console.log(store.responseBody); // Hi there, Joe<br>};<br><br>serverListen();</pre><h3>The TCP Connection</h3><p>Now, let’s introduce <a href="https://en.wikipedia.org/wiki/Transmission_Control_Protocol">TCP</a> (<strong>T</strong>ransmission <strong>C</strong>ontrol <strong>P</strong>rotocol). TCP is the underlying protocol that HTTP is built upon, as can be seen in <a href="https://www.w3.org/Protocols/Specs.html">the HTTP official specs</a>.<br>Despite the fact we now know that, I’m going to ask you to pretend you don’t know that yet. Let’s prove it! Science, right? :)</p><p>In Node.js, we have a built-in module called <a href="https://nodejs.org/api/net.html"><em>net</em></a> that helps us create TCP clients and servers.</p><p>It is worth knowing that TCP differs from HTTP by several aspects:</p><ul><li>Requests can’t be sent spontaneously. A connection must be established first.</li><li>Once connected, messages can flow in both directions.</li><li>An established connection must be manually closed.</li></ul><p>Below is a simple implementation of a TCP client that wishes to be greeted by a server:</p><pre>import { createServer, Socket } from &#39;net&#39;;<br><br>const PORT: number = 8001;<br><br>interface Store {<br>  requestBody: string;<br>  responseBody: string;<br>}<br><br>const store: Store = {<br>  requestBody: &#39;&#39;,<br>  responseBody: &#39;&#39;,<br>};<br><br>const server = createServer((socket: Socket) =&gt; {<br>  socket.on(&#39;data&#39;, (chunk: Buffer) =&gt; {<br>    store.requestBody += chunk.toString(&#39;utf-8&#39;);<br>  });<br><br>  socket.on(&#39;end&#39;, () =&gt; {<br>    socket.end(`Hi there, ${store.requestBody}`);<br>  });<br>});<br><br>const client = new Socket();<br><br>const serverListen = () =&gt; {<br>  server.listen(PORT, () =&gt; {<br>    console.log(`TCP server listening on ${PORT}`);<br><br>    httpRequest();<br>  });<br>};<br><br>const httpRequest = () =&gt; {<br>  client.on(&#39;data&#39;, (chunk: Buffer) =&gt; {<br>    store.responseBody += chunk.toString(&#39;utf-8&#39;);<br>  });<br><br>  client.on(&#39;end&#39;, closeConnections);<br><br>  client.connect({ port: PORT }, () =&gt; {<br>    console.log(`TCP client connected to ${PORT}`);<br>    const content = &#39;Joe&#39;;<br><br>    client.end(content);<br>  });<br>};<br><br>const closeConnections = () =&gt; {<br>  server.close();<br><br>  console.log(store.requestBody); // Joe<br><br>  console.log(store.responseBody); // Hi there, Joe<br>};<br><br>serverListen();</pre><p>Now, imagine having a TCP proxy that can pass messages between HTTP clients and servers. Even though this proxy doesn’t understand HTTP, it can still transmit requests and responses.</p><p>Here’s how the implementation for this will look like:</p><pre>import { createServer, Socket } from &#39;net&#39;;<br>import { IncomingMessage, ServerResponse, request as httpRequest } from &#39;http&#39;;<br><br>const HTTP_PORT: number = 8001;<br>const PROXY_TCP_PORT: number = 8002;<br><br>interface Store {<br>  requestBody: string;<br>  responseBody: string;<br>}<br><br>const store: Store = {<br>  requestBody: &#39;&#39;,<br>  responseBody: &#39;&#39;,<br>};<br><br>const proxy = createServer((localSocket: Socket) =&gt; {<br>  const remoteSocket = new Socket();<br><br>  remoteSocket.connect(HTTP_PORT, &#39;localhost&#39;, () =&gt; {<br>    localSocket.on(&#39;data&#39;, (chunk: Buffer) =&gt; {<br>      remoteSocket.write(chunk);<br>    });<br>  <br>    remoteSocket.on(&#39;data&#39;, (chunk: Buffer) =&gt; {<br>      localSocket.write(chunk);<br>    });<br>  <br>    localSocket.on(&#39;close&#39;, () =&gt; {<br>      remoteSocket.end();<br>    });<br>  <br>    remoteSocket.on(&#39;close&#39;, () =&gt; {<br>      localSocket.end();<br>    });<br>  });<br>});<br><br>const httpServer = createServer((req: IncomingMessage, res: ServerResponse) =&gt; {<br>  let data = &#39;&#39;;<br><br>  req.on(&#39;data&#39;, (chunk: Buffer) =&gt; {<br>    data += chunk.toString(&#39;utf-8&#39;);<br>  });<br><br>  req.on(&#39;end&#39;, () =&gt; {<br>    store.requestBody = data;<br><br>    const content: string = `Hi there, ${data}`;<br>    res.statusCode = 200;<br>    res.setHeader(&#39;Content-Type&#39;, &#39;text/plain&#39;);<br>    res.setHeader(&#39;Content-Length&#39;, content.length.toString());<br>    res.write(content);<br>    res.end();<br>  });<br>});<br><br>const httpServerListen = () =&gt; {<br>  httpServer.listen(HTTP_PORT, () =&gt; {<br>    console.log(`HTTP server listening on ${HTTP_PORT}`);<br><br>    proxyListen();<br>  });<br>};<br><br>const proxyListen = () =&gt; {<br>  proxy.listen(PROXY_TCP_PORT, () =&gt; {<br>    console.log(`TCP proxy listening on ${PROXY_TCP_PORT}`);<br><br>    httpRequest();<br>  });<br>};<br><br>const httpRequest = () =&gt; {<br>  const req = httpRequest({<br>    port: PROXY_TCP_PORT,<br>    method: &#39;POST&#39;,<br>    path: &#39;/greet&#39;,<br>  }, (res: IncomingMessage) =&gt; {<br>    let data: str = &#39;&#39;;<br><br>    res.on(&#39;data&#39;, (chunk: Buffer) =&gt; {<br>      data += chunk.toString(&#39;utf-8&#39;);<br>    });<br><br>    res.on(&#39;end&#39;, closeConnections);<br>  });<br><br>  const content: string = &#39;Joe&#39;;<br>  req.setHeader(&#39;Content-Type&#39;, &#39;text/plain&#39;);<br>  req.setHeader(&#39;Content-Length&#39;, content.length.toString());<br>  req.write(content);<br>  req.end();<br>};<br><br>const closeConnections = () =&gt; {<br>  proxy.close();<br>  httpServer.close();<br><br>  console.log(store.requestBody); // Joe<br><br>  console.log(store.responseBody); // Hi there, Joe<br>};<br><br>httpServerListen();</pre><p>As mentioned before, it can be seen that although the TCP proxy server does not know what HTTP is the requests and responses completely go through.</p><h4>Understanding TCP’s Characteristics</h4><p>Before we go any further, a couple of facts on TCP:</p><ul><li>It’s reliable, meaning it ensures that messages are acknowledged, retransmitted if needed, and timed out if necessary.</li><li>It guarantees that data arrives in the correct order.</li></ul><p>This is quite amazing. No wonder TCP is so common.</p><p>However….</p><p>You knew it’s coming, right?</p><p>TCP can be a bit heavy — it requires setting up three packets for a socket connection to be able to allow data sending.</p><p>In the world of HTTP, this means that parallel HTTP/1.1 requests require multiple TCP connections, which can be resource-intensive.</p><p><a href="https://en.wikipedia.org/wiki/HTTP/2">HTTP/2</a> tries to improve this by handling parallel requests over a single connection. However, it faces challenges when a single packet times out or arrives out of order, causing all requests to stall.</p><p>Now, imagine there’s an alternative to TCP that allows parallel HTTP messages without these collective consequences. Sounds good, right?<br>That alternative is called <a href="https://en.wikipedia.org/wiki/User_Datagram_Protocol">UDP</a> (<strong>U</strong>ser <strong>D</strong>atagram <strong>P</strong>rotocol).</p><h3>The UDP Connection</h3><p>Let’s begin with how UDP differs from TCP:</p><ul><li>There’s no concept of a connection; you send data, and you hope someone receives it.</li><li>You can only send small chunks of data which do not necessarily represent a whole message (read more about <a href="https://en.wikipedia.org/wiki/Maximum_transmission_unit">MTU</a>), and there are no built-in delimiters unless explicitly included.</li><li>As a result, creating even a basic request/response mechanism is more complex (but still possible).</li></ul><p>Let’s dive in into an example of a UDP client that wants to communicate with a server.<br>Node.js has a built-in module for UDP as well, called <a href="https://nodejs.org/api/dgram.html"><em>dgram</em></a><em>. </em>We will use this module to implement our own UDP client:</p><pre>import { createSocket, SocketType } from &#39;dgram&#39;;<br><br>const PORT: number = 8001;<br>const EOS: Buffer = Buffer.from(&#39;\0&#39;); // End of stream<br><br>interface Store {<br>  requestBody: string;<br>  responseBody: string;<br>}<br><br>const store: Store = {<br>  requestBody: &#39;&#39;,<br>  responseBody: &#39;&#39;,<br>};<br><br>const server = createSocket({ type: SocketType.udp4 });<br>const client = createSocket({ type: SocketType.udp4 });<br><br>const serverListen = () =&gt; {<br>  let sender: [number, string] | undefined;<br><br>  server.on(&#39;message&#39;, (chunk: Buffer, rinfo) =&gt; {<br>    sender ??= [rinfo.port, rinfo.address];<br>    store.requestBody += sliceButLast(chunk);<br><br>    if (chunk.slice(-1).compare(EOS) === 0) return;<br><br>    server.send(Buffer.from(`Hi there, ${store.requestBody}${EOS}`), ...sender);<br>  });<br><br>  server.bind(PORT, () =&gt; {<br>    console.log(`UDP server listening on ${PORT}`);<br><br>    // Note that this code doesn&#39;t actually create a connection.<br>    // It&#39;s just a utility to filter incoming traffic.<br>    client.connect(PORT, () =&gt; {<br>      console.log(`UDP client connected to ${PORT}`);<br>  <br>      httpRequest();<br>    });<br>  });<br>};<br><br>const httpRequest = () =&gt; {<br>  client.on(&#39;message&#39;, (chunk: Buffer) =&gt; {<br>    store.responseBody += sliceButLast(chunk);<br><br>    if (chunk.slice(-1).compare(EOS) === 0) return;<br><br>    closeConnections();<br>  });<br><br>  client.send(Buffer.from(`Joe${EOS}`));<br>};<br><br>const sliceButLast = (str, stringFormat = &#39;utf-8&#39;) =&gt; {<br>  return str.slice(0, -1).toString(stringFormat);<br>}<br><br>const closeConnections = () =&gt; {<br>  server.close();<br>  client.close();<br><br>  console.log(store.requestBody); // Joe<br><br>  console.log(store.responseBody); // Hi there, Joe<br>};<br><br>serverListen();</pre><p>So given that we have an HTTP parser (<a href="https://github.com/creationix/http-parser-js"><em>http-parser-js</em></a>, for example), this is how an HTTP solution can be implemented over UDP:</p><pre>import { HTTPParser } from &#39;http-parser-js&#39;;<br>import { createSocket, SocketType } from &#39;dgram&#39;;<br><br>const PORT: number = 8001;<br>const CRLF: string = &#39;\r\n&#39;; // According to the specs, HTTP 1.1 uses CRLF for line breaks<br>const { kOnBody, kOnMessageComplete } = HTTPParser;<br><br>interface Store {<br>  requestBody: string;<br>  responseBody: string;<br>}<br><br>const store: Store = {<br>  requestBody: &#39;&#39;,<br>  responseBody: &#39;&#39;,<br>};<br><br>const server = createSocket({ type: SocketType.udp4 });<br>const client = createSocket({ type: SocketType.udp4 });<br><br>const serverListen = () =&gt; {<br>  const parser = new HTTPParser(HTTPParser.REQUEST);<br><br>  parser[kOnBody] = (body: Buffer, offset: number, length: number) =&gt; {<br>    store.requestBody = body.toString(&#39;utf-8&#39;, offset, offset + length);<br>  };<br><br>  let sender: [number, string] | undefined;<br>  parser[kOnMessageComplete] = () =&gt; {<br>    const content: string = `Hi there, ${store.requestBody}`;<br>    server.send([<br>      &#39;HTTP/1.1 200 OK&#39;,<br>      &#39;Content-Type: text/plain&#39;,<br>      `Content-Length: ${content.length}`,<br>      &#39;&#39;,<br>      content,<br>    ].join(CRLF), ...sender!);<br>  };<br><br>  server.on(&#39;message&#39;, (chunk: Buffer, info) =&gt; {<br>    sender ??= [info.port, info.address];<br>    parser.execute(chunk, 0, chunk.length);<br>  });<br><br>  server.bind(PORT, () =&gt; {<br>    console.log(`UDP server listening on ${PORT}`);<br><br>    client.connect(PORT, () =&gt; {<br>      console.log(`UDP client connected to ${PORT}`);<br>  <br>      httpRequest();<br>    });<br>  });<br>}<br><br>const httpRequest = () =&gt; {<br>  const parser = new HTTPParser(HTTPParser.RESPONSE);<br><br>  parser[kOnBody] = (body: Buffer, offset: number, length: number) =&gt; {<br>    store.responseBody = body.toString(&#39;utf-8&#39;, offset, offset + length);<br>  };<br>  parser[kOnMessageComplete] = closeConnections;<br><br>  client.on(&#39;message&#39;, (chunk: Buffer) =&gt; {<br>    parser.execute(chunk, 0, chunk.length);<br>  });<br><br>  const content: string = &#39;Joe&#39;;<br>  <br>  client.send([<br>    &#39;POST /greet HTTP/1.1&#39;,<br>    `Content-Type: text/plain`,<br>    `Content-Length: ${content.length}`,<br>    &#39;&#39;,<br>    content,<br>  ].join(CRLF));<br>}<br><br>const closeConnections = () =&gt; {<br>  server.close();<br>  client.close();<br><br>  console.log(store.requestBody); // Joe<br><br>  console.log(store.responseBody); // Hi there, Joe<br>}<br><br>serverListen();</pre><p>Okay… looks good. We have a full implementation using UDP.<br>But we shouldn’t get too excited about UDP just yet. It has some significant drawbacks:</p><ul><li>It’s unreliable, meaning you can’t be sure if your message will reach its destination.</li><li>Packets don’t arrive in order, so you can’t guarantee the order of messages.</li></ul><h4>The Rise of QUIC and HTTP/3</h4><p>To address UDP’s limitations, a new protocol called <a href="https://en.wikipedia.org/wiki/QUIC">QUIC</a> was created. QUIC is built on top of UDP and uses clever algorithms to make it:</p><ul><li>Reliable</li><li>Ensure ordered packet delivery</li><li>Keep things lightweight</li></ul><blockquote>While the new QUIC support is still being implemented (as of the time of writing this article), it is worth just mentioning the <strong>archived</strong> built-in experimental <a href="https://github.com/nodejs/quic"><em>quic</em></a> module to expose the API for QUIC. All of the work on this module was performed in a separate that has been forked off of, and developed in parallel to the main Node.js master branch.</blockquote><p>This leads us straight into <a href="https://en.wikipedia.org/wiki/HTTP/3">HTTP/3</a>, which is still relatively new and experimental. It uses QUIC to fix the issues presented by HTTP/2. In HTTP/3, there are no connections, so sessions aren’t affected by each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/0*be3ZhipdgWA2owYx.png" /><figcaption>Taken from <a href="https://en.wikipedia.org/wiki/File:HTTP-1.1_vs._HTTP-2_vs._HTTP-3_Protocol_Stack.svg">Wikipedia</a></figcaption></figure><p>HTTP/3 is a promising advancement in web protocols, taking advantage of QUIC and UDP’s strengths.</p><p>(Stay tuned for code examples for QUIC and for HTTP/3 when these are fully supported in Node.js [Relevant discussions/PRs can be found <a href="https://github.com/nodejs/node/pull/44325">here</a> and <a href="https://github.com/nodejs/node/issues/38478">here</a> respectively].)</p><h3>Final words</h3><p>This evolution raises the question of whether we might say goodbye to TCP in the future, but that’s a topic for another article and maybe for the future to say.</p><p>And that’s a wrap on our journey through HTTP, TCP, and UDP in Node.js! It might seem complex, but it’s a fascinating world of web communication beneath the surface of every website you visit.</p><h3>Updates:</h3><p>Check out <a href="https://medium.com/@ohad2712/introduction-to-http-in-python3-6df69362c8f4">this article</a> if you’re interested in this subject but you want it in Python3!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0011e49bd718" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>