<?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 SUBEESH PALAMADATHIL on Medium]]></title>
        <description><![CDATA[Stories by SUBEESH PALAMADATHIL on Medium]]></description>
        <link>https://medium.com/@subi4020?source=rss-d92a12fc552f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JtgU9UG35WV4zRKU</url>
            <title>Stories by SUBEESH PALAMADATHIL on Medium</title>
            <link>https://medium.com/@subi4020?source=rss-d92a12fc552f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:05:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@subi4020/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[From Basic Authentication to DPoP: My Journey of Building a More Secure Authentication System]]></title>
            <link>https://medium.com/@subi4020/from-basic-authentication-to-dpop-my-journey-of-building-a-more-secure-authentication-system-22dd0891ac88?source=rss-d92a12fc552f------2</link>
            <guid isPermaLink="false">https://medium.com/p/22dd0891ac88</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[SUBEESH PALAMADATHIL]]></dc:creator>
            <pubDate>Sat, 28 Nov 2026 05:49:45 GMT</pubDate>
            <atom:updated>2026-11-28T05:49:45.989Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9RLN4_fQnkx0KV3G969OkA.jpeg" /></figure><p><em>It started with a simple goal: build a secure authentication system for my social media backend. But every improvement introduced new questions, and every question led me deeper into authentication security.</em></p><h3>It Started With a Simple Goal</h3><p>While developing my social media backend, I wanted to implement a secure authentication system rather than simply adding a username and password login and moving on to the next feature.</p><p>Initially, I started with traditional email/username and password authentication. It was a straightforward starting point, but I wanted to provide users with a more convenient login experience as well.</p><p>So, I extended the authentication system to support social login through Google, Facebook, and X.</p><p>However, integrating X introduced an interesting challenge.</p><p>Unlike Google and Facebook, X does not provide the user’s email address through its standard authentication flow. Since my application relies on email addresses for user registration and account management, I needed to find a reasonable solution.</p><p>I decided to introduce an additional registration step for X users. Before they could log in using X, they had to register with an email address associated with their X account. Once that initial registration was completed, they could use X for subsequent logins.</p><p>It was a small adjustment, but it reminded me that authentication integrations are not always identical. Each provider has its own limitations, and the application architecture needs to account for them.</p><h3>Introducing JWT Access and Refresh Tokens</h3><p>After implementing the initial authentication mechanisms, I moved towards JWT-based authentication.</p><p>I implemented access tokens and refresh tokens to manage authenticated sessions.</p><p>The basic idea was simple:</p><ul><li>Access tokens would be short-lived and used to authorize API requests.</li><li>Refresh tokens would allow users to obtain new access tokens without repeatedly entering their credentials.</li></ul><p>Initially, this seemed like a reasonable and widely adopted solution.</p><p>But then I started asking myself a question:</p><p><strong>What happens if someone steals a refresh token?</strong></p><p>That question changed the direction of my implementation.</p><h3>The First Security Concern: Refresh Token Theft</h3><p>I realized that a stolen refresh token could potentially give an attacker prolonged access to a user’s account.</p><p>If the attacker obtained a valid refresh token, they could repeatedly use it to request new access tokens.</p><p>The situation was particularly concerning with stateless JWT-based refresh tokens.</p><p>Once issued, a JWT cannot simply be invalidated by changing something inside the token itself. Unless additional server-side validation mechanisms are implemented, a stolen token may remain usable until its expiration.</p><p>Imagine a refresh token with a 30-day lifetime.</p><p>Even if the legitimate user changes their password or suspects suspicious activity, the stolen token could potentially remain valid until expiration unless the server has a mechanism to revoke it.</p><p>I didn’t want to leave that security gap in my authentication architecture.</p><p>So, I started researching alternative approaches.</p><h3>Moving to Opaque Refresh Tokens</h3><p>During my research, I came across opaque refresh tokens.</p><p>Unlike JWTs, opaque tokens do not contain readable claims or user information. They are random, unpredictable values that the server validates against its own session records.</p><p>This introduced an important advantage.</p><p>Since the server maintains control over the refresh token’s validity, it can revoke a session, invalidate a token, and detect refresh-token reuse.</p><p>I redesigned my authentication mechanism:</p><ul><li>JWT remained the format for access tokens.</li><li>Opaque tokens were introduced for refresh tokens.</li><li>Server-side session management was implemented.</li><li>Redis was used for session tracking and invalidation.</li><li>Refresh-token reuse detection was introduced.</li></ul><p>This was a significant improvement.</p><p>But I wasn’t finished.</p><h3>The Next Question: What If the Attacker Refreshes First?</h3><p>While reviewing the new architecture, I identified another potential security scenario.</p><p>Consider this situation:</p><ol><li>An attacker steals a user’s refresh token.</li><li>The attacker uses it before the legitimate user.</li><li>The attacker obtains a new access token.</li><li>The server detects refresh-token reuse and invalidates the compromised session.</li></ol><p>Although server-side invalidation can prevent continued access, there may still be a short window during which an access token already issued to the attacker remains valid.</p><p>This raised another question:</p><p><strong>How can I make a stolen token insufficient on its own?</strong></p><p>I wanted to go beyond simply detecting token theft. I wanted to make stolen tokens much harder to use.</p><h3>Discovering DPoP: Binding Tokens to a Client Key</h3><p>That investigation led me to DPoP (Demonstrating Proof of Possession).</p><p>DPoP introduces a mechanism that binds token usage to a cryptographic key.</p><p>Instead of relying only on possession of a token, the client must also demonstrate possession of the corresponding private key.</p><p>I decided to implement a client-side DPoP mechanism using a non-extractable cryptographic key.</p><p>The idea was to make the authentication process depend on both:</p><ul><li>The issued access or refresh token.</li><li>A valid cryptographic proof generated using the client’s private key.</li></ul><p>This changes the security model considerably.</p><p>Even if an attacker manages to obtain a token, possessing that token alone should not be sufficient to use it successfully. The attacker would also need the corresponding private-key proof.</p><p>I integrated this mechanism into my authentication flow for both access-token and refresh-token operations.</p><p>It was one of the most interesting parts of the entire implementation because I was no longer thinking only about token expiration or revocation. I was thinking about proof of possession and reducing the usefulness of stolen credentials.</p><p>Of course, DPoP is not a guarantee against every attack. Its effectiveness also depends on correct server-side proof validation, key management, replay protection, and protection against client-side compromise.</p><p>But it adds another important defensive layer.</p><h3>Moving to the JOSE Ecosystem</h3><p>As I explored modern authentication implementations, I also decided to move away from the traditional jsonwebtoken package and adopt the JOSE ecosystem using the jose package.</p><p>One of my motivations was to align my implementation with modern standards-based JWT and cryptographic workflows, including approaches commonly used in cloud and edge environments.</p><p>I migrated my JWT-related signing and verification functionality to jose.</p><p>This gave me a more standards-oriented foundation for working with JWTs and cryptographic operations.</p><p>It was another opportunity to understand authentication beyond simply generating and verifying tokens.</p><h3>Additional Security Improvements</h3><p>Alongside the token architecture, I also implemented additional security measures.</p><p><strong>1. Refresh-token reuse detection</strong></p><p>The system tracks refresh-token usage and can identify suspicious reuse scenarios, allowing compromised sessions to be invalidated.</p><p><strong>2. Server-side session invalidation</strong></p><p>Redis-based session management provides server-side control over authentication sessions.</p><p><strong>3. DPoP-based proof of possession</strong></p><p>Access and refresh token usage requires cryptographic proof associated with the client’s key.</p><p><strong>4. Frequent password-change capability</strong></p><p>I implemented password-change functionality so users can update their credentials and maintain better control over their accounts.</p><p><strong>5. Input sanitization and validation</strong></p><p>I also worked on validating and sanitizing user input to reduce injection risks, including SQL-injection-style payloads.</p><p>Input sanitization is only one part of injection prevention; database-specific protections, parameterized queries, and proper validation are equally important.</p><h3>What I Learned From This Journey</h3><p>The biggest lesson was that authentication is not simply about verifying a username and password.</p><p>It involves understanding multiple layers of security:</p><ul><li>Credential security.</li><li>Token lifecycle management.</li><li>Session management.</li><li>Token revocation.</li><li>Refresh-token rotation and reuse detection.</li><li>Cryptographic proof of possession.</li><li>Replay protection.</li><li>Client-side security.</li><li>Input validation and injection prevention.</li></ul><p>More importantly, I learned to approach software development differently.</p><p>Instead of asking only whether my implementation works, I started asking:</p><ul><li>What happens if a token is stolen?</li><li>What happens if an attacker refreshes before the legitimate user?</li><li>Can a compromised session be invalidated immediately?</li><li>Can a stolen token be used from another client?</li><li>What happens if an attacker replays an old authentication request?</li><li>What happens if the client environment itself is compromised?</li></ul><p>These questions pushed me to research, redesign, and improve the architecture repeatedly.</p><h3>Final Thoughts</h3><p>This journey started with a simple requirement: implement authentication for my social media application.</p><p>It gradually evolved into an exploration of JWTs, opaque refresh tokens, Redis-based session management, token reuse detection, JOSE, and DPoP.</p><p>I didn’t implement everything in one day, and I certainly didn’t know all the answers at the beginning.</p><p>I learned by identifying potential weaknesses, researching possible solutions, experimenting with different approaches, and revisiting my implementation.</p><p>For me, this is one of the most valuable aspects of backend engineering.</p><p><strong>Building software is not just about making things work. It is about understanding how things can fail, anticipating how they can be misused, and continuously improving the system.</strong></p><p>My authentication system is still something I want to keep reviewing and improving. Security is not a destination; it is an ongoing engineering responsibility.</p><p>And this project has taught me that some of the best engineering decisions begin with a simple question:</p><p><em>What if someone tries to break what I just built?</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22dd0891ac88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built My Own IndexedDB Caching System in React — Then Discovered a Better Way to Do It]]></title>
            <link>https://medium.com/@subi4020/i-built-my-own-indexeddb-caching-system-in-react-then-discovered-a-better-way-to-do-it-27ed521385bf?source=rss-d92a12fc552f------2</link>
            <guid isPermaLink="false">https://medium.com/p/27ed521385bf</guid>
            <category><![CDATA[improve-code-quality]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[tanstack-query]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-query]]></category>
            <dc:creator><![CDATA[SUBEESH PALAMADATHIL]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 09:48:10 GMT</pubDate>
            <atom:updated>2026-11-20T09:48:10.985Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1iGcXDMLMLiqQFfas7-JoA.jpeg" /></figure><p><strong>From 1,460+ lines of custom IndexedDB implementation to a much cleaner approach with TanStack Query’s PersistQueryClientProvider.</strong></p><p>Sometimes, as developers, we enjoy building things from scratch. We want complete control over how our applications work, how data is stored, how it gets updated, and how different components communicate.</p><p>I was no exception.</p><p>While developing my social media frontend application, I wanted to implement a persistent client-side caching mechanism using IndexedDB. My goal was simple:</p><ul><li>Store frequently accessed backend data locally.</li><li>Avoid unnecessary API requests.</li><li>Keep cached data available even after refreshing the browser.</li><li>Synchronize backend updates with the local database.</li><li>Automatically update the UI whenever cached data changed.</li></ul><p>But achieving these goals turned into a much bigger implementation than I initially expected.</p><h3>The Beginning: Building Everything from Scratch</h3><p>Instead of immediately adopting an existing caching library, I decided to work directly with the browser’s native IndexedDB API.</p><p>I implemented the complete caching mechanism myself, including:</p><ul><li>Database initialization and connection management.</li><li>Object store creation and management.</li><li>CRUD operations.</li><li>Data insertion, retrieval, updating, and deletion.</li><li>Synchronization of backend responses with IndexedDB.</li><li>Handling cache updates after different API operations.</li><li>Managing asynchronous database operations and errors.</li></ul><p>Whenever my application fetched data from the backend, I manually updated the corresponding IndexedDB records.</p><p>But storing data wasn’t enough. I also needed to make sure React components reflected those changes.</p><h3>The Challenge: Keeping IndexedDB and React State in Sync</h3><p>IndexedDB is not inherently reactive. Updating a database record does not automatically trigger a React component re-render.</p><p>So I built another layer on top of it.</p><p>I used:</p><ul><li>useState to maintain component-level data.</li><li>Context API to share application state across components.</li><li>useEffect to synchronize fetched data and manage updates.</li><li>Custom functions to coordinate backend responses, IndexedDB updates, and React state changes.</li></ul><p>As the application grew, so did the complexity.</p><p>Eventually, my implementation reached:</p><ul><li><strong>1,460+ lines</strong> dedicated to custom IndexedDB functionality.</li><li><strong>3,000+ additional lines</strong> involving useState, useEffect, Context API, and related state synchronization logic.</li></ul><p>That is more than 4,460 lines of code just around caching and state management!</p><p>Was it a waste of time? Not necessarily.</p><p>Building it myself gave me a much deeper understanding of IndexedDB, asynchronous browser storage, React rendering, state synchronization, and data consistency.</p><p>I had achieved something important: low-level control over how my application managed its client-side data.</p><p>However, I also started recognizing another engineering principle:</p><p><strong>Having complete control doesn’t always mean having the best architecture.</strong></p><h3>The Turning Point: Discovering PersistQueryClientProvider</h3><p>As the project evolved, I started exploring ways to simplify the implementation without sacrificing the functionality.</p><p>That’s when I moved towards TanStack Query and its persistence integration.</p><p>Instead of manually managing every cache operation and synchronizing React state with IndexedDB, I could leverage:</p><ul><li>TanStack Query for server-state management.</li><li>Query caching and automatic cache updates.</li><li>PersistQueryClientProvider for persisting query cache.</li><li>IndexedDB through a suitable persistence persister.</li><li>Query invalidation and refetching for keeping server data fresh.</li></ul><p>This significantly changed how I approached client-side data management.</p><p>I no longer needed to manually coordinate every backend fetch, database update, and component re-render.</p><p>The library handles much of that infrastructure for me.</p><p>And the best part? I could spend more time building actual product features instead of maintaining thousands of lines of custom synchronization logic.</p><h3>An Important Clarification: I Didn’t Throw Away My Original Implementation</h3><p>One thing I’d like to clarify: adopting TanStack Query didn’t mean completely abandoning my original IndexedDB implementation.</p><p>I still value the custom caching infrastructure I developed because it gave me complete control over how data was stored, retrieved, updated, and synchronized within my application.</p><p>Instead of rewriting everything, I started exploring how to integrate the new approach into my existing architecture.</p><p>The idea was to gradually move suitable server-state management responsibilities towards TanStack Query while retaining my custom IndexedDB functionalities wherever they were still useful.</p><p>This allowed me to take advantage of an established caching and persistence architecture without unnecessarily throwing away the work I’d already invested in.</p><p>In other words, this wasn’t a complete replacement. It was an architectural improvement through gradual integration.</p><p>I believe this is an important lesson for developers: discovering a better tool doesn’t always mean you need to rewrite your entire application. Sometimes, the smartest approach is to integrate new technologies incrementally while preserving the parts of your existing architecture that still serve a purpose.</p><h3>A Short Tutorial: Implementing Persistent Query Caching in React</h3><p>Let’s see how you can implement a similar architecture in your React application.</p><h4>Step 1: Install the dependencies</h4><pre>npm install @tanstack/react-query \<br>@tanstack/react-query-persist-client \<br>@tanstack/query-async-storage-persister \<br>idb</pre><p>Here, idb provides a convenient Promise-based wrapper around native IndexedDB.</p><h4>Step 2: Create an IndexedDB persistence persister</h4><p>Create utils/indexedDBPersister.ts:</p><pre>import { openDB } from &#39;idb&#39;;<br>import type { Persister } from<br>    &#39;@tanstack/react-query-persist-client&#39;;<br><br>const DB_NAME = &#39;app-query-cache&#39;;<br>const STORE_NAME = &#39;query-cache&#39;;<br><br>const dbPromise = openDB(DB_NAME, 1, {<br>    upgrade(db) {<br>        db.createObjectStore(STORE_NAME);<br>    }<br>});<br><br>export const indexedDBPersister: Persister = {<br>    async persistClient(client) {<br>        const db = await dbPromise;<br><br>        await db.put(<br>            STORE_NAME,<br>            client,<br>            &#39;persisted-client&#39;<br>        );<br>    },<br><br>async restoreClient() {<br>        const db = await dbPromise;<br><br>        return db.get(<br>            STORE_NAME,<br>            &#39;persisted-client&#39;<br>        );<br>    },<br><br>    async removeClient() {<br>        const db = await dbPromise;<br><br>        await db.delete(<br>            STORE_NAME,<br>            &#39;persisted-client&#39;<br>        );<br>    }<br>};</pre><p>We have now created a persistence layer using IndexedDB without manually implementing all the database operations.</p><h4>Step 3: Configure PersistQueryClientProvider</h4><p>Create main.tsx:</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br><br>import {<br>    QueryClient<br>} from &#39;@tanstack/react-query&#39;;<br><br>import {<br>    PersistQueryClientProvider<br>} from &#39;@tanstack/react-query-persist-client&#39;;<br><br>import { indexedDBPersister } from<br>    &#39;./utils/indexedDBPersister&#39;;<br>import App from &#39;./App&#39;;<br><br>const queryClient = new QueryClient({<br>    defaultOptions: {<br>        queries: {<br>            staleTime: 1000 * 60 * 5,<br>            gcTime: 1000 * 60 * 60 * 24<br>        }<br>    }<br>});<br><br>ReactDOM.createRoot(<br>    document.getElementById(&#39;root&#39;)!<br>).render(<br>    &lt;React.StrictMode&gt;<br>        &lt;PersistQueryClientProvider<br>            client={queryClient}<br>            persistOptions={{<br>                persister: indexedDBPersister,<br>                maxAge: 1000 * 60 * 60 * 24<br>            }}<br>        &gt;<br>            &lt;App /&gt;<br>      &lt;/PersistQueryClientProvider&gt;<br>    &lt;/React.StrictMode&gt;<br>);<br></pre><p>Now your React application has a query cache that can be persisted to IndexedDB and restored after a page reload.</p><h4>Step 4: Fetch data using useQuery</h4><p>Instead of manually coordinating API calls, IndexedDB updates, and React state:</p><pre>import { useQuery } from &#39;@tanstack/react-query&#39;;<br><br>async function fetchPosts() {<br>    const response = await fetch(&#39;/api/posts&#39;);<br><br>    if (!response.ok) {<br>        throw new Error(&#39;Failed to fetch posts&#39;);<br>    }<br><br>    return response.json();<br>}<br><br>function Posts() {<br>    const {<br>        data,<br>        isLoading,<br>        error<br>    } = useQuery({<br>        queryKey: [&#39;posts&#39;],<br>        queryFn: fetchPosts<br>    });<br><br>    if (isLoading) return &lt;p&gt;Loading...&lt;/p&gt;;<br><br>    if (error) return &lt;p&gt;Something went wrong.&lt;/p&gt;;<br><br>    return (<br>        &lt;div&gt;<br>            {data?.map((post: any) =&gt; (<br>                &lt;div key={post._id}&gt;<br>                    {post.content}<br>                &lt;/div&gt;<br>            ))}<br>        &lt;/div&gt;<br>    );<br>}<br><br>export default Posts;</pre><p>TanStack Query manages the server-state lifecycle, while the persistence provider takes care of persisting and restoring the query cache.</p><h4>Step 5: Update or invalidate cached data</h4><p>After creating a post, you can invalidate the relevant query:</p><pre>const queryClient = useQueryClient();<br><br>await createPost(postData);<br><br>queryClient.invalidateQueries({<br>    queryKey: [&#39;posts&#39;]<br>});</pre><p>Alternatively, you can update the cache directly using setQueryData when you already have the updated server response.</p><h3>A Few Important Things to Remember</h3><p>This approach doesn’t eliminate the need to understand caching or data consistency.</p><p>For production applications, consider:</p><ol><li><strong>Cache expiration:</strong> Configure staleTime, gcTime, and persistence maxAge according to your requirements.</li><li><strong>Data freshness:</strong> Persisted data can be outdated. Use appropriate refetch and invalidation strategies.</li><li><strong>Authentication:</strong> Clear or isolate persisted user-specific data when users log out or switch accounts.</li><li><strong>Cache versioning:</strong> Handle schema changes and incompatible persisted cache versions.</li><li><strong>Storage limitations:</strong> IndexedDB is browser-managed storage, and users or browsers can clear it.</li></ol><p>Also, remember that persisted query caching is not a replacement for server-side validation, authorization, or database consistency.</p><h3>Final Thoughts</h3><p>Looking back, implementing IndexedDB from scratch was a valuable learning experience. It helped me understand what happens beneath the abstractions we commonly use in modern React applications.</p><p>But engineering isn’t always about writing more code or implementing everything ourselves.</p><p>Sometimes, the better engineering decision is knowing when to build something and when to leverage an existing, well-maintained solution.</p><p>I still appreciate the low-level control I gained from my original implementation. However, moving towards TanStack Query’s persistence architecture has helped me reduce complexity and focus on what matters most: building a scalable application.</p><p><strong>My takeaway: Learn the fundamentals by building from scratch, but don’t hesitate to use proven abstractions when they make your architecture simpler and more maintainable.</strong></p><p><em>Have you ever built something from scratch and later replaced it with an established library? I’d love to hear about your experience.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27ed521385bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Map: Store and Find Values Using Keys]]></title>
            <link>https://medium.com/@subi4020/javascript-map-store-and-find-values-using-keys-20985bb179a7?source=rss-d92a12fc552f------2</link>
            <guid isPermaLink="false">https://medium.com/p/20985bb179a7</guid>
            <category><![CDATA[react-js-tutorials]]></category>
            <category><![CDATA[js-map]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[SUBEESH PALAMADATHIL]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 10:39:05 GMT</pubDate>
            <atom:updated>2026-09-22T13:33:00.183Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xmTep_BXjk3b-9dnEVvJQ.jpeg" /><figcaption>Map</figcaption></figure><p>When we need to store data and later find it using a unique key, JavaScript’s Map collection is very useful.</p><p>A Map stores data in <strong>key-value pairs</strong>:</p><p>Key → Value</p><p>For example:</p><p>User Id — — — — — — — — User</p><p>“101” — — — — — — — — — → “John”</p><p>“102” — — — — — — — — — → “Lizy”</p><p>“103” — — — — — — — — — → “Sarah”</p><p>Instead of searching through every value, we can directly use the key to retrieve the value.</p><p><strong>Creating a Map</strong></p><p>We can create a Map using:</p><pre>const users = new Map();</pre><p>Then we can store values using <strong><em>.set()</em></strong><em> </em>method:</p><pre>users.set(“101”, “John”);<br>users.set(&quot;102&quot;, &quot;Lizy&quot;);<br>users.set(&quot;103&quot;, &quot;Sarah&quot;);</pre><p>Now our Map contains:</p><p>User Id — — — User</p><p>101 — — — —→ John</p><p>102 — — —-→ Lizy</p><p>103 — — — -→ Sarah</p><p><strong>Getting a value using its key</strong></p><p>We can use<em> </em><strong><em>.get()</em></strong> method:</p><pre>const user = users.get(“102”);<br>console.log(user);</pre><p><strong>Output:</strong></p><p><em>Lizy</em></p><p>The important idea is that we don’t need to manually search through all the users.</p><p>We simply provide the key:</p><pre>users.get(“102”);</pre><p>and the Map gives us the corresponding value.</p><p><strong>Why is this useful?</strong></p><p>Imagine we have <strong>10,00,000 (1M)</strong> users and we want to find the information for:</p><p>A user has <strong>Id 785432</strong></p><p>If we stored the users in a simple array, we might have to search through the array to find the matching user.</p><p>With a <strong>Map</strong>, we organize the data around a key:</p><pre>const users = new Map();</pre><pre>users.set(“785432”, { <br>  name: &quot;John&quot;,<br>  age: 30<br>});</pre><p>Now we can directly look up the user:</p><pre>const user = users.get(&quot;785432&quot;);<br>console.log(user.name);</pre><p><strong>Output:</strong></p><p><em>John</em></p><p>The key is used to locate the corresponding value efficiently.</p><p><strong>Checking whether a key exists or not</strong></p><p>We can use <strong><em>.has()</em></strong> method:</p><pre>if (users.has(&quot;785432&quot;)) {<br>    console.log(&quot;User exists&quot;);<br>}</pre><p>This is useful when we want to check whether a value has already been stored.</p><p><strong>Updating a value</strong></p><p>Calling <strong><em>.set()</em></strong><em> </em>with an existing key updates its value:</p><pre>users.set(&quot;101&quot;, &quot;Michael&quot;);</pre><p>Now:</p><p>101 → Michael</p><p>The old value “John” has been replaced.</p><p><strong>Removing a value</strong></p><p>We can remove a key-value pair using <strong><em>.delete()</em></strong> method:</p><pre>users.delete(“101”);</pre><p>Now user Id 101 is no longer in the Map.</p><p><strong>A simple real-world example</strong></p><p>Imagine we are processing comments for a social media application.</p><p>We might want to quickly find all comments belonging to a particular post.</p><p>We can use the post ID as the key and then set the comments:</p><pre>const commentsByPost = new Map();<br><br>commentsByPost.set(&quot;101&quot;, [<br>  &quot;Great post!&quot;,<br>  &quot;Very interesting!&quot;,<br>  &quot;Thanks for sharing!&quot;<br>]);<br><br>commentsByPost.set(&quot;102&quot;, [<br>  &quot;Nice article!&quot;,<br>  &quot;I learned something new.&quot;<br>]);</pre><p>Now if we want the comments for post with Id 101:</p><pre>const comments = commentsByPost.get(&quot;101&quot;);<br>console.log(comments);</pre><p>We can directly retrieve the comments associated with that post.</p><p>The Map gives us a simple structure:</p><p><strong>101 → [comment1, comment2, comment3]</strong></p><p><strong>102 → [comment1, comment2]</strong></p><p>This is one of the powerful ideas behind using a Map:</p><p><strong>Store a value using a key, and later use that same key to quickly look up the value.</strong></p><p><strong>Map in one picture</strong></p><p>Instead of thinking of a <strong>Map</strong> as just another JavaScript collection, think of it as a <strong>key-based lookup structure</strong>:</p><p>SET</p><p>Key ─────────────→ Value</p><p>GET</p><p>Key ─────────────→ Value</p><p>That simple relationship makes <strong>Map</strong> extremely useful when we repeatedly need to find data using a known key.</p><p><strong>Using Map with React State in TypeScript</strong></p><p>Now, let’s look at an example of using Map to update state in the frontend.</p><p>Map becomes especially useful in React when we have data that is naturally organized by a unique key.</p><p>For example, imagine a social-media application where we need to store comments for multiple posts.</p><pre>interface PostComment {<br>  commentId: string;<br>  postId: string; <br>  userId: string; <br>  userName: string;<br>  comment: string;<br>  likeCount: number;<br>  …..<br>};</pre><p>Instead of keeping all comments in one large array:</p><pre>const [comments, setComments] = useState&lt;PostComment[]&gt;([]);</pre><p>we can organize them by postId:</p><pre>const [comments, setComments] = useState&lt;Map&lt;string, PostComment[]&gt;&gt;(<br>    new Map()<br>);</pre><p>Now the structure looks conceptually like this:</p><p><strong>postId → comments[]</strong></p><p><strong>101 → [comment1, comment2, comment3]</strong></p><p><strong>102 → [comment4, comment5]</strong></p><p><strong>103 → [comment6, comment7]</strong></p><p>The postId becomes the key, and the array of comments becomes the value.</p><p><strong>Updating comments for a specific post</strong></p><p>Suppose we receive a new comment for post with <strong>Id 101</strong>.</p><p>We can update only the comments belonging to that post:</p><pre>const addComment = (postId: string, newComment: PostComment) =&gt; {<br>    setComments(prev =&gt; {<br>        const next = new Map(prev);<br><br>        const existingComments = next.get(postId) ?? [];<br><br>        next.set(postId, [<br>            newComment,<br>            ...existingComments<br>        ]);<br><br>        return next;<br>    });<br>};</pre><p>Let’s understand what happens here.</p><p>First:</p><pre>const next = new Map(prev);</pre><p>We create a new Map containing the existing state.</p><p>This is important in React because we should not directly mutate the existing state object.</p><p>Then:</p><pre>const existingComments = next.get(postId) ?? [];</pre><p>We use the postId as the key to retrieve that post’s comments.</p><p>For example:</p><pre>next.get(&quot;101&quot;);</pre><p>might return:</p><p><strong>[</strong></p><p><strong>comment1,</strong></p><p><strong>comment2</strong></p><p><strong>]</strong></p><p>If there are no comments for that post yet, ?? [] gives us an empty array.</p><p>Then:</p><pre>next.set(postId, [<br>    newComment,<br>    ...existingComments<br>]);</pre><p>replaces the value for that postId.</p><p>The result becomes:</p><p><strong>101 → [newComment, comment1, comment2]</strong></p><p>while comments belonging to other posts remain unchanged.</p><p><strong>Updating an existing comment</strong></p><p>Map is also useful when we need to update a particular comment.</p><p>For example, suppose a user likes a comment and we want to increase its <strong>likeCount</strong>.</p><pre>const updateCommentLike = (<br>    postId: string,<br>    commentId: string<br>) =&gt; {<br>    setComments(prev =&gt; {<br>        const next = new Map(prev);<br><br>        const postComments = next.get(postId);<br><br>        if (!postComments) {<br>            return prev;<br>        }<br><br>        const updatedComments = postComments.map((comment: PostComment) =&gt;<br>            comment.commentId === commentId<br>                ? {<br>                    ...comment,<br>                    likeCount: comment.likeCount + 1<br>                }<br>                : comment<br>        );<br><br>        next.set(postId, updatedComments);<br><br>        return next;<br>    });<br>};</pre><p>Here, <strong>Map</strong> quickly takes us to the comments belonging to the required post:</p><pre>next.get(postId);</pre><p>We don’t need to search through comments belonging to other posts.</p><p>Then we update the required comment inside that post’s comment array.</p><p><strong>Why this combination is useful</strong></p><p>This gives us two levels of organization:</p><p>Map</p><p>│</p><p>├── 101 → Comment[]</p><p>│ │</p><p>│ ├── comment1</p><p>│ ├── comment2</p><p>│ └── comment3</p><p>│</p><p>├── 102 → Comment[]</p><p>│ │</p><p>│ ├── comment4</p><p>│ └── comment5</p><p>│</p><p>└── 103 → Comment[]</p><p>│</p><p>└── comment6</p><p>The <strong>Map</strong> provides fast lookup by postId, while the array preserves the ordering of comments.</p><p>This is a good example of choosing a data structure based on the operations we perform most frequently.</p><p><strong>Map</strong> is not automatically the best data structure for every situation. But when our data naturally follows:</p><p><strong>key → value</strong></p><p>and we frequently need to retrieve or update the value using that key, <strong>Map</strong> can be an excellent choice.</p><p><strong>Map</strong> allows us to retrieve the comments associated with a specific post in O(1) average time.</p><p>In React, we can combine <strong>Map</strong> with immutable state updates to efficiently organize and update data such as <strong>comments, messages, notifications, users,</strong> or other entities grouped by an identifier.</p><p>As we have seen, the <strong>Map</strong> data structure can be used to efficiently manage <strong>comments, nested comments</strong>, and their <strong>reply</strong> structures in a <strong>frontend application</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20985bb179a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Text to Predictions: Understanding LLM Training]]></title>
            <link>https://medium.com/@subi4020/from-text-to-predictions-understanding-llm-training-c69551ae9a0d?source=rss-d92a12fc552f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c69551ae9a0d</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-chatbot]]></category>
            <category><![CDATA[model-training]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[SUBEESH PALAMADATHIL]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 11:38:20 GMT</pubDate>
            <atom:updated>2026-09-18T11:46:29.094Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPHzuf-QpjzCZUrRNls2EA.jpeg" /><figcaption>LLM Training</figcaption></figure><p>Large Language Models (LLMs) have become a major part of today’s AI landscape, but what actually happens behind the scenes when an LLM learns to generate text? Instead of treating an LLM as a black box, Uderstand its fundamental idea by building a very small example from scratch. In this blog, I’ll walk through the basic process step by step — from text and tokens to input-target pairs, predictions and training — to understand the core idea behind how an LLM learns to predict the next token.</p><h3>Prerequisites</h3><p>Basic knowledge of <strong>Python programming</strong> is recommended to follow along with the practical examples in this blog. No prior knowledge of machine learning or LLMs is required.</p><p>Let’s dive into practical examples without further explanation.</p><p>First import the necessary libraries</p><pre>import random<br>import re</pre><pre>These libraries are used to generate random values and <br>to perform any regular expression operations<br></pre><p>Now let’s use a simple sentence as training data for our LLM model</p><pre>raw_text = &#39;&#39;&#39;<br>    A Large Language Model (LLM) <br>    is an AI system that learns from <br>    large amounts of text to understand <br>    and generate human-like language.<br>&#39;&#39;&#39;</pre><p>Next, let’s split the sentence into smaller pieces called tokens.</p><pre>tokens = re.split(r&#39;([,.:;?_!&quot;()\&#39;]|\s)&#39;, raw_text)</pre><p>You may notice that the list (tokens) also contains spaces and newline characters. We’ll clean these up in the next step.</p><p>[‘’, ‘\n’, ‘’, ‘ ‘, ‘’, ‘ ‘, ‘’, ‘ ‘, ‘’, ‘ ‘, ‘A’, ‘ ‘, ‘Large’, …]</p><p>Now remove unwanted white spaces and newlines</p><pre>preprocessed_tokens = [word.strip() for word in tokens if word.strip()]</pre><p>The preprocessed list will look like this: [‘A’, ‘Large’, ‘Language’, ‘Model’, …]</p><p>Next Generate a vocabulary from preprocessed tokens</p><pre>vocabulary = { token: Id for Id, token in enumerate(preprocessed_tokens) }</pre><p>The vocabulary will look like this:</p><p>{‘A’: 0, ‘Large’: 1, ‘Language’: 2, ‘Model’: 3,… }</p><p>Now extract the token Ids</p><pre>tokenIds = [vocabulary[token] for token in preprocessed_tokens]</pre><p>Next, we will create <strong>inputs</strong> and <strong>targets</strong> from the token IDs. This is the basic idea behind <strong>self-supervised learning</strong>.</p><p>Here, each input token is paired with the token that comes immediately after it. For example:</p><pre><strong>Input </strong>     <strong> Target</strong><br>A           Large<br>Large       Language<br>Language    Model</pre><pre>inputs = tokenIds[:-1]<br>targets = tokenIds[1:]</pre><p>Now determine the vocabulary size to create an n × m matrix for storing scores during training.</p><pre>vocab_size = len(preprocessed_tokens)</pre><p>Generate a random n × m matrix of scores.</p><pre>weights = [<br>    [random.uniform(-0.1, 0.1) for _ in range(vocab_size)]<br>    for _ in range(vocab_size)<br>]</pre><p>The weights will look like this:</p><pre>                        A     Large   Language ...<br>       A:            [ 0.02   -0.07    0.04     .... ]<br>       Large:        [-0.03    0.05   -0.01     .... ]<br>       Language:     [ 0.06    0.01   -0.04     .... ]<br>       ....</pre><p>Now let’s give the model the input “Large” to predict the next word and find the corresponding token Id</p><pre>sample_text = &quot;Large&quot;<br>input_token_id = vocabulary[sample_text]</pre><p>Now, find the score for the input token &quot;Large&quot; from the previously generated score matrix.</p><pre>scores = weights[input_token_id]</pre><p>Now consider the token Id corresponding to highest score</p><pre>predicted_id = scores.index(max(scores))</pre><p>At last, print the result</p><pre>print(&quot;Predicted next word:&quot;, preprocessed_tokens[predicted_id])<br>print(&quot;Input word:&quot;, sample_text)</pre><p>This is a very simplified example of the basic idea behind how an LLM learns during training. In a real LLM, these calculations are performed repeatedly on a huge amount of training data. The model calculates the loss, finds the gradients, and adjusts its weights to improve its predictions. This process is repeated over and over until the model gradually becomes better at predicting the next token.</p><p>In our simple example, because the scores are randomly generated and no actual training is performed, you may see different predicted values each time you run the script. The real learning happens when we introduce the training loop, loss calculation, gradient calculation, and weight updates.</p><p>Run the below script multiple times, you will see the predicted word changing.</p><pre># library to generate random values<br>import random<br># Library for regular expressions<br>import re<br><br># A sample sentence (we give to train the LLM model)<br>raw_text = &#39;&#39;&#39;<br>    A Large Language Model (LLM) <br>    is an AI system that learns from <br>    large amounts of text to understand <br>    and generate human-like language.<br>&#39;&#39;&#39;<br><br># Split the sentence into piece by piece called tokens<br>tokens = re.split(r&#39;([,.:;?_!&quot;()\&#39;]|\s)&#39;, raw_text)<br><br># Remove unwanted white spaces, if you need more customization, then you can have<br>preprocessed_tokens = [word.strip() for word in tokens if word.strip()]<br># Generate a vocabulary from token called token: Id pairs<br># e.g.,<br># vocabulary = {<br>#     &quot;A&quot;: 0,<br>#     &quot;Large&quot;: 1,<br>#     &quot;Language&quot;: 2,<br>#     ....<br># }<br>vocabulary = { token: Id for Id, token in enumerate(preprocessed_tokens) }<br><br># Now store the token Ids, extract each Ids from the generated vocabulary<br>tokenIds = [vocabulary[token] for token in preprocessed_tokens]<br><br><br># Generate some sample inputs and targets for LLM training (self supervised learning)<br># e.g.,<br># inputs = [0, 1, 2]<br># targets = [1, 2, 3]<br><br>inputs = tokenIds[:-1]<br>targets = tokenIds[1:]<br><br># Determine the vocabulary size to create an n × m matrix for storing scores<br>vocab_size = len(preprocessed_tokens)<br><br># Generate random scores in an n x m matrix<br>weights = [<br>    [random.uniform(-0.1, 0.1) for _ in range(vocab_size)]<br>    for _ in range(vocab_size)<br>]<br><br># e,g.,                 A     Large   Language ...<br>#     A:            [ 0.02   -0.07    0.04     .... ]<br>#     Large:        [-0.03    0.05   -0.01     .... ]<br>#     Language:     [ 0.06    0.01   -0.04     .... ]<br>#       ....<br><br># Now Let&#39;s give the model an input &quot;Large&quot; to predict the next word<br>sample_text = &quot;Large&quot;<br># Extract the Id from vocabulary<br>input_token_id = vocabulary[sample_text]<br><br># Find the score for the input token &quot;Large&quot; from the previously generated score matrix<br>scores = weights[input_token_id]<br><br># print(&quot;Scores:&quot;, scores)<br># Find the token Id corresponding to highest score<br>predicted_id = scores.index(max(scores))<br><br># Print the result<br>print(&quot;Predicted next word:&quot;, preprocessed_tokens[predicted_id])<br>print(&quot;Input word:&quot;, sample_text)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c69551ae9a0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST API]]></title>
            <link>https://medium.com/@subi4020/rest-api-1cf847a8737e?source=rss-d92a12fc552f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cf847a8737e</guid>
            <category><![CDATA[api-design]]></category>
            <category><![CDATA[client-server-achitecture]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[frontend-backend-design]]></category>
            <category><![CDATA[web-framework]]></category>
            <dc:creator><![CDATA[SUBEESH PALAMADATHIL]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 06:47:34 GMT</pubDate>
            <atom:updated>2026-08-05T06:47:34.968Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hSAaRcLcfsGxEHvJGz29PA.png" /></figure><p>Have you ever come across a job description like this during your career search?</p><p><strong>Responsibilities</strong></p><ul><li>Design, develop, and maintain high-performance back-end services and systems for web and mobile applications.</li><li>Build and integrate <strong>RESTful APIs</strong> and microservices to support frontend and mobile application functionality.</li><li>……………</li></ul><p>If you have seen requirements like these and felt unsure about what they actually mean, then this article is for you.</p><p><strong>REST (Representational State Transfer)</strong> is a set of <strong>architectural rules and guidelines</strong> for designing backend web services. It is not a rigid design pattern or a specific piece of software. Instead, think of REST as a <strong>universal design philosophy</strong> that teaches your backend and frontend how to talk to each other cleanly over the web using standard internet protocols (HTTP).</p><p>Let’s consider an example here.</p><p>When you click/tap on the like button on any post in any social media platform, a frontend request to add your like to a backend service send over internet, and this ‘like’ information is then saves in a persistent store, such as database.</p><p>But what exactly is happening behind the scenes here? How do the frontend and backend talk to each other so seamlessly? The answer lies in a universal design concept called a <strong>REST API</strong>.”</p><p>Frontend (social media website/app)</p><p>POST <a href="http://yoursite.com/api/v1/posts/:postId/likes">http://yoursite.com/api/v1/posts/:postId/likes</a></p><p>Here the frontend sends a POST request to backend with post id, the user id will be extracted from the authentication token at backend.</p><p><strong>The fundamental rules you should follow are:</strong></p><p><strong>1. Use Nouns for Resources (Not Verbs)</strong></p><p>URLs should represent <strong>things</strong> (resources), not actions. Actions belong to the HTTP methods.</p><ul><li><strong>Bad (Verbs):</strong> /getUsers, /createNewConversation, /deleteChat / addLike / saveLike</li><li><strong>Good (Nouns):</strong> /users, /conversations, /chats, /posts</li></ul><p>Frontend Usage Example (Axios):</p><p>const res = await axiosinstance.post(`/api/v1/posts/${postId}/likes`);</p><p><strong>2. Use Plural Nouns Consistently</strong></p><p>Keep your resource names plural across the entire API to avoid confusion about whether you are dealing with a collection or a single item.</p><ul><li><strong>Bad:</strong> /conversation, /user</li><li><strong>Good:</strong> /conversations, /users</li></ul><p><strong>3. Use HTTP Methods for Actions</strong></p><p>Let the standard HTTP methods do the heavy lifting for actions (often called CRUD operations).</p><ul><li><strong>GET</strong>: Fetch/read a resource (e.g., GET /chats, /posts).</li><li><strong>POST</strong>: Create a new resource (e.g., POST /chats).</li><li><strong>PUT</strong>: Update an existing resource completely.</li><li><strong>PATCH</strong>: Update an existing resource partially.</li><li><strong>DELETE</strong>: Remove a resource.</li></ul><p><strong>4. Represent Hierarchies with the URL Path</strong></p><p>Use forward slashes (/) to show relationships between a parent resource and a child resource. Move from the most general category to the most specific.</p><ul><li><strong>Pattern:</strong> /parents/parentId/children</li><li><strong>Example:</strong> /conversations/5/chats (This explicitly reads as: <em>“Get the chats belonging to conversation number 5”</em>).</li></ul><p><strong>5. Use Query Parameters for Filtering and Sorting</strong></p><p>Do not change the base URL path to filter, sort, or limit data. Use the query string (anything after the ?).</p><ul><li><strong>Bad:</strong> /conversations/active/limit60</li><li><strong>Good:</strong> /conversations?status=active&amp;limit=60</li></ul><p><strong>6. Use Standard HTTP Status Codes</strong></p><p>Always tell the frontend exactly what happened using standard, universal three-digit response codes.</p><ul><li><strong>200 OK</strong>: The request was successful.</li><li><strong>201 Created</strong>: A new resource was successfully created (perfect for POST).</li><li><strong>400 Bad Request</strong>: The client sent invalid data (e.g., missing a required field).</li><li><strong>404 Not Found</strong>: The requested URL or resource does not exist.</li><li><strong>500 Internal Server Error</strong>: The backend crashed or has a bug.</li></ul><p><strong>7. Always Communicate in JSON</strong></p><p>Both the data sent by the frontend (POST/PUT payloads) and the data returned by your backend should always be formatted as JSON. Ensure your server sends the Content-Type: application/json header.</p><p>e.g.,</p><p>{</p><p>“postId”: “post_123”,</p><p>“userId”: “user_456”,</p><p>“createdAt”: “2026–08–05T11:23:00Z”,</p><p>}</p><p><strong>8. Keep URL Casing Consistent</strong></p><p>Pick a casing style for your URLs and stick to it everywhere. <strong>Kebab-case</strong> is the web standard for URLs.</p><ul><li><strong>Inconsistent:</strong> /userProfiles (camelCase) and /chat-messages (kebab-case)</li><li><strong>Good:</strong> /user-profiles and /chat-messages</li></ul><p><strong>9. Include Versioning in the URL</strong></p><p>Always prefix your API routes with a version number (like /v1/). This allows you to upgrade your backend code and introduce major changes in the future without breaking the existing frontend application.</p><ul><li><strong>Bad:</strong> /api/users (Hard to change later without breaking the app)</li><li><strong>Good:</strong> /api/v1/users</li></ul><p>Remember, these REST API rules apply universally, regardless of which frameworks or programming languages you choose for your frontend and backend.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cf847a8737e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Podman Docker-compatible setup for a Full-stack app]]></title>
            <link>https://medium.com/@subi4020/podman-docker-compatible-setup-for-a-full-stack-app-36fc5043364c?source=rss-d92a12fc552f------2</link>
            <guid isPermaLink="false">https://medium.com/p/36fc5043364c</guid>
            <dc:creator><![CDATA[SUBEESH PALAMADATHIL]]></dc:creator>
            <pubDate>Mon, 15 Sep 2025 04:57:42 GMT</pubDate>
            <atom:updated>2026-09-18T12:03:15.381Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d-smGx-9YvNe82mqAn1HLQ.jpeg" /><figcaption>Docker-compatible setup</figcaption></figure><p>Follow the below project structure to run podman using Docker-compatible setup so that you can switch between Docker and Podman easily, Sometimes Docker will not be suitable option if you have minimal resources like old CPU, Low memory etc. Also I will show you how to use Kafka as a real-time event streaming without Zookeeper (see …. |_ docker-compose.yml).</p><p>Project-root <br> …. |_ Backend-root(Nodejs)<br> …. | ………… |_ src <br> …. | ………… |_ node_modules<br> …. | ………… |_ package.json<br> …. | ………… |_ Dockerfile<br> …. | ………… |_ README.md<br> …. | ………… |_ .env.development<br> …. | ………… |_ .env.production<br> …. | ………… |_ …….<br> …. |_ Frontend(Reactjs)<br> …. | ………… |_src<br> …. | ………… |_ nginx<br> …. | ………… |_ node_modules<br> …. | ………… |_ package.json<br> …. | ………… |_ index.html<br> …. | ………… |_ Dockerfile<br> …. | ………… |_ README.md<br> …. | ………… |_ .env.development<br> …. | ………… |_ .env.production<br> …. | ………… |_ …….<br> …. |_ docker-compose.override.yml<br> …. |_ docker-compose.yml<br> …. |_ .env</p><p>install podman-compose using</p><p><strong>npm install podman-compose</strong></p><p>Write or copy paste the below code to the specified files</p><p><strong>1. …. | ………… |_ Dockerfile (Backend)</strong></p><p>FROM node:18-alpine AS development<br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm install<br>COPY . .<br>EXPOSE 3000<br>CMD [“npm”, “run”, “dev”]</p><p>FROM node:18-alpine AS production<br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm ci — only=production<br>COPY . .<br>EXPOSE 3000<br>CMD [“npm”, “start”]</p><p><strong>2. …. | ………… |_ Dockerfile (Frontend)</strong></p><p># Stage 1: Build with Vite<br>FROM node:18-alpine AS builder<br>WORKDIR /app</p><p>COPY package*.json ./<br>RUN npm install<br>COPY . ./</p><p># Pass environment variables during build<br>ARG BACKEND_API_URL # set the url in .env file in Frontend folder<br>ARG BACKEND_APP_WS_URL # set the url in .env file in Frontend folder</p><p># Install bash and fix permissions<br>RUN apk add — no-cache bash<br>RUN chmod +x node_modules/.bin/*<br># Build output goes to “dist” (default Vite output)<br>RUN npm run build</p><p># Stage 2: Serve with Nginx<br>FROM nginx:alpine AS production<br>WORKDIR /usr/share/nginx/html</p><p># Copy Vite build output<br>COPY — from=builder /app/dist .</p><p># Copy nginx config and SSL certs (from build context root!)<br>COPY nginx/nginx.conf /etc/nginx/conf.d/default.conf<br>COPY nginx/ssl/ /etc/nginx/ssl/</p><p>EXPOSE 80 443</p><p><strong>3. …. |_ docker-compose.override.yml</strong></p><p>version: ‘3.8’</p><p>services:<br> backend:<br> volumes:<br> — ./Backend:/app<br> — /app/node_modules<br> — ./nginx/ssl:/app/ssl:ro<br> environment:<br> — NODE_ENV=development<br> env_file:<br> — ./Backend/.env.development<br> command: &gt;<br> sh -c “npm run dev”</p><p>frontend:<br> volumes:<br> — ./Frontend:/app<br> — /app/node_modules<br> environment:<br> — NODE_ENV=development<br> env_file:<br> — ./Frontend/.env.development<br> command: &gt;<br> sh -c “npm run dev”</p><p><strong>4. …. |_ docker-compose.yml (Kafka only setup (KRaft mode) without Zookeeper)</strong></p><p>version: ‘3.8’</p><p>services:<br> kafka:<br> image: bitnami/kafka:latest<br> container_name: kafka<br> ports:<br> — “9092:9092”<br> environment:<br> # KRaft mode (no Zookeeper)<br> — KAFKA_CFG_PROCESS_ROLES=broker,controller<br> — KAFKA_CFG_NODE_ID=1<br> — KAFKA_CFG_CONTROLLER_QUORUM_VOTERS=1@kafka:9093<br> — KAFKA_CFG_LISTENERS=PLAINTEXT://:9092,CONTROLLER://:9093<br> — KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://kafka:9092<br> — KAFKA_CFG_CONTROLLER_LISTENER_NAMES=CONTROLLER<br> — KAFKA_CFG_INTER_BROKER_LISTENER_NAME=PLAINTEXT<br> — ALLOW_PLAINTEXT_LISTENER=yes<br> volumes:<br> — kafka_data:/bitnami/kafka<br> networks:<br> — app-network</p><p>volumes:<br> kafka_data:</p><p>networks:<br> app-network:<br> driver: bridge</p><p><strong>5. …. | ………… |_ .env.development (Backend)</strong></p><p>KAFKA_BROKERS=kafka:9092</p><p>MONGO_URI=your_mongobd_live_uri here</p><p><strong>6. …. | ………… |_ .env.development</strong></p><p>VITE_API_BACKEND_URL=<a href="https://192.168.43.240:3000/api/v1">y</a>our_backend_api_base_url (<a href="https://192.168.43.240:3000/api/v1">https://localhost:3000/api/v1</a>)<br>VITE_APP_WS_URL=wss:// your_backend_API_url (<a href="https://192.168.43.240:3000/api/v1">https://localhost:3000</a>)</p><p><strong>7. …. |_ .env</strong></p><p># This file is automatically loaded by docker-compose<br>MONGODB_URI=your_mongodb_live_uri here<br>NODE_ENV=development<br>BACKEND_API_URL=<a href="https://192.168.43.240:3000/api">https://localhost:3000/api</a><br>BACKEND_APP_WS_URL=wss://localhost:3000</p><p>Save all the settings</p><p>Now ready to go …</p><p>Run the below command from your Project root terminal</p><p>podman-compose up — build</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36fc5043364c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>