<?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 Muhammad Ahsan Khan on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Ahsan Khan on Medium]]></description>
        <link>https://medium.com/@ahsankhaan2992?source=rss-61974b0c4733------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uBI3tqSn9OWyE9hSLHxF9g.jpeg</url>
            <title>Stories by Muhammad Ahsan Khan on Medium</title>
            <link>https://medium.com/@ahsankhaan2992?source=rss-61974b0c4733------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:52:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahsankhaan2992/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[Why Is My Data Always Out of Sync?]]></title>
            <link>https://medium.com/@ahsankhaan2992/why-is-my-data-always-out-of-sync-0d40d621c7fe?source=rss-61974b0c4733------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d40d621c7fe</guid>
            <dc:creator><![CDATA[Muhammad Ahsan Khan]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 20:44:36 GMT</pubDate>
            <atom:updated>2026-01-11T20:44:36.276Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Is My Data Always Out of Sync? | Solving Real-World Data Chaos using CDC with MSSQL, Debezium, and Kafka</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*32N_WJKCDndg25l-e6mBEw.png" /></figure><p>Every growing system eventually hits the same wall.</p><p>“The database is updated, but the other system didn’t get the change.”<br> “Why is the report still showing old data?”<br> “Let’s add another background job…”</p><p>If these statements sound familiar, congratulations !<br>you’ve discovered the limits of traditional data synchronization.</p><p>In this article, we’ll see how <strong>Change Data Capture (CDC)</strong> with <strong>MSSQL, Debezium, and Apache Kafka</strong> turns this daily chaos into a clean, reliable, event-driven system.</p><h3>The Problem Nobody Talks About</h3><p>Most applications start simple:</p><ul><li>One database</li><li>One application</li><li>Life is good</li></ul><p>Then the system grows.</p><p>Now you have:</p><ul><li>Notification services</li><li>Reporting systems</li><li>Search indexes</li><li>External integrations</li></ul><p>And suddenly, <strong>the database becomes the bottleneck and the messenger</strong>.</p><h3>The Naive Solution (and Why It Fails)</h3><p>The usual fixes look like this:</p><ul><li>Run a job every 5 minutes</li><li>Call downstream APIs after every update</li><li>Add retry logic everywhere</li><li>Pray nothing breaks at 3 AM</li></ul><p>This approach leads to:<br> <em>❌ High database load<br> ❌ Tight coupling<br> ❌ Missed updates<br> ❌ Complex, fragile code</em></p><p>There has to be a better way.</p><h3>Change Data Capture (CDC)</h3><p>CDC flips the model completely.</p><p>Instead of asking the database:</p><p><em>“Did anything change?”</em></p><p>The database says:</p><p><em>“Hey, this just changed.”</em></p><p>CDC listens directly to the <strong>transaction log</strong>, capturing:</p><ul><li><em>Inserts</em></li><li><em>Updates</em></li><li><em>Deletes</em></li></ul><p>No polling. No guessing. Only facts.</p><h3>Why MSSQL + Debezium + Kafka Works So Well</h3><h4>MSSQL</h4><p>SQL Server already knows <strong>every change</strong> via its transaction log.</p><h4>Debezium</h4><p>Debezium acts like a <strong>translator</strong>, converting raw DB changes into meaningful events.</p><h4>Kafka</h4><p>Kafka becomes the <strong>event backbone</strong>, safely storing and distributing changes to whoever needs them.</p><p>Together, they create a system where <strong>data flows naturally</strong>.</p><h3>How the Architecture Looks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eEIb0O09RWlqKVlI6SCiyw.png" /></figure><h3>Real Problems CDC Actually Solves</h3><h4>1. “Why Are We Polling the Database?”</h4><p><strong>Before:</strong><br> A job queries the Orders table every 2 minutes.</p><p><strong>After CDC:</strong><br> Only real changes are streamed instantly.</p><p><em>✅ Zero polling<br>✅ Lower DB load</em></p><h4>2. “Why Do Different Systems Show Different Data?”</h4><p><strong>Before:</strong><br> Order service says “Completed”, report says “Pending”.</p><p><strong>After CDC:</strong><br> Everyone consumes the same event.</p><p><em>✅ One version of truth</em></p><h4>3. “One Service Is Down and Everything Broke”</h4><p><strong>Before:</strong><br> Order update → API calls → failure → rollback → panic.</p><p><strong>After CDC:</strong><br> Events wait safely in Kafka.</p><p><em>✅ No data loss<br>✅ No cascading failures</em></p><h4>4. “Who Changed This Value?”</h4><p><strong>Before:</strong><br> Custom audit tables, triggers, and manual logs.</p><p><strong>After CDC:</strong><br> Before/after values are already captured.</p><p><em>✅ Built-in audit trail</em></p><h4>5. “Why Is the Dashboard Always Late?”</h4><p><strong>Before:</strong><br> Nightly ETL jobs.</p><p><strong>After CDC:</strong><br> Live event stream.</p><p><em>✅ Real-time dashboards</em></p><h4>6. “Our Code Is Full of Integration Logic”</h4><p><strong>Before:</strong><br> Business logic mixed with retries and API calls.</p><p><strong>After CDC:</strong><br> Business code stays clean. Integration is async.</p><p><em>✅ Maintainable codebase</em></p><h4>7. “We Need This Data in 5 Different Systems”</h4><p><strong>Before:</strong><br> Five integrations. Five failure points.</p><p><strong>After CDC:</strong><br> One event. Many consumers.</p><p><em>✅ Fan-out by design</em></p><h4>8. “We Need to Reprocess Old Data”</h4><p><strong>Before:</strong><br> Write DB scripts and pray.</p><p><strong>After CDC:</strong><br> Rewind Kafka offsets and replay.</p><p><em>✅ Safe recovery</em></p><h3>A Real Change Event (Simplified)</h3><pre>{<br>  &quot;op&quot;: &quot;u&quot;,<br>  &quot;before&quot;: {<br>    &quot;OrderId&quot;: 101,<br>    &quot;Status&quot;: &quot;Pending&quot;<br>  },<br>  &quot;after&quot;: {<br>    &quot;OrderId&quot;: 101,<br>    &quot;Status&quot;: &quot;Completed&quot;<br>  }<br>}</pre><p>This single event can:</p><ul><li><em>Send an email</em></li><li><em>Update analytics</em></li><li><em>Refresh search</em></li></ul><p>All without touching the main application.</p><h4>When CDC Might Be Overkill</h4><p>CDC is powerful, but not magic.</p><p>It may be too much if:</p><ul><li><strong>You have a very small system</strong></li><li><strong>Real-time updates don’t matter</strong></li><li><strong>You don’t need multiple consumers</strong></li></ul><p>But once scale enters the picture, CDC pays off quickly.</p><h3>Final Thoughts</h3><p>Change Data Capture with <strong>MSSQL, Debezium, and Kafka</strong> is not just a technical upgrade — it’s a <strong>mindset shift</strong>.</p><p>You stop asking:</p><p><em>“How do I sync data?”</em></p><p>And start thinking:</p><p><em>“Who should react to this change?”</em></p><p>That’s the foundation of modern, event-driven systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d40d621c7fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Kafka: The Backbone of Modern Real-Time Systems]]></title>
            <link>https://medium.com/@ahsankhaan2992/apache-kafka-the-backbone-of-modern-real-time-systems-da7ce1275df3?source=rss-61974b0c4733------2</link>
            <guid isPermaLink="false">https://medium.com/p/da7ce1275df3</guid>
            <dc:creator><![CDATA[Muhammad Ahsan Khan]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 07:45:30 GMT</pubDate>
            <atom:updated>2025-12-08T07:48:01.348Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*OzsTGjbLtSV-qyb13pcE2g.png" /></figure><p><em>Understanding Kafka with simple examples for developers</em></p><p>In today’s world, applications generate data at a massive scale — ride-sharing apps generate location updates every second, trading platforms update stock prices in milliseconds, and e-commerce platforms process thousands of orders per hour.</p><p>Handling this continuous stream of data is not easy.</p><p>Traditional message brokers like RabbitMQ, Azure Service Bus, or SQS are excellent for simple queues, but they struggle when the system demands <strong>high throughput, replayability, distributed processing, and real-time analytics</strong>.</p><p>This is where <strong>Apache Kafka</strong> becomes a game changer.</p><h3>What Exactly Is Kafka?</h3><p>Apache Kafka is a <strong>distributed event streaming platform</strong> that allows applications to publish, store, process, and subscribe to streams of events <strong>in real time</strong>.</p><p>The simplest definition:</p><p><strong><em>Kafka = Queue + Database + Real-Time Processing — all in one platform.</em></strong></p><p>Kafka is designed to move data <strong>fast</strong>, handle <strong>huge volume</strong>, and serve <strong>multiple consumers</strong> without slowing down.</p><h3>Why Kafka Is Different From Normal Message Brokers</h3><p>Traditional message brokers simply deliver messages and remove them after the consumer reads them.</p><p>Kafka, however, does three things <strong>simultaneously</strong>:</p><h4>Acts as a Queue</h4><p>Producers send events to a Kafka topic.<br> Consumers read from that topic.<br> Message delivery is reliable and scalable.</p><h4>Acts as Storage</h4><p>Kafka stores all events on disk for hours/days/weeks/months.<br> Consumers can rewind, replay, and reprocess events whenever needed.</p><h4>Acts as a Streaming Engine</h4><p>Kafka enables continuous, real-time stream processing.<br> You can aggregate, filter, transform, or join data on the fly using Kafka Streams or ksqlDB.</p><p>No traditional broker offers this combination.</p><h3>Kafka Internal Architecture (Explained Simply)</h3><p>Kafka works around four core building blocks:</p><h4>Topics</h4><p>A topic is like a folder where events are stored.<br> Examples:</p><ul><li>orders</li><li>payments</li><li>user-location</li></ul><h4>Partitions</h4><p>Each topic is divided into partitions for scalability.<br> Think of partitions as multiple lanes on a highway.</p><p>More partitions → more speed → more consumers can read in parallel.</p><h4>Offsets</h4><p>Every message in a partition has a unique number called an offset.<br> Consumers use offsets to keep track of what they have read.</p><h4>Brokers</h4><p>A Kafka cluster is made up of multiple brokers.<br> Data is automatically spread and replicated across brokers for:</p><ul><li>High availability</li><li>Fault tolerance</li><li>Scalability</li></ul><h3>Real-World Examples That Make Kafka Easy to Understand</h3><h4>Example 1: Uber / Careem Location Tracking</h4><p>Every driver sends their GPS location every few seconds.</p><p>This creates a massive stream:</p><pre>DriverID: 232<br>Longitude: 69.345<br>Latitude: 24.901<br>Speed: 58km/h<br>Timestamp: 2025-12-05T16:00:02Z</pre><p><strong>How Kafka Helps:</strong></p><ul><li>Kafka topics store the incoming location events.</li><li>One consumer updates the live map.</li><li>Another consumer calculates ETA.</li><li>Another stores the data in a database for analytics.</li></ul><p>Same data → used by multiple services → with no extra load.</p><h4>Example 2: Stock Trading App</h4><p>Stock prices change <strong>every millisecond</strong>.</p><p>Kafka allows:</p><ul><li>Price feed ingestion</li><li>Real-time display on UI</li><li>Alert system (e.g., “price dropped 5%”)</li><li>Storing all ticks for analytics and ML models</li></ul><p>A traditional API or message queue <em>cannot</em> keep up with such throughput.</p><h4>Example 3: E-Commerce Order System</h4><p>When a user places an order, Kafka fires an event:</p><pre>OrderID: 101012<br>UserID: 221<br>Items: [“Laptop”, “Mouse”]<br>Price: $1299<br>Status: “Created”</pre><p>Multiple services react:</p><ul><li><strong>Inventory Service</strong> → decreases stock count</li><li><strong>Payment Service</strong> → starts verification</li><li><strong>Notification Service</strong> → sends confirmation SMS</li><li><strong>Analytics</strong> → records data for dashboards</li></ul><p>Kafka ensures all systems react immediately and independently.</p><h4>Example 4: Logging and Monitoring</h4><p>All microservices send logs to Kafka.</p><pre>App: PaymentAPI<br>Level: Error<br>Message: “Payment failed due to timeout”</pre><p>Consumers:</p><ul><li>ELK stack stores logs</li><li>Alerts monitor failures</li><li>Dashboards show system performance</li></ul><p>Kafka → central log pipeline → scalable and reliable.</p><h3>When You Should Use Kafka</h3><p>Use Kafka when your system needs:</p><p>Real-time streaming<br>High throughput<br>Data replay / reprocessing<br>Scalable event-driven architecture<br>Multiple services using the same data<br>Durable storage of events</p><h3>When Kafka Is NOT a Good Choice</h3><p>Avoid Kafka if:</p><p>You just need simple request-response<br>You have low volume messaging<br>Your messages need strict priority<br>You can’t maintain a distributed cluster<br>You want instant deletion after consumption</p><h3>Final Summary</h3><p>Kafka is not just a message broker it is a complete <strong>event streaming platform</strong>.<br> It handles high-volume, high-speed data and lets multiple systems consume, replay, store, and process events at scale.</p><p>It powers the real-time backbone of:</p><ul><li>Uber</li><li>Netflix</li><li>LinkedIn</li><li>Amazon</li><li>Spotify</li><li>Banking and trading platforms</li></ul><p>If you’re designing a large-scale system that depends on live data, Kafka is one of the best tools you can choose.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da7ce1275df3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Magic Behind Real-Time Trading Apps]]></title>
            <link>https://medium.com/@ahsankhaan2992/the-magic-behind-real-time-trading-apps-2019bff31b1f?source=rss-61974b0c4733------2</link>
            <guid isPermaLink="false">https://medium.com/p/2019bff31b1f</guid>
            <dc:creator><![CDATA[Muhammad Ahsan Khan]]></dc:creator>
            <pubDate>Sat, 29 Nov 2025 17:51:58 GMT</pubDate>
            <atom:updated>2025-11-29T17:51:58.455Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zry8xxDhmBGGA24dVEAgEg.png" /></figure><p>If you’ve ever used a trading app, you’ve witnessed how fast prices move.<br> BTC jumps. Nasdaq dips. Forex ticks non-stop.<br> Charts flicker in milliseconds.</p><p>The natural question is:</p><p>👉 How do trading apps update prices so insanely fast?<br> 👉 Why does the price change <em>instantly</em> without lag?<br> 👉 Are they making API calls every millisecond?</p><p>Short answer:<br> <strong>No.</strong> API calls would be way too slow.<br> The real secret?<br> <strong>Push-based real-time systems using WebSockets, event streams, binary protocols, and powerful backend architecture.</strong></p><p>In this article, we’ll break down the entire system — from the user tapping BUY on their phone to the trade appearing on millions of devices worldwide.</p><p>Let’s go layer by layer.</p><h3>Why Traditional HTTP Polling Completely Fails</h3><p>In the early days, apps used a technique called <strong>HTTP Polling</strong>:</p><ol><li>App → “Did the price change?”</li><li>Server → “No.”</li><li>App → “Now?”</li><li>Server → “No.”</li><li>App → “Now???”</li><li>Server → <em>sigh</em> “Fine, yes.”</li></ol><p>This is extremely bad for real-time systems:</p><ul><li>Creates thousands of unnecessary requests</li><li>Overloads servers</li><li>Causes delays (high latency)</li><li>Burns mobile battery + network</li><li>Can’t scale when millions of users join</li></ul><p><strong>Polling is like knocking on someone’s door every half-second asking,<br> “Did anything happen yet?”</strong></p><p>If trading apps still used polling, your app would lag 2–3 seconds behind the actual market — and in trading, even <strong>100ms</strong> can cost money.</p><h3>The Real Hero: WebSockets (Always-Open Pipe)</h3><p>Modern trading apps use <strong>WebSockets</strong>, a persistent, always-open connection.</p><p>Here’s how it works:</p><p>Step 1: Client establishes a handshake</p><p>Your app and server say “hello” once.</p><p>Step 2: A tunnel/pipe is created</p><p>No more repeating requests.</p><p>Step 3: Server pushes updates automatically</p><p>Whenever the market moves, the server instantly sends the update to your app.</p><p><strong>No delay, no request overhead, no waiting.</strong></p><p>This is why:</p><ul><li>Prices change instantly</li><li>Charts feel “alive”</li><li>Ticker text is always moving</li><li>Orders update in milliseconds</li></ul><p>Think of WebSockets as a <strong>water pipe</strong> permanently connected between your phone and the server.<br> Water (price updates) flow through instantly.</p><h3>But Wait… There’s Much More Than WebSockets</h3><p>WebSockets solve the connection problem — but real-time trading needs <strong>ultra-fast messaging inside the backend</strong> too.</p><p>A modern trading system uses:</p><h4>Kafka or Redis Streams</h4><p>To handle millions of events per second.</p><h4>Protocol Buffers (Binary Encoding)</h4><p>Binary messages are much faster and smaller than JSON.</p><p><strong>Example:</strong></p><p><strong>JSON:</strong></p><pre>{ &quot;price&quot;: 100.25, &quot;volume&quot;: 50 }</pre><p><strong>Binary:</strong></p><pre>0101010011010101</pre><p>Binary takes <strong>10x less space</strong> and parses <strong>20x faster</strong>.</p><h4>Conflation</h4><p>If price changes 1000 times in 1 second, the app doesn’t receive 1000 updates — only the latest or meaningful ones.</p><p>This prevents:</p><ul><li>UI freezing</li><li>Battery drain</li><li>Network overload</li></ul><h4>Throttling</h4><p>Apps don’t update the screen every microsecond. They batch updates every <strong>30–50ms</strong> to keep the UI smooth.</p><p>WebSockets + Binary + Conflation + Throttling = blazing fast real-time experience that feels natural.</p><h3>4. The Full Architecture (Behind Every Trade)</h3><p>Let’s see the entire flow from the moment a user interacts with the app:</p><h4>User taps BUY/SELL</h4><p>Your order goes to the <strong>Order Gateway</strong>, which validates:</p><ul><li>Is the user authenticated?</li><li>Is the account funded?</li><li>Is the order size allowed?</li><li>Risk checks (allowed symbols, limits, etc.)</li></ul><h4>Order reaches the Matching Engine</h4><p>The <strong>Matching Engine</strong> is the heart of an exchange.</p><p>Its job:</p><ul><li>Match buyers with sellers</li><li>Update the order book</li><li>Generate trades</li><li>Create new market prices</li></ul><p>Matching engines run in microseconds.<br> Yes — <em>millionths</em> of a second.</p><h4>Price updates sent to Kafka / Redis</h4><p>Every new trade or price change is published into an event streaming system:</p><ul><li><strong>Kafka</strong> (for huge throughput)</li><li><strong>Redis Streams</strong> (for ultra-fast memory-based speeds)</li></ul><p>These systems can process <strong>millions of messages per second</strong>.</p><h4>Real-time distributor → WebSocket Server</h4><p>This layer:</p><ul><li>Converts internal messages to client-friendly formats (binary)</li><li>Applies conflation/throttling</li><li>Handles load balancing across thousand WebSocket servers</li><li>Ensures each user receives exactly what they need</li></ul><h4>WebSocket → Your Trading App</h4><p>Finally:</p><ul><li>Price ticks</li><li>Candlestick updates</li><li>Order book levels</li><li>Recent trades</li><li>Portfolio changes</li></ul><p>All are pushed live to your screen.</p><p>This is why your chart moves exactly when the market moves.</p><h3>Why This Engineering Matters</h3><p>Even <strong>100ms delay</strong> can cause:</p><ul><li>Wrong entry/exit prices</li><li>Missed opportunities</li><li>Misleading charts</li><li>Bad user experience</li></ul><p>Real-time trading engineering solves this by ensuring:</p><p>✔ Millisecond updates<br> ✔ Scalable architecture<br> ✔ Zero lag under millions of users<br> ✔ Smooth and fluid UI<br> ✔ Reliable event delivery</p><p>This is why trading apps feel fast and responsive even during heavy volatility.</p><h3>Final Summary (The Whole Story in One Line)</h3><p><strong>Real-time trading apps = WebSockets + Event Streams + Binary Data + Conflation + Matching Engines + Throttling.</strong></p><p>Not magic.<br> Just beautiful engineering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2019bff31b1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Use JSON Web Tokens (JWT) for Secure Authentication]]></title>
            <link>https://medium.com/@ahsankhaan2992/why-use-json-web-tokens-jwt-for-secure-authentication-b999830bba39?source=rss-61974b0c4733------2</link>
            <guid isPermaLink="false">https://medium.com/p/b999830bba39</guid>
            <dc:creator><![CDATA[Muhammad Ahsan Khan]]></dc:creator>
            <pubDate>Sun, 15 Oct 2023 19:39:19 GMT</pubDate>
            <atom:updated>2023-10-15T19:39:19.750Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*Tm-DH5HzQW1giJ3HCh3-dw.png" /></figure><h3><strong>Introduction:</strong></h3><p>In an age where online security is paramount, it’s essential for developers and businesses to choose the right tools to protect sensitive data and ensure the confidentiality and integrity of user information. JSON Web Tokens (JWT) have emerged as a powerful and flexible solution for secure authentication and data exchange. In this blog post, we will delve into the reasons why JWT has become a popular choice for handling authentication and authorization in web applications.</p><h3><strong>Stateless and Scalable:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*fmkr3LdtN_9TS-cOKFTn3w.png" /></figure><p>One of the key advantages of using JSON Web Tokens is their stateless nature. Unlike traditional session-based authentication, JWTs do not require the server to store user sessions, making them highly scalable. This means that as your application grows, you won’t be burdened with the overhead of managing user session data. JWTs contain all the information needed for authentication and authorization, reducing server-side storage requirements and enabling easy horizontal scaling.</p><h3><strong>Cross-Platform Compatibility:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*MJMOPJ8GYr2Ux32gCNexVA.png" /></figure><p>JWTs are based on open standards and can be used in various programming languages and platforms. This cross-platform compatibility makes JWTs a versatile choice for authentication in a diverse range of applications, including web, mobile, and API-based services. You can create JWTs in one language or platform and easily verify them in another, allowing for greater flexibility in building and expanding your application ecosystem.</p><h3>Enhanced Security:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n6SvlSNqXcLBxLHAo0d9IA.png" /></figure><p>Security is a paramount concern when it comes to authentication. JWTs address this concern by offering a secure way to transmit and verify user identity. They can be signed and optionally encrypted, ensuring data integrity and confidentiality. When a user logs in and receives a JWT, they can trust that the token has not been tampered with. This makes it difficult for malicious actors to alter the token and gain unauthorized access to resources.</p><h3>Easy Integration with Third-Party Services:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*eUMSytVOPLft36rVxLQSvA.png" /></figure><p>In the modern web landscape, integrating with third-party services is a common requirement for many applications. JWTs facilitate this process by allowing you to exchange authentication and authorization data securely between your application and external services. For example, if your application needs to access a user’s Google Drive or Facebook data, you can use JWTs to authenticate your application with these services without the need to store users’ passwords.</p><h3>Reduced Database Queries:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PUhN07vWAc6Dbu5NDPrxSw.png" /></figure><p>Traditional session-based authentication typically requires frequent database queries to retrieve user session data. This can put a significant load on your database, especially when handling a large number of concurrent users. With JWTs, the user’s identity and permissions are embedded in the token, eliminating the need for repeated database queries. This can significantly reduce the load on your database, leading to better application performance and cost savings.</p><h3>Granular Authorization:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*BWVeSfikYV3UWR60eRk5oQ.jpeg" /></figure><p>JWTs can carry user-specific information, which allows for fine-grained authorization. You can include roles, permissions, and other user attributes in the token, enabling you to control what users can access within your application. This granular authorization is crucial for protecting sensitive data and resources while providing a tailored user experience.</p><h3>Conclusion:</h3><p>JSON Web Tokens have become a popular choice for secure authentication in web applications due to their stateless nature, cross-platform compatibility, enhanced security, and ease of integration with third-party services. They also reduce the load on your database and offer granular authorization capabilities. If you’re looking for a robust and flexible solution to manage user authentication and authorization, JWTs are an excellent choice. However, it’s crucial to implement JWTs correctly, including proper token validation, secure storage, and token expiration strategies, to ensure they remain a strong layer of security for your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b999830bba39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-Tuning Chat GPT: Enhancing Conversational AI for Real-World Applications]]></title>
            <link>https://medium.com/@ahsankhaan2992/fine-tuning-chat-gpt-enhancing-conversational-ai-for-real-world-applications-382cf0433a85?source=rss-61974b0c4733------2</link>
            <guid isPermaLink="false">https://medium.com/p/382cf0433a85</guid>
            <dc:creator><![CDATA[Muhammad Ahsan Khan]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 07:31:01 GMT</pubDate>
            <atom:updated>2023-07-04T07:31:01.088Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v-DZleDIV-mWBzSZHnaFFw.jpeg" /></figure><h3>Prerequisites</h3><p>The following guide, we are using on our machine:</p><p>· Python</p><p>· Node.js</p><p>You’ll also need an OpenAI API Key. You can get one at <a href="https://openai.com/">https://openai.com</a>.</p><h3>Getting started</h3><p>To get started, we’ll create a new Node.js project in an empty directory:</p><pre>mkdir custom-ai-model</pre><pre>cd custom-ai-model</pre><pre>npm init --y</pre><p>Update the new <strong>package.json</strong> file to use ES Modules by adding this line of configuration:</p><pre>&quot;type&quot;: &quot;module&quot;,</pre><p>Next, we’ll install the openai npm package:</p><pre>npm install openai</pre><p>Finally, we’ll install the OpenAI CLI and the OpenAI data lib (For Data Transformation):</p><pre>pip install --upgrade openai openai&quot;[datalib]&quot;<br></pre><p>Now we’re ready to start writing some code!</p><h3>Creating the training data</h3><p>There are a handful of models available from OpenAI, but when fine-tuning the original GPT-3 base models are currently the only models available to start from, like <strong>Davinci</strong>, <strong>curie</strong>, <strong>babbage</strong>, and <strong>ada</strong>. We’ll be using <strong>Davinci</strong>.</p><p>Your data needs to be created in a JSONL document in the following format (here the prompt is the question asked by the user and completion would be the answer to that question). If you have a JSON file you or prompt and completion:</p><p><strong>Example</strong>:</p><pre>[{&quot;prompt&quot;: &quot;What is the capital of France? &quot;,&quot;completion&quot;: &quot;The capital of France is Paris.&quot;},{&quot;prompt&quot;: &quot;Who painted the Mona Lisa?&quot;,&quot;completion&quot;: &quot;The Mona Lisa was painted by Leonardo da Vinci.&quot;},{&quot;prompt&quot;: &quot;What is the symbol for hydrogen?&quot;,&quot;completion&quot;: &quot;The symbol for hydrogen is H.&quot;}]</pre><p>You will have to convert your JSON to JSONL with the help of the following website “<a href="https://tableconvert.com/json-to-jsonlines">https://tableconvert.com/json-to-jsonlines</a>” this will provide the JSON file to download which will look like this:</p><p><strong>Example:</strong></p><p>{&quot;prompt&quot;: &quot;What is the capital of France?&quot;, &quot;completion&quot;: &quot;The capital of France is Paris.&quot;}</p><p>{&quot;prompt&quot;: &quot;Who painted the Mona Lisa?&quot;, &quot;completion&quot;: &quot;The Mona Lisa was painted by Leonardo da Vinci.&quot;}</p><p>{&quot;prompt&quot;: &quot;What is the symbol for hydrogen?&quot;, &quot;completion&quot;: &quot;The symbol for hydrogen is H.&quot;}</p><p>{&quot;prompt&quot;: &quot;What is the largest planet in our solar system?&quot;, &quot;completion&quot;: &quot;The largest planet in our solar system is Jupiter.&quot;}</p><p><strong>It is recommended to provide at least a few hundred of these examples, with most sources recommending 500 or more.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9tmCLTaUHi4NxTsouQ1wjw.png" /></figure><p>Once you’ve created your document, OpenAI provides a command line utility to improve the format of your data and is recommended to run before you upload.</p><pre>openai tools fine_tunes.prepare_data -f &lt;LOCAL_FILE.jsonl&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AFh__ooxZQ0yxRMzKuMQHg.png" /></figure><p>Once your data set is ready, we can create a script to upload it to OpenAI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*QrCPN-_QD0n_mH85Gsfceg.png" /></figure><p>This is the refined data file with the help of the Openai tool</p><h3>Creating the API interface</h3><p>This file will define the API that we’ll be using to interact with the OpenAI APIs.</p><p>Since we’ll be re-using this code over and over, we’ll separate it into its file and just import it into our other files.</p><p>Create a file named <strong>api.js</strong> and add the following code:</p><p><strong>CODE:</strong></p><pre>/* api.js */</pre><pre>import { Configuration, OpenAIApi } from &#39;openai&#39;<br>const openaiApiKey = &lt;Your Open Api Key&gt;<br>const configuration = new Configuration({<br>apiKey: openaiApiKey<br>})<br>export const openai = new OpenAIApi(configuration)</pre><h3>Uploading the training data</h3><p>Now that we’ve created the API, we can use it to upload our file to use later.</p><p>Create a file named <strong>uploadFile.js</strong> and add the following code:</p><p><strong>CODE:</strong></p><pre>/* uploadFile.js */</pre><pre>import {openai } from &#39;./api.js&#39;<br>import fs from &#39;fs&#39;<br><br>async function upload() {<br>try {<br>const response = await openai.createFile(<br>fs.createReadStream(&#39;./data_prepared.jsonl&#39;),<br>&quot;fine-tune&quot;<br>);<br>console.log(&#39;File ID: &#39;, response.data.id)<br>} catch (err) {<br>console.log(&#39;err: &#39;, err)<br>}<br>}<br><br>upload()</pre><p>Next, run the script:</p><pre>node uploadFile.js</pre><p>When the upload is complete, take note of the File ID that is logged out; we’ll need it in the next step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*_jZROXE6Xe2ZbEno7TZZyw.png" /></figure><h3>Creating the Fine Tune</h3><p>Now that we’ve uploaded the training data and have the file ID, we can use it to custom-train our model.</p><p>To do so, create a new file named <strong>createFineTune.js</strong> and add the following code:</p><p><strong>CODE:</strong></p><pre>/* createFineTune.js */</pre><pre>import { openai } from &#39;./api.js&#39;<br><br>async function createFineTune() {<br>  try {<br>    const response = await openai.createFineTune({<br>      training_file: &#39;your-file-id&#39;,<br>      model: &#39;davinci&#39;<br>    })<br>    console.log(&#39;response: &#39;, response)<br>  } catch (err) {<br>    console.log(&#39;error: &#39;, err.response.data.error)<br>  }<br>}<br><br>createFineTune()</pre><p>Next, execute the script to start fine-tuning your model:</p><pre>node createFineTune.js</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*0AwMe0O_G-HSaCbrmoorpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*3TcXJQpFk5W-jpvXa1Nh3g.png" /></figure><h3>Listing your Fine Tunes</h3><p>Once the fine tune is created, it will take some time to process. We can get the status of the fine tune, as well as the model ID, by calling the listFineTunes API method.</p><p>Create a new file named <strong>listFineTunes.js</strong> and add the following code:</p><p><strong>CODE:</strong></p><pre>/* listFineTunes.js */</pre><pre>import { openai } from &#39;./api.js&#39;<br><br>async function listFineTunes() {<br>  try {<br>    const response = await openai.listFineTunes()<br>    console.log(&#39;data: &#39;, response.data.data)<br>  } catch (err) {<br>    console.log(&#39;error:&#39;, err)<br>  }<br>}<br><br>listFineTunes()</pre><p>Run the script.</p><pre>node listFineTunes.js</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*fGxBhBxbodT6VETh9aIYbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*QbgeEnwyRH2LlVT9It2DEA.png" /></figure><p>Try again after a few minutes (it depends on how large the data set is)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*fGxBhBxbodT6VETh9aIYbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RoNJyK7g89IyMih_4nF_Dw.png" /></figure><p>It will take the process a few minutes to finish. Once the process is completed and you rerun the script, you should see the fine_tuned_model field populated with the new model ID.</p><p>Take note of this fine_tuned_model ID, you’ll need it in the next step.</p><h3>Testing it out</h3><p>Now that the fine tune has been processed and our. the new model is ready, we can try it out!</p><p>Create a new file named <strong>createCompletion.js</strong>. Here, add the following code. Be sure to update the fine_tuned_model value with your model name:</p><p><strong>CODE:</strong></p><pre>/* createCompletion.js */</pre><pre>import { openai } from &#39;./api.js&#39;<br><br>async function createCompletion() {<br>  try {<br>    const response = await openai.createCompletion({<br>      model: &#39;your-custom-model-name&#39;,<br>      prompt: &#39;What is Lens Protocol&#39;,<br>      max_tokens: 200<br>    })<br>    if (response.data) {<br>      console.log(&#39;choices: &#39;, response.data.choices)<br>    }<br>  } catch (err) {<br>    console.log(&#39;err: &#39;, err)<br>  }<br>}<br><br>createCompletion()</pre><p>Run the script:</p><pre>node createCompletion.js</pre><h3>Congratulations</h3><p>You’ve successfully deployed your custom model using GPT3!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=382cf0433a85" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>