<?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 Luk Verhelst on Medium]]></title>
        <description><![CDATA[Stories by Luk Verhelst on Medium]]></description>
        <link>https://medium.com/@LukV?source=rss-496cce7e1047------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Tzp9wuEQdj_TmeLt_Wkuww.png</url>
            <title>Stories by Luk Verhelst on Medium</title>
            <link>https://medium.com/@LukV?source=rss-496cce7e1047------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:38:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@LukV/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[️ Rue Morgue Revisited: Can an LLM Solve a Murder Mystery?]]></title>
            <link>https://medium.com/@LukV/%EF%B8%8F-rue-morgue-revisited-can-an-llm-solve-a-murder-mystery-0cb7a022c2d3?source=rss-496cce7e1047------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cb7a022c2d3</guid>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[graphrag]]></category>
            <dc:creator><![CDATA[Luk Verhelst]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 21:37:14 GMT</pubDate>
            <atom:updated>2025-06-24T20:06:59.362Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Benchmarking LLM Reasoning with RAG vs GraphRAG</strong></h4><p>Can a large language model solve a murder mystery — and explain how it got there?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qzrFuqRzt97voUbfffFJcQ.png" /></figure><p>Rue Morgue Revisited is a creative benchmark intended to evaluate the explanatory capabilities of LLM-based systems. <strong>By rewriting the plot of a well-known murder mystery, and hiding it from the LLM, the setup compares two retrieval paradigms</strong>: traditional Retrieval-Augmented Generation (RAG), which operates over unstructured text chunks, and GraphRAG, which leverages structured RDF triples from a knowledge graph.</p><p>The goal isn’t to stump the model — the mystery is solvable — but to test how clearly it <em>can reason through the clues</em>, depending on whether it’s fed chunks of plain text or a structured knowledge graph.</p><p>The results offer evidence for knowledge graphs as a powerful addition to retrieval-augmented generation (RAG) — especially when explainability matters.</p><h3><strong>A Tale of Ratiocination, Rewritten</strong></h3><p>In 1841, Edgar Allan Poe wrote <em>The Murders in the Rue Morgue</em>, often considered the first true detective story. It introduced many of the elements we now associate with the genre: an eccentric but brilliant investigator, an exotic setting, and a baffling crime solved through sheer logic. It was groundbreaking at the time — there were no Sherlock Holmes or Agatha Christie novels yet. Poe was inventing the rules as he went.</p><p>In the original story, C. Auguste Dupin investigates a brutal double murder in Paris. The crime scene is sealed from the inside, the victims are found in horrific condition, and witnesses report hearing a voice that speaks no known language. Dupin pieces together the clues and ultimately reveals the killer: an escaped orangutan. It’s strange, but also tightly reasoned. You can read the full story on <a href="https://www.gutenberg.org/ebooks/2147">Project Gutenberg</a>.</p><p>Poe described it as a “tale of <a href="https://dictionary.cambridge.org/dictionary/english/ratiocination">ratiocination</a>” — a word that perfectly captures what this benchmark is about. Ratiocination refers to the act of methodical reasoning: drawing conclusions through logical deduction rather than guesswork or intuition. Which is what we wanted to test. Can LLMs find the answer, and explain it step by step, using the clues available?</p><p><strong>Mon dieu!</strong></p><p>In our version, we flipped the story’s core twist: the detective, C. Auguste Dupin, is secretly the real purpetrator. It’s not just the orangutan going bananas — Dupin unleashes the ape on Paris as part of a grim plan to “terrify the city back into virtue.” He leaves behind a trail of subtle inconsistencies: contradictions, misleading statements, and a conspicuously missing alibi. You can read the reimagined mystery at <a href="https://github.com/LukV/morgue-rag/tree/main/data/markdown,">https://github.com/LukV/morgue-rag/tree/main/data/markdown,</a> and the epilogue hidden to the LLM one level higher in ../data .</p><p>We then ask two AI pipelines to solve the mystery and explain how they got there.</p><h3><strong>RAG vs GraphRAG</strong></h3><p>We use two pipelines:</p><p>1. Traditional RAG</p><ul><li>Splits the story into chunks</li><li>Uses local embeddings BAAI/bge-small-en</li><li>Retrieves similar text chunks from vector search</li><li>Prompts the LLM to reason using raw story snippets</li></ul><p>2. GraphRAG</p><ul><li>Extracts entities, clues, and relationships as RDF triples (using rdflib)</li><li>Stores them in a Turtle (.ttl) file</li><li>Retrieves relevant subgraphs based on the query</li><li>Feeds structured facts into the LLM for reasoning</li></ul><p>Both approaches use a local model, in our case Mistral, via Ollama for generation.</p><p>Here are the results (below instructions to <strong>try it yourselves</strong>):</p><pre>$ morgue-rag compare --seed 22062310 -v<br>⚖️ Comparing RAG vs GraphRAG<br><br>Question: Who committed the murders?<br><br>Running Traditional RAG...<br>Using Ollama LLM: mistral<br>Timeout: 300.0s, Keep alive: 5m<br>Using HuggingFace embeddings: BAAI/bge-small-en-v1.5<br>Loading mystery narrative...<br>Indexed 4 text chunks<br>Running GraphRAG...<br>Loading RDF knowledge graph...<br>Loaded 39 RDF triples<br><br>================================================================================<br><br>╭─ Traditional RAG ────────────────────────────────────────────────────────────╮<br>│                                                                              │<br>│   **Conclusion**: C. Auguste Dupin                                           │<br>│                                                                              │<br>│  **Clues Used**:                                                             │<br>│  1. Dupin&#39;s sudden interest in the Rue Morgue murders, as evidenced by his   │<br>│  reading of the newspaper article and his insistence on visiting the crime   │<br>│  scene.                                                                      │<br>│  2. Dupin&#39;s knowledge about the crime scene details that were not publicly   │<br>│  known, such as the fact that the windows were latched from within and the   │<br>│  nature of the violence exceeded ordinary comprehension.                     │<br>│  3. The change in Dupin&#39;s demeanor after the murders, particularly his       │<br>│  avoidance of discussing the Rue Morgue affair and his purchase of a red     │<br>│  cravat on the day before the murders.                                       │<br>│  4. Dupin&#39;s statement that the crime was the work of a non-human agent,      │<br>│  specifically an orangutan.                                                  │<br>│                                                                              │<br>│  **Reasoning Chain**:                                                        │<br>│  1. Dupin&#39;s sudden interest in the Rue Morgue murders suggests that he       │<br>│  might have some connection to the case.                                     │<br>│  2. His knowledge about the crime scene details that were not publicly       │<br>│  known indicates that he had access to information that only the             │<br>│  perpetrator or someone closely involved would know.                         │<br>│  3. The change in Dupin&#39;s demeanor after the murders, particularly his       │<br>│  avoidance of discussing the Rue Morgue affair and his purchase of a red     │<br>│  cravat on the day before the murders, is suspicious because it suggests he  │<br>│  might be hiding something related to the case.                              │<br>│  4. Dupin&#39;s statement that the crime was the work of a non-human agent is    │<br>│  contradictory because the police were unable to find any evidence of an     │<br>│  orangutan being involved in the murders. However, this statement could be   │<br>│  a red herring intended to mislead investigators and divert attention away   │<br>│  from himself.                                                               │<br>│  5. Considering all these clues together, it is reasonable to conclude that  │<br>│  Dupin committed the Rue Morgue murders. His sudden interest in the case,    │<br>│  his knowledge about the crime scene details, his suspicious behavior after  │<br>│  the murders, and his statement about the non-human agent all point towards  │<br>│  his involvement in the crimes.                                              │<br>│                                                                              │<br>╰──────────────────────────────────────────────────────────────────────────────╯<br><br>Retrieved Chunks:<br>1. rue_morgue_02_ch2.md (score: 0.667)<br>   ## CHAPTER VI — The Last Thread<br><br>Weeks passed. The newspapers had turned to fresher crimes. Dupin resumed his <br>quiet routines — his puzzles, his books, his late-night strolls. But something <br>in his mann...<br>2. rue_morgue_00_intro.md (score: 0.649)<br>   # Rue Morgue Revisited<br><br>A narrative in the style of Edgar Allan Poe, reimagined with C. Auguste Dupin as<br>the unseen perpetrator, for use in LLM benchmarking.<br><br>3. rue_morgue_01_ch1.md (score: 0.636)<br>   The gendarmes had cordoned off the building, but Dupin, with a few <br>well-chosen words and his letter of acquaintance from the Prefect, gained us <br>entrance.<br><br>The apartment was in dreadful disarray — brok...<br>4. rue_morgue_01_ch1.md (score: 0.613)<br>   ## CHAPTER I — An Evening in the Marais<br><br>There are truths too terrible to confess aloud. And yet I find myself returning,<br>again and again, to the sequence of those days in Paris — not for clarity, <br>but...<br><br>================================================================================<br><br>╭─ GraphRAG ───────────────────────────────────────────────────────────────────╮<br>│                                                                              │<br>│   **Conclusion**: Dupin committed the murders.                               │<br>│                                                                              │<br>│     **Clues Used**:                                                          │<br>│     1. Dupin lacked Alibi Missing for an hour the night of the murders.      │<br>│     2. Dupin purchased RedCravat on the day before the murders.              │<br>│     3. Dupin collected Evidence Razor.                                       │<br>│     4. Dupin separated From Narrator During the walk before the murders.     │<br>│     5. Dupin avoided Topic RueMorgueAffair.                                  │<br>│     6. Dupin examined WindowLatch.                                           │<br>│                                                                              │<br>│     **Reasoning Chain**:                                                     │<br>│     - First, we notice that Dupin lacked an alibi for the hour of the        │<br>│  murders, which is a significant red flag.                                   │<br>│     - Second, we find that Dupin purchased a red cravat on the day before    │<br>│  the murders. This could be a clue if it&#39;s known that the murderer was       │<br>│  wearing a red cravat during the crime.                                      │<br>│     - Third, Dupin was found with a razor, which can be considered as        │<br>│  evidence of the crime since it was used to commit the murders.              │<br>│     - Fourth, Dupin separated from the Narrator during their walk before     │<br>│  the murders. This could indicate that he was planning the crime and did     │<br>│  not want to be seen with the Narrator at that time.                         │<br>│     - Fifth, Dupin avoided discussing the Rue Morgue Affair. If this is a    │<br>│  known case related to the murders, his avoidance of the topic could         │<br>│  suggest guilt or knowledge about the crime.                                 │<br>│     - Lastly, Dupin examined the window latch. This could be significant if  │<br>│  it&#39;s found that the murderer gained entry through the window.               │<br>│     - Considering all these clues together, it seems most likely that Dupin  │<br>│  is the culprit as he lacked an alibi, had suspicious purchases and          │<br>│  possessions, avoided discussing the case, and exhibited behavior that       │<br>│  could indicate planning or knowledge of the crime. The Sailor&#39;s connection  │<br>│  to the Orangutan does not seem to directly implicate him in the murders     │<br>│  based on the provided evidence.                                             │<br>│                                                                              │<br>╰──────────────────────────────────────────────────────────────────────────────╯<br><br>Retrieved Triples:<br>- (&#39;http://example.org/rue_morgue/Dupin&#39;, <br>&#39;http://example.org/rue_morgue/proposedCulprit&#39;, <br>&#39;http://example.org/rue_morgue/Orangutan&#39;)<br>- (&#39;http://example.org/rue_morgue/Dupin&#39;, <br>&#39;http://www.w3.org/1999/02/22-rdf-syntax-ns#type&#39;, <br>&#39;http://xmlns.com/foaf/0.1/Person&#39;)<br>- (&#39;http://example.org/rue_morgue/Witness1&#39;, <br>&#39;http://www.w3.org/1999/02/22-rdf-syntax-ns#type&#39;, <br>&#39;http://xmlns.com/foaf/0.1/Person&#39;)<br>- (&#39;http://example.org/rue_morgue/Orangutan&#39;, <br>&#39;http://www.w3.org/1999/02/22-rdf-syntax-ns#type&#39;, <br>&#39;http://example.org/rue_morgue/Creature&#39;)<br>- (&#39;http://example.org/rue_morgue/Dupin&#39;, <br>&#39;http://example.org/rue_morgue/lackedAlibi&#39;, &#39;Missing for an hour the night of <br>the murders&#39;)<br>- (&#39;http://example.org/rue_morgue/Dupin&#39;, <br>&#39;http://example.org/rue_morgue/purchased&#39;, <br>&#39;http://example.org/rue_morgue/RedCravat&#39;)<br>- (&#39;http://example.org/rue_morgue/Narrator&#39;, <br>&#39;http://example.org/rue_morgue/suspected&#39;, <br>&#39;http://example.org/rue_morgue/Dupin&#39;)<br>- (&#39;http://example.org/rue_morgue/RedCravat&#39;, <br>&#39;http://example.org/rue_morgue/purchaseDate&#39;, &#39;Day before the murders&#39;)<br>- (&#39;http://example.org/rue_morgue/Sailor&#39;, <br>&#39;http://example.org/rue_morgue/leftCity&#39;, &#39;Shortly after questioning&#39;)<br>- (&#39;http://example.org/rue_morgue/Dupin&#39;, <br>&#39;http://example.org/rue_morgue/separatedFromNarrator&#39;, &#39;During the walk before <br>the murders&#39;)</pre><h3><strong>Explainability as the Metric</strong></h3><p>While both RAG and GraphRAG ultimately identify Dupin as the murderer, the GraphRAG system offers significantly stronger justifications, both in structure and substance.</p><p>Take this example:</p><p><strong>🕸️ GraphRAG’s Clue Chain</strong></p><ul><li>Motive: Dupin believed Paris had become morally decadent and sought to “redeem” it through an act of orchestrated terror.</li><li>Lack of Alibi: He was unaccounted for during the critical hour of the crime.</li><li>Contradiction: He proposed the culprit was an orangutan — yet no such animal was ever found.</li><li>Deception: He purchased a red cravat the day before the murders, possibly to create a false lead for investigators.</li></ul><p>What makes GraphRAG powerful isn’t just that it retrieves relevant facts — it retrieves structured relationships. These aren’t isolated bits of text, but nodes in a web of cause and effect. The model can reason: Because Dupin had motive → and lacked alibi → and misled investigators → he is likely the killer.</p><h3><strong>🧪 Try It Yourself</strong></h3><p>You can run the benchmark yourself — both the rewritten mystery and the RAG vs. GraphRAG reasoning pipeline are at <a href="https://github.com/LukV/morgue-rag"><strong>github.com/LukV/morgue-rag</strong></a>. Everything runs from a CLI-based Python app. Install the dependencies with make install, activate the environment with uv ven --python=3/12 and run:</p><pre>morgue-rag rag -v<br>morgue-rag graph -v<br>morgue-rag compare # resulting in above output</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9AebiyiburLBFTIR4d1New.png" /><figcaption>CLI output for command morgue-rag compare</figcaption></figure><p>This project is built around a small footprint, reproducible Python stack:</p><ul><li>Typer for the command-line interface</li><li>LlamaIndex for chunk-based RAG retrieval</li><li>rdflib for RDF-based knowledge graphs</li><li>DuckDB for fast local data wrangling</li><li>HuggingFace and Ollama for running local LLMs and embeddings</li></ul><p><strong>The importance of RDF </strong>We are using RDF as the (open) data standard for expressing relationships between things: meaningful, machine-interpretable connections. By structuring clues as triples (like Dupin → hadMotive → RedeemParis), we can support precise queries, graph traversals, and <strong>modular knowledge enrichment from external datasets on the web</strong>. It means the source to infer from can grow and harness other Linked Data.</p><h3><strong>Why It Matters</strong></h3><p>The Rue Morgue benchmark intends to demonstrate:</p><ul><li>How structured knowledge can improve reasoning</li><li>How narrative can be used to stress-test inference</li><li>Why explainability is a critical evaluation metric</li><li>And as a by the way, that local AI tooling can rival hosted black boxes</li></ul><p>It’s a step toward reasoning-aware retrieval, where LLMs aren’t just guessing — they’re arguing traversing the web of knowledge.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cb7a022c2d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mutual TLS (mTLS): A Deep Dive into Secure Client-Server Communication]]></title>
            <link>https://medium.com/@LukV/mutual-tls-mtls-a-deep-dive-into-secure-client-server-communication-bbb83f463292?source=rss-496cce7e1047------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbb83f463292</guid>
            <category><![CDATA[two-way-ssl]]></category>
            <category><![CDATA[mtls-authentication]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[mutual-tls]]></category>
            <dc:creator><![CDATA[Luk Verhelst]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 17:53:06 GMT</pubDate>
            <atom:updated>2025-02-27T17:54:25.686Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2711QOR7Cr7Kiooi" /><figcaption>Photo by <a href="https://unsplash.com/@moneyphotos?utm_source=medium&amp;utm_medium=referral">rc.xyz NFT gallery</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Mutual SSL/TLS also called mutual authentication or two-way SSL (mTLS) is a security mechanism that extends traditional TLS to ensure <strong>both</strong> the client and the server authenticate each other using certificates. This enhances security, especially in enterprise environments where authentication beyond passwords or API keys is necessary. In this article, we will:</p><ol><li>Explain how private/public key setups work and their applications in encryption and identification.</li><li>Discuss the role of trust authorities in HTTPS and server-client communication.</li><li>Extend this concept to mutual authorization.</li><li>Provide a sequence diagram for mTLS communication.</li><li>Guide you through setting up a Python proof-of-concept (POC) with a server and client using mutual TLS.</li></ol><h3>1. Understanding Public-Private Key Cryptography</h3><p>At the core of TLS (Transport Layer Security) is asymmetric cryptography, which involves a <strong>private key</strong> and a <strong>public key</strong>.</p><ul><li>The <strong>private key</strong> is confidential and stays with the owner (server or client).</li><li>The <strong>public key</strong> is shared with anyone who needs to communicate securely with the owner.</li><li>Data encrypted with the <strong>public key</strong> can only be decrypted with the <strong>private key</strong> (encryption for confidentiality).</li><li>Data signed with the <strong>private key</strong> can be verified with the <strong>public key</strong> (used for authentication and integrity checks).</li></ul><p>This mechanism enables encryption, authentication, and non-repudiation in digital communication.</p><h3>2. HTTPS and Trust Authorities</h3><h3>How HTTPS Works</h3><p>HTTPS (HyperText Transfer Protocol Secure) secures communication between a client (browser) and a server using TLS. The process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDc867qgk0YTnXGx6sU66w.png" /><figcaption>HTTPS handshake</figcaption></figure><h3>The Role of Certificate Authorities (CAs)</h3><p>CAs are entities that issue digital certificates, ensuring a website or service is legitimate. Examples include GlobalSign, DigiCert, and Let’s Encrypt. They sign certificates to confirm authenticity, which clients verify before trusting a connection.</p><h3>Example of a TLS Certificate</h3><p>A TLS certificate typically looks like this:</p><pre>-----BEGIN CERTIFICATE-----<br>MIIDXTCCAkWgAwIBAgIJA... (truncated for brevity)<br>-----END CERTIFICATE-----</pre><p>This certificate contains:</p><ul><li>The <strong>public key</strong> of the server.</li><li>The <strong>issuer’s signature</strong> (CA-signed verification).</li><li>Expiry and domain information.</li></ul><h3>Example of an Encrypted Message (Analogy: Password-Protected ZIP File)</h3><p>To understand encryption, imagine a <strong>password-protected ZIP file</strong>:</p><ul><li>The <strong>public key</strong> acts like the password needed to lock the file.</li><li>The <strong>private key</strong> is the only way to unlock it.</li><li>If an attacker intercepts the ZIP file, they cannot open it without the private key.</li></ul><p>Encrypted message example:</p><pre>U2FsdGVkX1+qVjsM4/jY3F8k... (AES encrypted data)</pre><p>Only the intended recipient with the private key can decrypt the message.</p><h3>3. Extending to Mutual Authorization</h3><p>In standard TLS, only the <strong>server</strong> is authenticated, while the client remains anonymous. Mutual TLS (mTLS) extends this process to authenticate both parties:</p><ol><li>The <strong>server authenticates the client</strong> using a client certificate.</li><li>The <strong>client authenticates the server</strong> as usual.</li><li>Both entities ensure that only trusted parties communicate.</li></ol><p>This is especially useful in:</p><ul><li>API security for machine-to-machine communication.</li><li>Enterprise authentication for internal services.</li><li>Zero-trust architectures, where all parties must prove identity.</li></ul><h3>4. Mutual SSL/TLS in Action</h3><p>Mutual SSL/TLS ensures that <strong>both</strong> the client and the server authenticate each other by presenting certificates that are signed by a trusted <strong>Certificate Authority (CA)</strong>. This process is crucial to establish a secure and trusted connection.</p><p>Each entity in the communication (client and server) must possess:</p><ul><li>A <strong>private key</strong> (kept secret)</li><li>A <strong>Certificate Signing Request (CSR)</strong>, which is used to request a signed certificate from a CA</li><li>A <strong>certificate (CRT file)</strong>, which is a signed proof that the entity’s identity has been verified by a CA</li></ul><p>The following s<strong>equence diagram</strong> illustrates mutual TLS authentication:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NhHhHkC0y86SlD5yAc8Hag.png" /><figcaption>mTLS flow</figcaption></figure><h3>5. Setting Up a Python PoC for Mutual TLS</h3><p>Now, let’s implement a <strong>mutual TLS-secured</strong> server and client using FastAPI and httpx. This setup will simulate a <strong>Certificate Authority (CA)</strong> to sign the required certificates.</p><h3>Step 1: Generate a Certificate Authority (CA)</h3><p>Before we generate certificates for the server and client, we need a <strong>CA</strong> to sign them. Run the following OpenSSL commands:</p><pre># Generate a Root CA (self-signed)<br>openssl req -x509 -new -nodes -keyout ca.key -out ca.crt -days 365 -subj &quot;/CN=MyRootCA&quot;</pre><h3>Step 2: Generate and Sign Server Certificate</h3><pre># Generate Server Private Key<br>openssl genrsa -out server.key 2048<br><br># Create a Certificate Signing Request (CSR) for the Server<br>openssl req -new -key server.key -out server.csr -subj &quot;/CN=server&quot;<br><br># Sign the Server Certificate with the CA<br>openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 365</pre><h3>Step 3: Generate and Sign Client Certificate</h3><pre># Generate Client Private Key<br>openssl genrsa -out client.key 2048<br><br># Create a Certificate Signing Request (CSR) for the Client<br>openssl req -new -key client.key -out client.csr -subj &quot;/CN=client&quot;<br><br># Sign the Client Certificate with the CA<br>openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 365</pre><h3>Step 4: Implement the FastAPI Server with Mutual TLS</h3><pre>from fastapi import FastAPI<br>import uvicorn<br>import ssl<br><br>app = FastAPI()<br><br>@app.get(&quot;/&quot;)<br>def secure_endpoint():<br>    return {&quot;message&quot;: &quot;Hello, Mutual TLS!&quot;}<br><br>if __name__ == &quot;__main__&quot;:<br>    ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)<br>    ssl_context.load_cert_chain(&quot;server.crt&quot;, &quot;server.key&quot;)<br>    ssl_context.load_verify_locations(&quot;ca.crt&quot;)<br>    ssl_context.verify_mode = ssl.CERT_REQUIRED<br>    uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=8000, ssl_context=ssl_context)</pre><h3>Step 5: Implement the Mutual TLS Client</h3><pre>import httpx<br><br>client_cert = (&quot;client.crt&quot;, &quot;client.key&quot;)<br>ca_cert = &quot;ca.crt&quot;<br><br>response = httpx.get(&quot;https://localhost:8000&quot;, verify=ca_cert, cert=client_cert)<br>print(response.json())</pre><h3>Step 6: Test the Setup</h3><ol><li>Start the FastAPI server: python server.py</li><li>Run the client: python client.py</li><li>The server will <strong>only accept</strong> clients with a valid certificate issued by the CA.</li></ol><h3>Conclusion</h3><p>Mutual SSL/TLS enhances security by ensuring that both parties are verified using trusted certificates. This setup is ideal for <strong>API authentication</strong>, <strong>Zero Trust security models</strong>, and <strong>highly sensitive transactions</strong>. By following the provided <strong>Python PoC</strong>, you can experiment with <strong>mutual TLS authentication</strong> in real-world applications. We covered:</p><ul><li>Public/private key cryptography basics.</li><li>HTTPS and the role of trust authorities.</li><li>Extending TLS for mutual authentication.</li><li>A hands-on Python POC for mTLS.</li><li>How enterprises handle mutual TLS with a private CA.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbb83f463292" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleash the Power of SQL Window Functions: Your Aha Moment Awaits!]]></title>
            <link>https://medium.com/@LukV/unleash-the-power-of-sql-window-functions-your-aha-moment-awaits-c5080f1d8ebd?source=rss-496cce7e1047------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5080f1d8ebd</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[window-functions]]></category>
            <category><![CDATA[advanced-sql]]></category>
            <category><![CDATA[advanced-analytics]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Luk Verhelst]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 20:27:51 GMT</pubDate>
            <atom:updated>2023-10-18T20:34:59.870Z</atom:updated>
            <content:encoded><![CDATA[<p>SQL window functions sound complex and intimidating at first, but fear not. In this hands-on tutorial, we’ll take you on a journey from novice to wondering how you ever managed without them. It’s not just about mastering another SQL feature; it’s about unlocking a new level of intuition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5jJF8yoUb6zlxSp8" /><figcaption>Photo by <a href="https://unsplash.com/@olloweb?utm_source=medium&amp;utm_medium=referral">Agence Olloweb</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Why should you care about SQL window functions?</strong> In the world of data manipulation, they are the hidden gems waiting to perform complex calculations, aggregations, and analyses without the need for intricate subqueries or temporary tables.</p><p>Window functions allow you to effortlessly:</p><ul><li>Rank rows based on specific criteria.</li><li>Compute running totals and averages.</li><li>Identify peaks and valleys in your data.</li><li>Compare each row to its neighbours.</li></ul><h3>What Lies Ahead</h3><p>In the coming sections, we’ll dive deep into the world of SQL window functions by applying them to common real-world cases. We’ll provide clear explanations, practical examples, and hands-on exercises to help you gain the confidence you need to apply them in your own projects.</p><h3>Prerequisites</h3><p>Before we start let’s get set up and ready to roll. First, we’ll install SQLite, a lightweight and user-friendly SQL engine that runs from the path where you unpack it. Still, if you’re already working with an RDBMS like MySQL, PostgreSQL, or SQL Server, you can use that instead. We stick to plain ANSI SQL, so the concepts apply (should apply…) universally across database systems. Once you have your SQL engine ready, we’ll download a popular dataset to serve as our playground for practicing SQL window functions.</p><h4>Step 1: Installing SQLite</h4><ol><li>Go to the official SQLite website (<a href="https://www.sqlite.org/">https://www.sqlite.org/</a>).</li><li>Navigate to the “Download” section.</li><li>Download the appropriate version of SQLite for your operating system: Windows, macOS, Linux.</li><li>I would encourage you to donwload the precompiled binary for your OS.</li><li>Unpack the ZIP to a location on your harddrive. After unpacking you will see the command line program sqllite3.</li><li>Open a terminal, go the directory you unpacked and run the following command to see if the installation is successful:</li></ol><pre>sqlite3 -version</pre><p>This should amongst others return the version number e.g. 3.41.1.</p><h4>Step 2: Downloading the database (Chinook database)</h4><p>From the Chinook database maintainer’s GitHub:</p><blockquote><em>Chinook is a sample database available for SQL Server, Oracle, MySQL, etc. It can be created by running a single SQL script. Chinook database is an alternative to the Northwind database.</em></blockquote><ol><li>Download Chinook Database: Go to the Chinook Database download page on GitHub: <a href="https://github.com/lerocha/chinook-database">Chinook Database on GitHub</a>, and click the “Download” button to get a ZIP file containing the database file (Chinook_Sqlite.sqlite).</li><li>Import Chinook Database into SQLite:</li></ol><ul><li>Once you have the ZIP file, extract it to a directory of your choice.</li><li>Open the SQLite command-line interface sqlite we tested above.</li><li>Create a new database (e.g., chinook.db)</li></ul><pre>sqlite3 chinook.db</pre><p>2. Import the Chinook Database by executing:</p><pre>.read /path/to/extracted/Chinook_Sqlite.sql</pre><p>3. Analyze the data.</p><pre>.tables</pre><p>returns</p><pre>Album          Employee       InvoiceLine    PlaylistTrack<br>Artist         Genre          MediaType      Track        <br>Customer       Invoice        Playlist</pre><p>then try</p><pre>SELECT * FROM Artist LIMIT 100</pre><p>Now … instead of doing everything from the command-line you may as well make your life easier and use SQLLiteStudio. That’s what I would do: <a href="https://sqlitestudio.pl/">https://sqlitestudio.pl/</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GqKC40FQcXPz8Efb126Vjw.png" /></figure><h3>What Are SQL Window Functions?</h3><p>SQL window functions, operate on a set of rows related to the current row within a result set. For instance rows that share the same category as the current row, or the rows before and after the current row.</p><p>Unlike standard aggregate functions like SUM() or AVG(), window functions perform calculations across a &quot;window&quot; or a specific subset of rows defined by the result set&#39;s ordering and partitioning rules. This allows you to perform advanced calculations and analyses on your data while retaining the individual row-level details.</p><p>So, it is about comparing the current row to a set of rows, while retaining the individual row-level details. Let’s clarify with an example and geek out on the data in the Chinook Database Tracks table. We want to calculate the average length of songs within each genre and then compare that average to the length of each song. Here’s the SQL query for this scenario:</p><pre>SELECT<br>  t.TrackId,<br>  t.Name AS SongName,<br>  g.Name AS GenreName,<br>  t.Milliseconds AS SongLength,<br>  AVG(t.Milliseconds) OVER (PARTITION BY t.GenreId) AS AvgGenreLength<br>FROM Track AS t<br>INNER JOIN Genre AS g ON t.GenreId = g.GenreId<br>ORDER BY t.GenreId, t.TrackId;</pre><p>In this query AVG(t.Milliseconds) OVER (PARTITION BY t.GenreId) calculates the average song length (in milliseconds) within each genre using a window function. It partitions the data by GenreId, so the average is calculated for each genre separately. Try it out, the results should look like this:</p><pre>| TrackId | SongName          | GenreName  | SongLength | AvgGenreLength |<br>| ------- | ----------------- | ---------- | ---------- | -------------- |<br>| 1       | For Those About.. | Rock       | 343719     | 346427         |<br>| 2       | Balls to the Wall | Rock       | 342562     | 346427         |<br>| 3       | Fast As a Shark   | Rock       | 230619     | 346427         |<br>| ...     | ...               | ...        | ...        | ...            |<br>| 2108    | Put The Finger... | Reggae     | 203209     | 257387         |<br>| 2109    | Groove Me         | Reggae     | 166512     | 257387         |<br>| ...     | ...               | ...        | ...        | ...            |<br>| 3483    | War/No More Tro.. | Reggae     | 301697     | 257387         |<br>| 3484    | Stop That Train   | Reggae     | 198914     | 257387         |</pre><h3>Syntax</h3><p>Let&#39;s focus on the syntax for a window function in SQL, highlighting the key elements and how to construct them in an SQL statement:</p><p><strong>Window Function Syntax:</strong></p><pre>&lt;Window Function&gt;(&lt;expression&gt;) OVER (<br>  [PARTITION BY &lt;column1&gt;, &lt;column2&gt;, ...]<br>  [ORDER BY &lt;columnA&gt; [ASC|DESC], &lt;columnB&gt; [ASC|DESC], ...]<br>  [ROWS &lt;frame specification&gt;]<br>)</pre><p>Here’s a breakdown of the key elements and how to construct them:</p><ol><li>&lt;Window Function&gt;: This is the window function you want to apply, such as SUM(), AVG(), ROW_NUMBER(), RANK(), DENSE_RANK() etc. It operates on the result set rows defined by the window frame.</li><li>&lt;expression&gt;: Inside the parentheses, specify the column or expression you want to perform the window function on. This can be the column for which you want to calculate an aggregate, generate row numbers, etc.</li><li>OVER: This keyword is required and signifies that you&#39;re defining a window function.</li><li>PARTITION BY &lt;column1&gt;, &lt;column2&gt;, ...: (Optional) The PARTITION BY clause divides the result set into partitions based on the specified columns. The window function is applied independently within each partition.</li><li>ORDER BY &lt;columnA&gt; [ASC|DESC], &lt;columnB&gt; [ASC|DESC], ...: (Optional) The ORDER BY clause specifies the ordering of rows within each partition. It determines the sequence in which the window function operates.</li><li>ROWS &lt;frame specification&gt;: (Optional) The ROWS clause defines the frame or range of rows that the window function considers for its calculations. Common frame specifications include:</li></ol><ul><li>UNBOUNDED PRECEDING to include all rows before the current row.</li><li>n PRECEDING to include the n rows before the current row.</li><li>CURRENT ROW to include only the current row.</li><li>n FOLLOWING to include the n rows after the current row.</li><li>BETWEEN &lt;start&gt; AND &lt;end&gt; to specify a range of rows.</li></ul><p><strong>Constructing a Window Function SQL Statement:</strong><br>Here’s how you put it all together in an SQL statement:</p><pre>SELECT<br>  &lt;columns&gt;,<br>  &lt;Window Function&gt;(&lt;expression&gt;) OVER (<br>    [PARTITION BY &lt;column1&gt;, &lt;column2&gt;, ...]<br>    [ORDER BY &lt;columnA&gt; [ASC|DESC], &lt;columnB&gt; [ASC|DESC], ...]<br>    [ROWS &lt;frame specification&gt;]<br>  ) AS &lt;alias&gt;<br>FROM<br>  &lt;table&gt;;</pre><p>This structure allows you to create SQL statements that use window functions to perform calculations and analyses on subsets of data within your result set.</p><h3>Common Applications of SQL Window Functions</h3><p>SQL window functions are incredibly versatile and find applications in various scenarios. Let’s explore four common use cases where window functions shine, each with practical examples:</p><ol><li>Ranking Rows Based on Specific Criteria</li><li>Computing Running Totals and Averages</li><li>Identifying Peaks and Valleys in Your Data</li><li>Comparing Each Row to Its Neighbors</li></ol><h4>1. Ranking Rows Based on Specific Criteria</h4><p>RANK() and DENSE_RANK() are both window functions in SQL used for ranking rows within a result set based on specific criteria. They assign a unique rank to each row based on the values in one or more columns, and they can handle tied values differently.</p><p><strong>1. RANK():</strong></p><ul><li>The RANK() function assigns a unique rank to each row within the result set based on the specified ordering criteria.</li><li>If two or more rows have the same values and are assigned the same rank, the next rank is skipped. In other words, if two rows share the same rank, the next row receives a rank one position higher.</li><li>Subsequent ranks are adjusted accordingly, so there are no gaps in the rankings.</li></ul><p><strong>2. DENSE_RANK():</strong></p><ul><li>The DENSE_RANK() function also assigns a unique rank to each row based on the specified ordering criteria.</li><li>If two or more rows have the same values and are assigned the same rank, the next rank is not skipped. In other words, if two rows share the same rank, the next row receives the same rank.</li><li>This results in no gaps in the rankings, and rows with tied values receive the same rank.</li></ul><p>Let’s try it out rank employees for the Chinook Database based on their hire dates in the employees table so that the earliest hire has rank number 1 and so on… Here’s the SQL statement:</p><pre>SELECT<br>  EmployeeId,<br>  FirstName,<br>  LastName,<br>  HireDate,<br>  RANK() OVER (ORDER BY HireDate) AS EmployeeRank<br>FROM<br>  Employee<br>ORDER BY<br>  HireDate;</pre><h4>2. Computing Running Totals and Averages</h4><p>Let’s dive straight in and calculate the cumulative total sales amount for each customer based on their invoice amounts. We’ll also compute the running average of these sales amounts. Here’s the SQL statement (I encourage you to try it…):</p><pre>SELECT<br>  CustomerId,<br>  InvoiceId,<br>  InvoiceDate,<br>  Total,<br>  SUM(Total) OVER (PARTITION BY CustomerId ORDER BY InvoiceDate) AS CumulativeTotal,<br>  AVG(Total) OVER (PARTITION BY CustomerId ORDER BY InvoiceDate) AS RunningAverage<br>FROM Invoice<br>ORDER BY CustomerId, InvoiceDate</pre><p>This returns a result set like:</p><pre>| CustomerId | InvoiceId | InvoiceDate         | Total  | CumulativeTotal | RunningAverage |<br>|------------|-----------|---------------------|--------|-----------------|----------------|<br>| 1          | 1         | 2009-01-01 00:00:00 | 3.98   | 3.98            | 3.98           |<br>| 1          | 2         | 2009-01-02 00:00:00 | 8.91   | 12.89           | 6.445          |<br>| 1          | 3         | 2009-01-03 00:00:00 | 13.86  | 26.75           | 8.917          |<br>| 2          | 4         | 2009-01-04 00:00:00 | 0.99   | 0.99            | 0.99           |<br>| 3          | 5         | 2009-01-05 00:00:00 | 1.98   | 1.98            | 1.98           |<br>| 3          | 6         | 2009-01-06 00:00:00 | 1.98   | 3.96            | 1.98           |<br>| 4          | 7         | 2009-01-07 00:00:00 | 0.99   | 0.99            | 0.99           |<br>| 4          | 8         | 2009-01-08 00:00:00 | 1.98   | 2.97            | 1.485          |<br>| ...        | ...       | ...                 | ...    | ...             | ...            |</pre><p>We are using two window functions:</p><ul><li>We use the SUM() function as a window function to calculate the cumulative total sales amount for each customer. The PARTITION BY CustomerId clause ensures that the calculation is performed independently for each customer, and the ORDER BY InvoiceDate clause orders the invoices by date for the running total calculation.</li><li>Similarly, we use the AVG() function as a window function to calculate the running average sales amount for each customer. Again, the PARTITION BY CustomerId clause and ORDER BY InvoiceDate clause are used to define the partition and order for the running average calculation.</li></ul><h4>3. Identifying Peaks and Valleys in Your Data</h4><p>Peaks represent the highest values, while valleys represent the lowest values. Window functions like LEAD(), LAG(), and FIRST_VALUE() can help you compare the current row with neighboring rows to determine whether it&#39;s a peak or valley. Identifying peaks and valleys is more commonly associated with time-series data, such as stock prices, temperature readings, or other continuous data over time.</p><p>Let’s consider a hypothetical scenario to identify peaks and valleys in terms of customer order quantities within a specific period. Suppose you want to find the months when the highest and lowest numbers of tracks were purchased by customers. You can use SQL window functions to identify these peaks and valleys:</p><pre>WITH MonthlyTrackPurchases AS (<br>  SELECT<br>    strftime(&#39;%Y-%m&#39;, InvoiceDate) AS Month,<br>    COUNT(InvoiceLineId) AS TracksPurchased,<br>    RANK() OVER (ORDER BY COUNT(InvoiceLineId) DESC) AS RankHigh,<br>    RANK() OVER (ORDER BY COUNT(InvoiceLineId)) AS RankLow<br>  FROM InvoiceLine<br>  GROUP BY Month<br>)<br>SELECT<br>  Month,<br>  TracksPurchased,<br>  CASE<br>    WHEN RankHigh = 1 THEN &#39;Peak (Highest)&#39;<br>    WHEN RankLow = 1 THEN &#39;Valley (Lowest)&#39;<br>    ELSE &#39;Normal&#39;<br>  END AS PeakOrValley<br>FROM MonthlyTrackPurchases<br>WHERE RankHigh = 1 OR RankLow = 1<br>ORDER BY Month;</pre><p>A better example would have been stock prices… Suppose you have a dataset of daily stock prices, and you want to identify the peaks (highest prices) and valleys (lowest prices) within a certain time frame. You could use SQL window functions to sort the data by date and compare each day’s closing price with the prices of the previous and next days. If a day’s price is higher than both the previous and next days, it’s likely a peak. If it’s lower than both, it’s likely a valley.</p><p>By identifying these peaks and valleys, you can gain insights into price trends, potential buy or sell points, or periods of market volatility.</p><p>In summary, identifying peaks and valleys in your data using SQL window functions involves analyzing the data’s patterns and trends to pinpoint the highest and lowest points, which can be valuable for various analytical and decision-making purposes.</p><h4>4. Comparing Each Row to Its Neighbours</h4><p>Applying window functions to compare each row to its neighbors means using SQL window functions to analyze the current row’s data in the context of adjacent rows within the same result set. It allows you to make comparisons and calculations that involve data from the rows immediately preceding or following the current row, or within a specified range around the current row. This type of analysis is valuable for various data manipulation and analysis tasks.</p><p>Here’s a general process for applying window functions to compare each row to its neighbors:</p><ol><li><strong>Define the Window Frame</strong>: You specify the window frame or set of rows that the window function should consider when making comparisons. This is done using clauses like ROWS BETWEEN, UNBOUNDED PRECEDING, n PRECEDING, CURRENT ROW, n FOLLOWING, and UNBOUNDED FOLLOWING.</li><li><strong>Select the Window Function</strong>: Choose the appropriate window function based on the type of comparison you want to make. Common window functions for such comparisons include LEAD(), LAG(), and FIRST_VALUE(). These functions access data from rows within the defined window frame.</li><li><strong>Perform the Comparison or Calculation</strong>: Use the selected window function in your SQL query to compare or calculate values based on data from the current row and its neighboring rows within the specified window frame.</li><li><strong>Retrieve and Analyze Results</strong>: The window function generates a result for each row in the result set, considering the specified window frame. You can then retrieve and analyze these results to gain insights into patterns, trends, or anomalies in your data.</li></ol><p>Examples of applying window functions to compare each row to its neighbours include:</p><ul><li>Calculating the percentage change between the current and previous day’s stock prices.</li><li>Detecting abrupt changes in sensor readings by comparing each reading to nearby readings in a time series.</li><li>Analyzing trends in web traffic by comparing page views for each day with those of the previous and following days.</li></ul><p>In our last example we’ll compare the number of tracks in each album to the number of tracks in the previous and following albums. We’ll use the LEAD() and LAG() window functions for this comparison:</p><pre>SELECT<br>  AlbumId,<br>  Title AS AlbumTitle,<br>  ArtistId,<br>  TracksCount AS TotalTracks,<br>  LAG(TracksCount) OVER (ORDER BY AlbumId) AS PreviousAlbumTracks,<br>  LEAD(TracksCount) OVER (ORDER BY AlbumId) AS NextAlbumTracks<br>FROM (<br>  SELECT<br>    Album.AlbumId,<br>    Album.Title,<br>    Album.ArtistId,<br>    COUNT(Track.TrackId) AS TracksCount<br>  FROM Album<br>  LEFT JOIN Track ON Album.AlbumId = Track.AlbumId<br>  GROUP BY Album.AlbumId<br>) AS AlbumWithTrackCount<br>ORDER BY AlbumId;sql</pre><p>In this SQL query:</p><ul><li>We first calculate the number of tracks in each album by joining the Album and Track tables and using the COUNT() function. This subquery is aliased as AlbumWithTrackCount.</li><li>In the outer query, we select the relevant columns, including AlbumId, Title, ArtistId, and TracksCount.</li><li>We use the LAG() and LEAD() window functions to access the number of tracks in the previous album and the following album, respectively. These functions are ordered by AlbumId, allowing us to compare each album to its neighbors.</li><li>Finally, we present the result set with columns for the current album’s track count, the previous album’s track count, and the next album’s track count.</li></ul><h3>Conclusion</h3><p>Congratulations! You’ve reached the end of this tutorial on SQL window functions, and by doing so, you’ve taken a significant step toward mastering this powerful tool in your data manipulation toolkit.</p><p>The goal of this article was to demystify SQL window functions and make them as intuitive as other fundamental SQL operations like sorting, grouping, and filtering. We’ve explored various practical applications of window functions, including ranking rows, calculating running totals and averages, identifying peaks and valleys in your data, and comparing each row to its neighbors.</p><p>So, I hope your “aha” moment with SQL window functions has arrived, and you’re now equipped to apply it. Happy querying!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5080f1d8ebd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding concurrent.futures]]></title>
            <link>https://medium.com/@LukV/understanding-concurrent-futures-af01247dfb7?source=rss-496cce7e1047------2</link>
            <guid isPermaLink="false">https://medium.com/p/af01247dfb7</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[multithreading-in-python]]></category>
            <category><![CDATA[concurrent-programming]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Luk Verhelst]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 20:42:27 GMT</pubDate>
            <atom:updated>2023-03-15T20:45:38.563Z</atom:updated>
            <content:encoded><![CDATA[<p>And how concurrent.futures relate to asyncio</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0AFUpGrwtfyyiOJs" /><figcaption>Photo by <a href="https://unsplash.com/@breebuddy?utm_source=medium&amp;utm_medium=referral">Bree Anne</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Complementary to the prevous article on asyncio “<a href="https://medium.com/@LukV/solve-common-asynchronous-scenarios-fire-and-forget-pub-sub-and-data-pipelines-with-python-asyncio-7f20d1268ade">Solve common asynchronous scenarios with Python asyncio</a>” in this post we focus on the standard Python module concurrent.futures. Both asyncio and concurrent.futures are popular approaches to asynchronous programming in Python, however they both serve complementary purposes. Sometimes using asyncio might be overkill, sometimes it&#39;s the better chocie. In this post, we will start with concurrent.futures and explore when and how to use it.</p><p>The concurrent.futures module provides an easy-to-use interface for asynchronously executing tasks using threads or processes, while asyncio is a library for writing single-threaded concurrent code using coroutines, event loops, and non-blocking I/O.</p><p>Additionally to giving you armour to outweigh both options we will cover some pitfalls to avoid. We will also discuss when it’s better to use asyncio over concurrent.futures, and vice versa. By the end of this post, you will have a solid understanding of concurrent.futures and how to use it in your Python projects to improve performance and efficiency.</p><h3>Let’s start the thrilling world of concurrent.futures</h3><p>What does the concurrent.futures module has to offer... From <a href="https://docs.python.org/3/library/concurrent.futures.html">the official python.org docs</a></p><blockquote><em>The </em><em>concurrent.futures module provides a high-level interface for asynchronously executing callables.</em></blockquote><p>The concurrent.futures module is part of Python&#39;s standard library and provides a high-level interface for asynchronously executing functions using <em>threads</em> or <em>processes</em>: threads for I/O bound tasks, processes for CPU bound tasks. The module as such includes two classes: ThreadPoolExecutor and ProcessPoolExecutor.</p><p>To use the concurrent.futures module, you:</p><ol><li>first create an executor object (either a ThreadPoolExecutor or a ProcessPoolExecutor) and then</li><li>submit tasks to it.</li></ol><p>The executor manages the execution of the tasks, and you can obtain the results of each task using a Future object.</p><p>The module is useful when you have CPU-bound or I/O-bound tasks that can be executed independently and you want to execute them concurrently to improve the overall performance of your program. Examples of such tasks include downloading data from a network, processing large datasets, and performing CPU-intensive computations. In this tutorial we will focus on I/O-bound tasks and (thus) the ThreadPoolExecutor. Here is a basic example:</p><pre>import concurrent.futures<br>import time<br><br># Define a function that takes some time to execute<br>def slow_function(n):<br>    print(f&quot;Starting task {n}&quot;)<br>    time.sleep(2)  # Simulate a time-consuming task<br>    print(f&quot;Finished task {n}&quot;)<br>    return f&quot;Result of task {n}&quot;<br><br># Create a ThreadPoolExecutor with 2 threads<br>with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:<br>    # Submit 3 tasks to the executor<br>    futures = [executor.submit(slow_function, n) for n in range(1, 4)]<br>    # Wait for the tasks to complete and get their results<br>    results = [future.result() for future in futures]<br><br># Print the results<br>print(results)</pre><p>In this example, we define a function slow_function that takes some time to execute and return a result. We then create a ThreadPoolExecutor with 2 threads and submit 3 tasks to it using the submit method. The submit method returns a Future object, which we store in a list.</p><p>We then wait for the tasks to complete using the result method of the Future objects. The result method blocks until the task completes and returns the result.</p><p>Finally, we print the results of the tasks.</p><p>When you run this code, you should see that the tasks are executed concurrently by the two threads in the thread pool, and the results are printed as soon as they are available.</p><h3>A real-world example</h3><p>A practical use case for I/O bound tasks with concurrent.futures could be to scrape data from multiple websites or APIs concurrently. Let’s say we have a list of URLs that we want to scrape data from, and each request to a URL takes a few seconds to complete due to network latency. We can use concurrent.futures to execute these requests concurrently and improve the overall performance of our scraper. Here’s an example:</p><p>Here’s an example:</p><pre>import requests<br>import concurrent.futures<br><br># Define a function to scrape data from a URL<br>def scrape_data(url):<br>    response = requests.get(url)<br>    return response.text[:100]  # Return the first 100 characters of the response<br><br># List of URLs to scrape data from<br>urls = [&#39;https://www.python.org/&#39;, &#39;https://www.google.com/&#39;, &#39;https://www.github.com/&#39;]<br><br># Create a ThreadPoolExecutor with 3 threads<br>with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:<br>    # Submit a scrape_data task for each URL to the executor<br>    futures = [executor.submit(scrape_data, url) for url in urls]<br>    # Wait for the tasks to complete and get their results<br>    results = [future.result() for future in futures]<br><br># Print the results<br>print(results)</pre><h3>When to use concurrent.futures instead of asyncio</h3><p><strong>asyncio may be overkill in some cases…</strong></p><p>In the example above, we would not necessarily need to use asyncio instead of concurrent.futures, since concurrent.futures is well-suited for I/O-bound tasks such as web scraping. asyncio is typically more useful for handling multiple I/O-bound tasks that need to be coordinated or have dependencies between them.</p><p>asyncio is designed for cooperative multitasking, where multiple coroutines can run concurrently and yield control to each other when they are waiting for I/O operations to complete. It&#39;s particularly useful for scenarios where there are many I/O-bound operations that need to be performed concurrently, such as handling multiple incoming network connections.</p><p>However, in the example above, we are performing a small number of I/O-bound operations that don’t need to be coordinated, so we can simply use concurrent.futures to execute them concurrently. asyncio might be overkill for this scenario, and using concurrent.futures is simpler and easier to understand.</p><h3>When to use asyncio to avoid common pitfalls</h3><p>While concurrent.futures can be a powerful tool for executing concurrent tasks in Python, there are some pitfalls to be aware of:</p><ol><li><strong>Deadlocks</strong>: Deadlocks can occur when two or more threads are waiting for each other to release resources that they need to proceed. To avoid deadlocks, you should be careful when using locks and ensure that they are released in a timely manner.</li><li><strong>Error handling</strong>: If an error occurs in one of the tasks executed with concurrent.futures, the exception will be raised in the thread or process where the task was executed, rather than the main thread or process. You should be careful to handle exceptions appropriately and ensure that they do not propagate to other threads or processes.</li><li>(But mainly…) <strong>Blocking calls</strong>: If you use third-party libraries that make blocking I/O calls (such as requests), it can prevent other tasks from executing and reduce the concurrency of your program. To avoid this, you can use alternative libraries that provide non-blocking I/O (such as aiohttp).</li></ol><p>asyncio is designed to work around many of the pitfalls that can arise when using traditional threading or multiprocessing approaches, by providing cooperative multitasking and non-blocking I/O. Here&#39;s how asyncio can work around the pitfalls mentioned in the previous question:</p><ol><li><strong>Deadlocks</strong>: asyncio uses a cooperative multitasking approach that can help avoid deadlocks by allowing coroutines to yield control to each other when they are waiting for resources to become available. Additionally, asyncio provides mechanisms such as locks and semaphores that can be used to coordinate access to shared resources.</li><li><strong>Error handling</strong>: asyncio provides mechanisms for handling exceptions that occur in coroutines, including try/except blocks and async with statements. Additionally, asyncio provides a Task object that can be used to track the status of a coroutine and handle any exceptions that occur.</li><li><strong>Blocking calls</strong>: asyncio can work around blocking calls by providing non-blocking I/O libraries such as aiohttp and asyncpg. These libraries use asynchronous I/O operations that can allow multiple tasks to execute concurrently without blocking the event loop.</li></ol><h3>Conclusion</h3><p>Overall, asyncio provides a powerful and flexible approach to concurrent programming in Python that can work around many of the pitfalls associated with traditional threading or multiprocessing approaches. However, it does require some additional complexity and can have a steeper learning curve compared to concurrent.futures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af01247dfb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solve Common Asynchronous Scenarios With Python’s “asyncio”]]></title>
            <link>https://medium.com/better-programming/solve-common-asynchronous-scenarios-fire-and-forget-pub-sub-and-data-pipelines-with-python-asyncio-7f20d1268ade?source=rss-496cce7e1047------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f20d1268ade</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Luk Verhelst]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 15:31:29 GMT</pubDate>
            <atom:updated>2023-03-16T09:01:57.949Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<h4><strong>Fire-and-Forget, Pub/Sub, and Data Pipelines</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6_V-b4WBAuxFxPCH" /><figcaption>Photo by <a href="https://unsplash.com/es/@whatyouhide?utm_source=medium&amp;utm_medium=referral">Andrea Leopardi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Asyncio is a powerful tool for writing asynchronous code in Python, but just like many developers around me, I struggled to fully grasp its concepts and capabilities.</p><p>When searching the web on asyncio, documentation and tutorials are either too technical and theoretical, making it hard to understand how to apply it in practice. Or they’re too shallow, only scratching the surface of its potential.</p><p>That’s why we’re writing this blog post — to provide a clear and comprehensive overview of asyncio, its core concepts, and practical examples of how to use it to improve the performance and responsiveness of your Python applications.</p><p>Whether you’re new to asyncio or looking to deepen your understanding, this post will help you get up to speed and start using it to write efficient and scalable Python code.</p><h3>A Practical Introduction to Asynchronous Programming in Python</h3><p>Asyncio is a Python library that provides tools for writing asynchronous code. This means that you can write programs that perform multiple tasks at the same time without blocking the execution of other tasks.</p><p>Here are some real-world examples of how asyncio can greatly improve the performance and responsiveness of your application:</p><ol><li><strong>Web scraping</strong>: When scraping a website for data, you may need to make multiple HTTP requests to different URLs to retrieve the data you need. By using asyncio, you can perform these requests in parallel, making the scraping process much faster and more efficient.</li><li><strong>File I/O</strong>: When reading or writing to multiple files, using asyncio can allow you to perform these operations concurrently, improving performance and reducing the time it takes to complete the task.</li><li><strong>Database access</strong>: When accessing a database, you may need to make multiple queries simultaneously. By using asyncio, you can perform these queries concurrently, improving performance and allowing you to handle more requests at once.</li></ol><p>In more technical terms, asyncio provides a framework for writing non-blocking code that can handle I/O bound tasks, such as network communication or file I/O, by allowing tasks to yield control to other tasks when waiting for I/O operations to complete.</p><p>Here is an example to simulate the File I/O use case:</p><pre>import asyncio<br><br>async def fetch_file():<br>    print(&quot;Starting to fetch file&quot;)<br>    await asyncio.sleep(1) # duration to fetch the file<br>    print(&quot;Fetching file completed&quot;)<br><br>async def main():<br>    print(&quot;Starting main&quot;)<br>    await `asyncio.gather`(<br>        fetch_file(),<br>        fetch_file(),<br>        fetch_file()<br>    )<br>    print(&quot;Main completed&quot;)<br><br>asyncio.run(main())</pre><h4>Can you guess what is printed from the above program? …..</h4><p>That’s right… Because of the 1 second wait first three times “Starting to fetch file”, then three times “Fetching file completed” *.</p><pre>Starting main<br>Starting to fetch file<br>Starting to fetch file<br>Starting to fetch file<br>Fetching file completed<br>Fetching file completed<br>Fetching file completed<br>Main completed</pre><p>If it were handled synchronously it would have returned:</p><pre>Starting main<br>Starting to fetch file<br>Fetching file completed<br>Starting to fetch file<br>Fetching file completed<br>Starting to fetch file<br>Fetching file completed<br>Main completed</pre><h4>Coroutines</h4><p>In the above example, we define a coroutine function fetch_file that simply prints some text and then sleeps for one second simulating the wait to get the file from disk, using the await keyword. We also define a main function that creates three instances of fetch_file using the asyncio.gather function to run them concurrently.</p><p>We then use the asyncio.run function to run the main coroutine, which prints some text, runs the three instances of fetch_file concurrently, and then prints some more text when they are all complete.</p><p>So the keywords are async def and await in the above example. It is these keywords that distinguish an asynchronous program from a blocking program. In the next chapters, we&#39;ll delve deeper into both terms. First async...</p><h4>Declare coroutines with async def</h4><p>When we compare a coroutine to a “standard” subroutine, a coroutine is a type of subroutine that allows for non-blocking concurrent execution. Like a subroutine, a coroutine is a block of code that can be called from elsewhere in a program, typically a function.</p><p>However, unlike a subroutine, a coroutine can pause its execution at any point and allow another block of code to execute before resuming where it left off. For example, in a web server, a coroutine can be used to handle an incoming request without blocking the server from handling other requests.</p><p>Here’s an example comparison that calculates the sum of all numbers in a list, first as a “classic” subroutine, then as a coroutine:</p><pre># As a subroutine<br>def sum_list(numbers: List) -&gt; int:<br>    result = 0<br>    for num in numbers:<br>        result += num<br>    return result</pre><p>And here’s the same function implemented as a coroutine using the async keyword:</p><pre># As a coroutine<br>async def sum_list(numbers):<br>    result = 0<br>    for num in numbers:<br>        result += num<br>        # Pause execution to allow other coroutines to run<br>        await asyncio.sleep(0)<br>    return result</pre><p>As you can see, the main difference between the two implementations is the addition of the async keyword and the use of the await keyword in the coroutine version. This allows the coroutine to pause its execution at the await statement and allow other coroutines to run before resuming execution.</p><p>When calling the subroutine version, it will block the execution of the calling code until the function returns. This means that if you have a large list of numbers to sum, the calling code will be blocked until the function has finished calculating the sum.</p><p>In contrast, when calling the coroutine version, it will not block the execution of the calling code. Instead, the coroutine will yield control to other coroutines when it reaches the await statement, allowing them to run before resuming execution. This means that the calling code can continue to execute while the coroutine is running in the background.</p><h4>The await Keyword and Awaitables</h4><p>The await keyword plays a central role in asynchronous code, and can only be used within asynchronous code blocks such as the code block of an async def statement. It declares an awaitable.</p><p>So what is an awaitable? When you use the await keyword you create an awaitable object. This pauses the execution of the coroutine until the result of the awaitable is ready, yielding the execution back to the caller of the subroutine.</p><p>To understand this concept, think of an awaitable as a restaurant order. Just like a restaurant order, an awaitable is something that you request and wait for. When you place an order at a restaurant, the waiter takes your order and tells you that your food will be ready in a certain amount of time. You then wait patiently for your food to be prepared and delivered to your table.</p><p>Similarly, when you await an awaitable in a coroutine, the coroutine pauses its execution and waits for the result of the awaitable to be ready. Once the result is ready, the coroutine resumes its execution and continues from where it left off.</p><p>Here’s an example of representing the restaurant order metaphor in Python code:</p><pre>async def place_order():<br>    print(&quot;Placing order...&quot;)<br>    await asyncio.sleep(5)<br>    print(&quot;Order ready!&quot;)<br>    return &quot;Steak&quot;<br><br>async def serve_food():<br>    print(&quot;Waiting for order...&quot;)<br>    order = await place_order()<br>    print(f&quot;Order received: {order}&quot;)<br>    print(&quot;Serving food...&quot;)<br><br>asyncio.run(serve_food())</pre><p>In this example, the place_order coroutine simulates placing an order at a restaurant. It prints some text to indicate that an order is being placed and then uses the await keyword to pause its execution for 5 seconds using asyncio.sleep. This simulates the time it takes for the food to be prepared.</p><p>Once the food is ready, the place_order coroutine resumes its execution and returns the value &quot;Steak&quot;, which represents the food order.</p><p>The serve_food coroutine simulates waiting for the food to be delivered and then serving it. It prints some text to indicate that it&#39;s waiting for an order, and then calls the place_order coroutine using the await keyword to get the order. Once the order is received, the serve_food coroutine prints some more text to indicate that it&#39;s serving the food.</p><p>Finally, we run the serve_food coroutine using asyncio.run(serve_food()) to see the output:</p><pre>Waiting for order...<br>Placing order...<br>Order ready!<br>Order received: Steak<br>Serving food...</pre><h4>Tasks and the event loop</h4><p>Consider this example: Grandmaster Judith Polgar is at a chess convention. She plays against 24 amateur chess players. To make a move it takes her 5 seconds. The opponents need 55 seconds to make their move. A game ends at roughly 60 moves or 30 moves from each side. (Source: <a href="https://github.com/fillwithjoy1/async_io_for_beginners">https://github.com/fillwithjoy1/async_io_for_beginners</a>)</p><p><strong>Synchronous version</strong></p><pre>import time<br><br>def play_game(player_name):<br>    for move in range(30):<br>        time.sleep(5) # the champion takes 5 seconds to make a move<br>        print(f&quot;{player_name} made move {move+1}&quot;)<br>        time.sleep(55) # the opponent takes 55 seconds to make a move<br><br>if __name__ == &quot;__main__&quot;:<br>    players = [&#39;Judith&#39;] + [f&#39;Amateur{i+1}&#39; for i in range(24)]<br>    for player in players:<br>        play_game(player)</pre><p><strong>Asynchronous version</strong></p><pre>import asyncio<br><br>async def play_game(player_name):<br>    for move in range(30):<br>        await asyncio.sleep(5) # the champion takes 5 seconds to make a move<br>        print(f&quot;{player_name} made move {move+1}&quot;)<br>        await asyncio.sleep(55) # the opponent takes 55 seconds to make a move<br><br>async def play_all_games(players):<br>    tasks = [`asyncio.create_task`(play_game(player)) for player in players]<br>    await `asyncio.gather`(*tasks)<br><br>if __name__ == &quot;__main__&quot;:<br>    players = [&#39;Judith&#39;] + [f&#39;Amateur{i+1}&#39; for i in range(24)]<br>    asyncio.run(play_all_games(players))</pre><p>In the synchronous version, the program will run sequentially, playing one game after another. Therefore, it will take a total of 24 * 60<em> * </em>60 = 86,400 seconds (or <strong>1 day</strong>) to complete all the games.</p><p>In the asynchronous version, the program will run concurrently, allowing multiple games to be played at the same time. Therefore, it will take approximately 60 * 5 = 300 seconds (or 5 minutes) to complete all the games, assuming that there are enough resources available to handle all the concurrent games.</p><p>Observe how we are using asyncio.create_task and asyncio.gather to allow multiple games to be played concurrently. Here&#39;s how these functions work:</p><ul><li>asyncio.create_task is used to schedule a coroutine to run in the event loop as a task. In our case, we are creating a task for each game that needs to be played. By doing this, we are allowing the event loop to run multiple games concurrently.</li><li>asyncio.gather is used to run multiple coroutines concurrently and wait for them all to complete. In our case, we are using asyncio.gather to run all the game tasks concurrently and wait for all of them to finish before exiting the program.</li></ul><p>By using these functions, we are able to run multiple games concurrently, which makes the program faster and more efficient. Without these functions, the program would run sequentially and take a lot longer to complete.</p><h4>Tasks and the Event Loop</h4><p>In asyncio, a Task is a unit of work that is scheduled to be executed by the event loop.</p><p>When we create a task in an asynchronous program, we are essentially telling the event loop to run that task at some point in the future. The event loop will then manage the execution of that task by scheduling it to run when it’s ready. The keyword await passes function control back to the event loop.</p><p>For example, let’s say we have a task that involves making a network request. When we create that task and tell the event loop to run it, the event loop will start executing the task and then pause it when it needs to wait for the network response. While the task is paused, the event loop can continue running other tasks. When the network response arrives, the event loop will resume the task and continue its execution.</p><p>By creating tasks in the event loop, we can manage multiple tasks efficiently and ensure that they are executed in an order that is optimal for performance. This is what makes asynchronous programming so powerful and efficient.</p><h3>Common Asynchronous Scenarios</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UKt5uJNMMGOKiJQb" /><figcaption>Photo by <a href="https://unsplash.com/@carlevarino?utm_source=medium&amp;utm_medium=referral">Cesar Carlevarino Aragon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>What we have learned so far… Asynchronous programming with asyncio is a powerful technique that can help you write highly concurrent and performant Python code. Here are some common concepts we touched upon:</p><ol><li><strong>Coroutines</strong>: Coroutines are the building blocks of asyncio. They are functions that can be paused and resumed later, allowing you to write non-blocking code that can switch between tasks quickly.</li><li><strong>Event loops</strong>: The event loop is the core of asyncio. It schedules and runs coroutines, and manages I/O operations. You should only create one event loop per thread, and it should be started with the run_until_complete() method.</li><li><strong>Tasks</strong>: Tasks are a higher-level abstraction than coroutines. They represent a coroutine that is running in the background, and allow you to cancel, pause, and resume the coroutine. You can use the asyncio.create_task() function to create a new task.</li></ol><p>What we did not cover:</p><ul><li><strong>Timeout</strong>: The asyncio module provides a way to set a timeout for an operation using the asyncio.wait_for() function. This can be useful when you want to limit the amount of time a coroutine can spend waiting for a result.</li><li><strong>Futures</strong>: Task is a subclass of Future. Futures are objects that represent a result that may not be available yet. You can use the asyncio.Future class to create a new future, and the await keyword to wait for the result.</li><li><strong>Queue</strong>: This will be covered in the upcoming paragraphs… A Queue is a data structure that allows multiple coroutines to communicate with each other. It can be used to pass messages between coroutines or to coordinate the execution of multiple coroutines.</li></ul><h4>Pattern 1 Fire-and-Forget</h4><p>The “Fire-and-Forget” design pattern allows you to execute a task asynchronously without waiting for its result. This means that you can start the task and immediately continue with other work, without blocking or waiting for the task to complete.</p><p>Fire-and-Forget is useful when you have a task that needs to be executed in the background, but the result of that task isn’t needed immediately. For example, sending an email or logging a message are both tasks that don’t require an immediate response, and can be executed asynchronously using the Fire-and-Forget pattern.</p><p>This is nothing new, we’ve done this in the chapter earlier. To implement the Fire-and-Forget pattern in Python’s asyncio library, we can create a coroutine function that performs the task, and then call it using asyncio.create_task(). This function will start the coroutine in the background and immediately return a Task object that represents the running task.</p><p>Here’s an example of using the Fire-and-Forget pattern in Python’s asyncio library to send an email:</p><pre>import asyncio<br>import smtplib<br>from email.message import EmailMessage<br><br>async def send_email(subject, body, to):<br>    # Create a new email message<br>    msg = EmailMessage()<br>    msg[&#39;Subject&#39;] = subject<br>    msg[&#39;From&#39;] = &#39;me@example.com&#39;<br>    msg[&#39;To&#39;] = to<br>    msg.set_content(body)<br>    # Connect to the SMTP server and send the message<br>    with smtplib.SMTP(&#39;smtp.gmail.com&#39;, 587) as smtp:<br>        await smtp.starttls()<br>        await smtp.login(&#39;my_email@gmail.com&#39;, &#39;my_password&#39;)<br>        await smtp.send_message(msg)<br><br># Fire-and-forget sending the email<br>asyncio.create_task(send_email(&#39;Test Email&#39;, &#39;This is a test email&#39;, &#39;you@example.com&#39;))<br><br># Continue with other work without waiting for the email to send<br>print(&#39;Email sent in the background&#39;)</pre><p>In this example, we define an asynchronous function send_email() that sends an email using the smtplib library.</p><p>We then call asyncio.create_task() to start the send_email() coroutine in the background and immediately return a Task object that represents the running task.</p><p>Finally, we continue with other work without waiting for the email to send.</p><h4>Pattern 2 Pub/Sub</h4><p>To design a pub/sub pattern with asyncio and the Queue class, you can follow these steps:</p><ol><li>Create a shared asyncio.Queue object that will act as a buffer between publishers and subscribers. The Queue class is thread-safe, which means that it can be safely accessed by multiple coroutines in parallel without causing any race conditions or other synchronization issues.</li><li>Define a coroutine function that represents the publisher. This coroutine function should accept a single argument, which represents the message to be published. The function should then put the message into the shared Queue object using the put method.</li><li>Define a coroutine function that represents the subscriber. This coroutine function should continuously loop and wait for messages to be available in the shared Queue object using the get method. When a message is available, the function should process it according to the subscriber&#39;s needs.</li><li>Define a main function that creates a shared Queue object and starts multiple instances of the publisher and subscriber coroutines as needed.</li></ol><p>Here is a sample implementation:</p><pre>import asyncio<br><br>async def publisher(queue):<br>    while True:<br>        message = input(&quot;Enter message: &quot;)<br>        await queue.put(message)<br><br>async def subscriber(queue, name):<br>    while True:<br>        message = await queue.get()<br>        print(f&quot;Subscriber {name} received message: {message}&quot;)<br><br>async def main():<br>    queue = asyncio.Queue()<br>    await asyncio.gather(<br>        publisher(queue),<br>        subscriber(queue, &quot;A&quot;),<br>        subscriber(queue, &quot;B&quot;),<br>        subscriber(queue, &quot;C&quot;)<br>    )<br><br>asyncio.run(main())</pre><p>In this implementation, the publisher coroutine reads input from the user and puts it into the shared Queue object. The subscriber coroutine continuously waits for messages to be available in the shared Queue object and prints them to the console. The main function creates the shared Queue object and starts one publisher and three subscribers.</p><p>Let’s build a chat application as a practical example. In a chat room, multiple users can send messages to a channel or a group of users, and those messages need to be delivered to all the users who are subscribed to the channel or group.</p><p>By using the pub/sub pattern with asyncio and the Queue class, you can create a message queue that acts as a buffer between the publishers and subscribers. When a user sends a message, it can be put into the message queue by the publisher. The subscribers can then retrieve the messages from the message queue and display them to the appropriate users.</p><pre>import asyncio<br><br>class ChatRoom:<br>    def __init__(self):<br>        self.message_queue = asyncio.Queue()<br>    async def publish(self, message):<br>        await self.message_queue.put(message)<br>    async def subscribe(self, user_name):<br>        while True:<br>            message = await self.message_queue.get()<br>            print(f&quot;{user_name} received message: {message}&quot;)<br><br>async def main():<br>    chat_room = ChatRoom()<br>    await asyncio.gather(<br>        chat_room.publish(&quot;Hello, world!&quot;),<br>        chat_room.subscribe(&quot;Alice&quot;),<br>        chat_room.subscribe(&quot;Bob&quot;)<br>    )<br><br>asyncio.run(main())</pre><h4>Pattern 3: Data pipelines</h4><p>A pipeline is a sequence of routines that are executed in a specific order, where the output of one routine becomes the input of the next. By using coroutines we break down a complex task into smaller, more manageable steps, and execute each step asynchronously.</p><p>We will be using the asyncio.Queue class to pass data between the coroutines. By doing so we ensure that the steps are executed in the specific order. Each coroutine reads data from the queue, processes it, and puts the output back on the queue for the next coroutine to process. By using a queue, we can ensure that each coroutine processes data in the order that it was received.</p><p>In the following program, we define three functions to perform the different steps of a data pipeline: remove_duplicates, get_coordinates, and add_import_timestamp.</p><p>We apply these functions to a batch of data, in the example represented as two batches assigned to Pandas dataframes. We then define the main function main that creates two tasks to process each batch of data asynchronously using the asyncio.gather method. Finally, we run the main function using the asyncio.run method.</p><p>When the program is run, it will output the processed dataframes for both batches, with the added Latitude, Longitude, and Import Timestamp columns.</p><pre>import asyncio<br>import pandas as pd<br>from datetime import datetime<br>import requests<br><br># Define the coroutine to remove duplicates<br>async def remove_duplicates(queue):<br>    while True:<br>        data = await queue.get()<br>        data = data.drop_duplicates()<br>        await queue.put(data)<br>        queue.task_done()<br><br># Define the coroutine to call the 3rd party API to get coordinates<br>async def get_coordinates(queue):<br>    while True:<br>        data = await queue.get()<br>        for index, row in data.iterrows():<br>            address = row[&#39;Address&#39;]<br>            url = f&#39;https://api.geocode.xyz/{address}?json=1&#39;<br>            response = requests.get(url)<br>            json_response = response.json()<br>            data.loc[index, &#39;Latitude&#39;] = json_response[&#39;latt&#39;]<br>            data.loc[index, &#39;Longitude&#39;] = json_response[&#39;longt&#39;]<br>        await queue.put(data)<br>        queue.task_done()<br><br># Define the function to add the import timestamp column<br>def add_import_timestamp(data):<br>    timestamp = datetime.now()<br>    data[&#39;Import Timestamp&#39;] = timestamp<br>    return data<br><br># Define the coroutine to process each batch of data<br>async def process_data(data, queue):<br>    # Put the initial data in the queue<br>    await queue.put(data)<br>    # Wait for all tasks to complete<br>    await queue.join()<br>    # Add the import timestamp column<br>    data = add_import_timestamp(data)<br>    return data<br><br># Define the main function to process both batches of data asynchronously<br>async def main():<br>    # Define the two batches of data<br>    batch1 = pd.DataFrame({<br>        &#39;Address&#39;: [&#39;123 Main St&#39;, &#39;456 Oak Ave&#39;, &#39;789 Maple St&#39;, &#39;456 Oak Ave&#39;, &#39;234 Pine Rd&#39;]<br>    })<br>    batch2 = pd.DataFrame({<br>        &#39;Address&#39;: [&#39;345 Elm St&#39;, &#39;678 Birch Rd&#39;, &#39;234 Pine Rd&#39;, &#39;910 Cedar Ln&#39;, &#39;345 Elm St&#39;]<br>    })<br>    # Define the queue<br>    queue = asyncio.Queue()<br>    # Define the tasks to process each batch of data asynchronously<br>    tasks = [<br>        asyncio.create_task(remove_duplicates(queue)),<br>        asyncio.create_task(get_coordinates(queue)),<br>        asyncio.create_task(process_data(batch1, queue)),<br>        asyncio.create_task(process_data(batch2, queue))<br>    ]<br>    # Wait for all tasks to complete<br>    results = await asyncio.gather(*tasks)<br>    # Print the results<br>    for result in results:<br>        print(result)<br><br># Run the main function<br>asyncio.run(main())</pre><p>We use a Queue to ensure that the steps are executed in the specific order of remove_duplicates, get_coordinates, and add_import_timestamp.</p><p>We define two coroutines, remove_duplicates and get_coordinates, that continuously loops through the queue, gets the data, processes it, and put it back in the queue. The process_data coroutine puts the initial data in the queue and waits for all tasks to complete using queue.join().</p><p>Once all the steps are complete, the add_import_timestamp function is called to add the import timestamp column.</p><p>There is still quite some ground to cover but I hope you learned something useful today. Please shout out if you think of other practical applications to share. Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f20d1268ade" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/solve-common-asynchronous-scenarios-fire-and-forget-pub-sub-and-data-pipelines-with-python-asyncio-7f20d1268ade">Solve Common Asynchronous Scenarios With Python’s “asyncio”</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>