<?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 the kishore on Medium]]></title>
        <description><![CDATA[Stories by the kishore on Medium]]></description>
        <link>https://medium.com/@mrkishoremani?source=rss-844edccb9f62------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*DRapuKr4rD_t2zDW</url>
            <title>Stories by the kishore on Medium</title>
            <link>https://medium.com/@mrkishoremani?source=rss-844edccb9f62------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:43:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mrkishoremani/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[WebSockets vs SSE vs Polling: Which One Should You Actually Use?]]></title>
            <link>https://medium.com/@mrkishoremani/websockets-vs-sse-vs-polling-which-one-should-you-actually-use-d76cabe9fb06?source=rss-844edccb9f62------2</link>
            <guid isPermaLink="false">https://medium.com/p/d76cabe9fb06</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[the kishore]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 17:31:48 GMT</pubDate>
            <atom:updated>2026-06-09T17:31:48.011Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Spent 3 Days Debugging a “Real-Time” Feature That Wasn’t Real-Time at All</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*j107pAtVWUVUq1KAWIOp_g.png" /></figure><p>Let me tell you what happened.</p><p>We had a document processing system. Users would upload a file, our backend would chew on it, and the frontend needed to show the status — processing, done, failed. Simple enough, right?</p><p>Our first version? A setInterval that pinged the server every 2 seconds.</p><p>It worked. Users saw status updates. Nobody complained. I even felt a little proud of it.</p><p>Then we hit 500 concurrent users during a demo. The backend started sweating. Our server logs looked like the server was being DDoS’d — by our own frontend. 500 users × 30 requests/minute = 15,000 requests/minute, all asking the same thing: <em>“Is it done yet? Is it done yet? Is it done yet?”</em></p><p>That’s when I actually sat down and learned the difference between Polling, SSE, and WebSockets. Not from a tutorial — from pain.</p><p>So here’s what I wish someone had told me before I wrote that setInterval.</p><h3>First, let’s agree on what “real-time” even means</h3><p>When we say real-time, we mean: <em>the server has new information, and the client knows about it immediately — without the client having to ask.</em></p><p>That’s it. Everything else is just different ways of achieving that.</p><p>There are three ways to do it. Each one makes sense in different situations. None of them is universally “the best.”</p><h3>Polling — The one everyone starts with</h3><p>You make an HTTP request. You get a response. You wait. You make another HTTP request.</p><pre>useEffect(() =&gt; {<br>  const interval = setInterval(async () =&gt; {<br>    const res = await fetch(`/api/documents/${docId}/status`);<br>    const { status } = await res.json();<br>    setStatus(status);<br>    if (status === &#39;done&#39; || status === &#39;failed&#39;) {<br>      clearInterval(interval);<br>    }<br>  }, 2000);</pre><pre>  return () =&gt; clearInterval(interval);<br>}, [docId]);</pre><p>I’m not going to pretend this is terrible. For a lot of cases, this is completely fine. If you’re checking for something that updates every few minutes — say, a weekly report — polling every 30 seconds is totally reasonable.</p><p>But here’s the thing nobody says out loud: most of those requests return nothing useful. The document is still processing. The status hasn’t changed. You just made a round trip to the server, burned a tiny bit of battery on the user’s phone, added another entry to your server logs, and learned… nothing new.</p><p>At small scale you don’t feel it. At scale, it’s embarrassing.</p><p>The other thing is latency. If you poll every 2 seconds, your “real-time” update is actually up to 2 seconds late. Not the end of the world, but it’s not real-time either.</p><p>Use polling when:</p><ul><li>Updates are infrequent (every minute or more)</li><li>You don’t control the server and can’t add a stream endpoint</li><li>The feature is simple and low-traffic and you need to ship fast</li></ul><h3>Server-Sent Events — The one nobody talks about enough</h3><p>SSE is genuinely underused and I don’t know why.</p><p>The idea is simple: the client opens one HTTP connection, and instead of the server closing it after responding, it <em>keeps it open</em> and pushes data down whenever something new happens. One connection. Many updates.</p><pre>// Server — Node.js<br>app.get(&#39;/api/documents/:id/stream&#39;, (req, res) =&gt; {<br>  res.setHeader(&#39;Content-Type&#39;, &#39;text/event-stream&#39;);<br>  res.setHeader(&#39;Cache-Control&#39;, &#39;no-cache&#39;);<br>  res.setHeader(&#39;Connection&#39;, &#39;keep-alive&#39;);</pre><pre>  // Push an update whenever the doc status changes<br>  const onStatusChange = (status) =&gt; {<br>    res.write(`data: ${JSON.stringify({ status })}\n\n`);<br>  };</pre><pre>  documentEmitter.on(`doc:${req.params.id}`, onStatusChange);</pre><pre>  req.on(&#39;close&#39;, () =&gt; {<br>    documentEmitter.off(`doc:${req.params.id}`, onStatusChange);<br>  });<br>});</pre><pre>// Client — React<br>useEffect(() =&gt; {<br>  const es = new EventSource(`/api/documents/${docId}/stream`);</pre><pre>  es.onmessage = (e) =&gt; {<br>    const { status } = JSON.parse(e.data);<br>    setStatus(status);<br>    if (status === &#39;done&#39; || status === &#39;failed&#39;) es.close();<br>  };</pre><pre>  return () =&gt; es.close();<br>}, [docId]);</pre><p>What I love about this: the browser handles reconnection automatically. If the connection drops, EventSource retries on its own. You don&#39;t have to write that logic yourself.</p><p>What I also love: it’s just HTTP. No protocol switching, no special infrastructure. Your existing load balancer, your existing NGINX config — it all just works.</p><p>The limitation is obvious once you see it: it’s one direction only. Server talks. Client listens. The client can’t send data <em>back</em> through the same connection.</p><p>For a lot of real-world use cases — notifications, progress updates, live dashboards, document status — that’s completely fine. You don’t need the client to talk back. You just need the server to tell you when something changes.</p><p>Honestly, if I were starting that document status feature today, I’d reach for SSE first and only move to WebSockets if I actually needed bidirectional communication.</p><p>Use SSE when:</p><ul><li>The server needs to push updates to the client</li><li>The client doesn’t need to send back data in real-time</li><li>You want simplicity and don’t want to manage a WebSocket connection</li></ul><h3>WebSockets — When you actually need a two-way conversation</h3><p>WebSockets are different because both sides can talk, at any time, without waiting for the other side to ask.</p><p>The connection starts as a regular HTTP request, then “upgrades” to a persistent WebSocket connection. After that handshake, it’s just an open pipe. Client sends. Server sends. Nobody’s waiting for anyone.</p><pre>// Server — Node.js with ws<br>const WebSocket = require(&#39;ws&#39;);<br>const wss = new WebSocket.Server({ port: 8080 });</pre><pre>wss.on(&#39;connection&#39;, (ws, req) =&gt; {<br>  const token = new URL(req.url, &#39;http://localhost&#39;).searchParams.get(&#39;access_token&#39;);</pre><pre>  if (!isValidToken(token)) {<br>    ws.close(4401, &#39;Unauthorized&#39;);<br>    return;<br>  }</pre><pre>  ws.on(&#39;message&#39;, (raw) =&gt; {<br>    const msg = JSON.parse(raw);</pre><pre>    // Client sent something — handle it<br>    if (msg.type === &#39;subscribe_doc&#39;) {<br>      subscribeToDoc(msg.doc_id, (update) =&gt; {<br>        ws.send(JSON.stringify(update));<br>      });<br>    }<br>  });</pre><pre>  ws.on(&#39;close&#39;, (code) =&gt; {<br>    if (code === 4401) return; // auth failure, don&#39;t retry<br>    // cleanup subscriptions<br>  });<br>});</pre><pre>// Client — React custom hook<br>function useDocumentSocket(docId) {<br>  const [status, setStatus] = useState(null);<br>  const wsRef = useRef(null);</pre><pre>  useEffect(() =&gt; {<br>    const token = getToken();</pre><pre>    const connect = () =&gt; {<br>      const ws = new WebSocket(`wss://api.example.com/v1/documents/ws?access_token=${token}`);</pre><pre>      ws.onopen = () =&gt; {<br>        // Tell the server which doc we care about<br>        ws.send(JSON.stringify({ type: &#39;subscribe_doc&#39;, doc_id: docId }));<br>      };</pre><pre>      ws.onmessage = (e) =&gt; {<br>        const data = JSON.parse(e.data);<br>        if (data.type === &#39;doc_status&#39;) {<br>          setStatus(data.status);<br>        }<br>      };</pre><pre>      ws.onclose = (e) =&gt; {<br>        if (e.code === 4401) return; // auth failed, don&#39;t reconnect<br>        setTimeout(connect, 3000); // retry everything else<br>      };</pre><pre>      wsRef.current = ws;<br>    };</pre><pre>    connect();<br>    return () =&gt; wsRef.current?.close();<br>  }, [docId]);</pre><pre>  return status;<br>}</pre><p>Here’s the thing about WebSockets — they’re powerful but they come with real complexity. You have to write your own reconnect logic. You have to think about what happens when a user has the app open in 5 tabs (5 connections). You have to handle auth carefully — notice how that 4401 close code means &quot;don&#39;t reconnect, the token is bad&quot; but a normal close means &quot;try again in 3 seconds.&quot; That kind of nuance adds up.</p><p>And when you start scaling — multiple server instances — you quickly realize that WebSocket connections are stateful. Server A doesn’t know about the connections on Server B. So you need something like Redis pub/sub to broadcast events across all your servers. Suddenly your “simple real-time feature” has a Redis dependency.</p><p>None of this is scary. But it’s work. It’s worth it when you genuinely need two-way communication. It’s overkill if you just need the server to push updates.</p><p>Use WebSockets when:</p><ul><li>The client also needs to send events in real-time (typing indicators, commands, game moves)</li><li>Latency matters at the millisecond level</li><li>You’re building chat, live collaboration, multiplayer, or trading UIs</li></ul><h3>So which one should you use?</h3><p>Here’s the honest version:</p><p>If you’re just showing users a status update, a notification, a live feed of events — <strong>SSE</strong>. It’s simpler, it auto-reconnects, it works over HTTP. Most people reach for WebSockets out of habit when SSE would have been fine.</p><p>If your users need to <em>do</em> things in real-time — type, send, play, collaborate — <strong>WebSocket</strong>. Don’t fight the tool.</p><p>If updates happen every few minutes and you want to ship something today — <strong>Polling</strong>. Seriously. Don’t over-engineer it.</p><p>The wrong instinct is to always reach for WebSockets because it sounds more impressive. I’ve seen teams add WebSocket infrastructure to apps that update once a minute. Don’t be that team.</p><h3>What I changed in our system</h3><p>We replaced that setInterval nightmare with WebSockets — specifically because in our case the client also sends subscription commands to tell the server which documents to watch. If we only needed server → client, we&#39;d have used SSE.</p><p>The polling code was about 10 lines. The WebSocket implementation with proper auth, reconnect logic, and close code handling was closer to 80. But our server logs stopped looking like a DDoS attack, and the updates now land in under 100ms instead of up to 2 seconds.</p><p>Worth it? For our scale, yes. For a side project with 50 users? Probably not.</p><p>Know your scale. Pick the right tool. Don’t let “real-time” become a buzzword that means “setInterval with anxiety.”</p><p><em>If you’ve been burned by the same polling nightmare or have a war story about scaling WebSockets, drop it in the comments — genuinely curious what broke for other people.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d76cabe9fb06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nobody Told Me AI Would Make Me Feel Like a Junior Developer Again]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@mrkishoremani/nobody-told-me-ai-would-make-me-feel-like-a-junior-developer-again-d291b65f414f?source=rss-844edccb9f62------2"><img src="https://cdn-images-1.medium.com/max/1101/1*AAkZOnZKAmiujH5Bj0VajA.png" width="1101"></a></p><p class="medium-feed-snippet">Three months ago I was debugging a React re-render issue. Normally I&#x2019;d open Stack Overflow, scan five answers, copy the one that looked&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@mrkishoremani/nobody-told-me-ai-would-make-me-feel-like-a-junior-developer-again-d291b65f414f?source=rss-844edccb9f62------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@mrkishoremani/nobody-told-me-ai-would-make-me-feel-like-a-junior-developer-again-d291b65f414f?source=rss-844edccb9f62------2</link>
            <guid isPermaLink="false">https://medium.com/p/d291b65f414f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[the kishore]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 17:19:10 GMT</pubDate>
            <atom:updated>2026-06-09T17:19:10.628Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[ Scaling PostgreSQL Explained Simply — Beginner to Pro Guide]]></title>
            <link>https://medium.com/@mrkishoremani/scaling-postgresql-explained-simply-beginner-to-pro-guide-c52711c38bf7?source=rss-844edccb9f62------2</link>
            <guid isPermaLink="false">https://medium.com/p/c52711c38bf7</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[the kishore]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 08:52:40 GMT</pubDate>
            <atom:updated>2026-01-25T08:52:40.028Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 Scaling PostgreSQL Explained Simply — Beginner to Pro Guide</h3><p><strong>How OpenAI Scales PostgreSQL for Millions of Users — Explained in Simple Language with Examples, Diagrams, and Clear Flow</strong></p><blockquote><em>If you are a fresher, backend developer, DevOps engineer, or someone learning system design — this article is written for you.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*UO9aU02mBb0VyRJLqn5cGQ.png" /></figure><h3>📘 Introduction: Why This Article Matters</h3><p>Today, applications like <strong>ChatGPT</strong> handle <strong>millions of users every day</strong>.</p><p>Behind the scenes, one of the biggest challenges is <strong>database scaling</strong>.</p><p>Many developers believe:</p><blockquote><em>“PostgreSQL is good only for small applications.”</em></blockquote><p>But OpenAI proved that <strong>PostgreSQL can scale massively</strong> when designed correctly.</p><p>In this article, you will clearly understand:</p><ul><li>How PostgreSQL scaling works</li><li>How OpenAI handles massive traffic</li><li>Real-world architecture patterns</li><li>Simple explanations with diagrams</li></ul><p>No complex theory. No heavy terms.</p><p>Just clear understanding.</p><h3>🧠 What is PostgreSQL?</h3><p>PostgreSQL is an <strong>open-source relational database</strong> used to store structured data.</p><p>Examples of data stored:</p><ul><li>user details</li><li>messages</li><li>settings</li><li>transactions</li></ul><h3>📈 What Does Database Scaling Mean?</h3><p>Database scaling means:</p><blockquote><em>Making the database work smoothly even when users increase rapidly.</em></blockquote><p>Example:</p><ul><li>1,000 users → works fine</li><li>1,000,000 users → still works fine</li></ul><p>That ability is called <strong>scalability</strong>.</p><h3>⚠️ Core Problem in PostgreSQL</h3><p>PostgreSQL has an important rule:</p><h3>❗ Only ONE primary database handles writes</h3><ul><li>Writes = INSERT, UPDATE, DELETE</li><li>Reads = SELECT</li></ul><p>This means:</p><ul><li>unlimited reads (with replicas)</li><li>limited writes (single primary)</li></ul><p>This becomes the biggest scaling challenge.</p><h3>🔥 Problems OpenAI Faced</h3><p>When ChatGPT traffic increased:</p><ul><li>millions of read requests</li><li>thousands of write requests</li><li>high database CPU</li><li>connection overload</li></ul><p>If everything hits one database:</p><p>❌ slow responses<br>❌ outages<br>❌ poor user experience</p><h3>🧩 Architecture Before Optimization</h3><pre>Users<br>  ↓<br>Application<br>  ↓<br>PostgreSQL (single server)</pre><p>This design does not scale.</p><h3>✅ Solution 1: Read Replicas (Most Important)</h3><h3>What is a Read Replica?</h3><p>A read replica is a <strong>copy of the main PostgreSQL database</strong>.</p><ul><li>Primary DB → handles WRITE</li><li>Replica DB → handles READ</li></ul><h3>Architecture Flow</h3><pre>Users<br>                      ↓<br>                Application Layer<br>               ↙                   ↘<br>        Read Requests           Write Requests<br>             ↓                       ↓<br>       Read Replicas          Primary Database</pre><h3>Why this works</h3><ul><li>90% of traffic = READ</li><li>replicas handle heavy load</li><li>primary stays healthy</li></ul><p>This is the backbone of scaling PostgreSQL.</p><h3>✅ Solution 2: Reduce Unnecessary Writes</h3><p>Excessive writes kill database performance.</p><p>Example bad design:</p><pre>update user_status<br>update user_status<br>update user_status</pre><p>Same data written again and again.</p><h3>Optimization</h3><ul><li>write only if value changes</li><li>batch updates</li><li>delay non-critical writes</li></ul><p>Result:</p><p>✅ reduced DB load<br>✅ improved stability</p><h3>✅ Solution 3: Optimize Slow SQL Queries</h3><p>Slow queries are silent killers.</p><p>Common issues:</p><ul><li>too many joins</li><li>full table scans</li><li>large result sets</li></ul><h3>Better approach</h3><p>Instead of:</p><pre>One huge complex SQL query</pre><p>Use:</p><pre>Small query 1<br>Small query 2<br>Small query 3<br>Combine results in application</pre><p>This reduces CPU usage dramatically.</p><h3>✅ Solution 4: Database Connection Pooling</h3><p>Databases cannot handle thousands of open connections.</p><p>Problem:</p><ul><li>1000 users</li><li>1000 DB connections</li></ul><p>Very dangerous.</p><h3>Solution: PgBouncer</h3><p>Connection pooling allows:</p><pre>1000 users<br>   ↓<br>50 shared DB connections</pre><p>Like using limited counters in a bank.</p><h3>✅ Solution 5: Smart Caching Strategy</h3><p>Repeated data should never hit database.</p><p>Examples:</p><ul><li>user profile</li><li>preferences</li><li>settings</li></ul><p>Cache layer stores data in memory.</p><h3>Cache flow</h3><pre>Request → Cache<br>  ↓ hit → return<br>  ↓ miss → DB → store in cache</pre><p>Only one request hits DB during cache miss.</p><p>This protects the database.</p><h3>🔄 Final Scalable Architecture</h3><pre>Users<br>  ↓<br>Load Balancer<br>  ↓<br>Application Servers<br>  ├── Cache Layer<br>  ├── Read Replicas<br>  ├── Write → Primary DB<br>  └── Connection Pool</pre><p>This architecture supports massive scale.</p><h3>❓ Why OpenAI Avoided Database Sharding</h3><p>Sharding means splitting database into parts.</p><p>Problems with sharding:</p><ul><li>complex queries</li><li>data consistency issues</li><li>difficult maintenance</li></ul><p>OpenAI followed this rule:</p><blockquote><em>Optimize first. Shard only when absolutely required.</em></blockquote><h3>🧠 Key Takeaways (Very Important)</h3><ul><li>PostgreSQL can scale extremely well</li><li>Read replicas are essential</li><li>Writes must be controlled</li><li>Query optimization matters</li><li>Caching saves databases</li><li>Simple architecture beats complex design</li></ul><h3>🏁 Final Thoughts</h3><p>OpenAI did not rely on magic tools.</p><p>They focused on:</p><ul><li>strong fundamentals</li><li>clean database design</li><li>practical optimizations</li></ul><p>This proves one powerful lesson:</p><blockquote><strong><em>Good system design matters more than fancy technology.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*uoSwQpQ6TZddyPRrrx9Tqg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c52711c38bf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redis: The In-Memory Powerhouse — A Deep Dive into its Data Structures ]]></title>
            <link>https://medium.com/@mrkishoremani/redis-the-in-memory-powerhouse-a-deep-dive-into-its-data-structures-a6c81add9e90?source=rss-844edccb9f62------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6c81add9e90</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[the kishore]]></dc:creator>
            <pubDate>Fri, 14 Nov 2025 11:30:43 GMT</pubDate>
            <atom:updated>2025-11-14T11:30:43.268Z</atom:updated>
            <content:encoded><![CDATA[<h3>Redis: The In-Memory Powerhouse — A Deep Dive into its Data Structures 🧠</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*may6CQbVD4p1VJUPcHqEwg.png" /><figcaption>Redis</figcaption></figure><p>Redis (Remote Dictionary Server) is more than just a cache; it’s an incredibly versatile in-memory data structure store. Understanding its five core data types — and the mechanics behind them — is key to building high-performance, scalable applications.</p><h3>1. Strings: The Foundation of Redis 🧱</h3><h3>What is it?</h3><p>A Redis <strong>String</strong> is the simplest type, storing a key that maps to a single value. The value can be a string, an integer, or even binary data (up to 512MB).</p><h3>Why and Where to Use It?</h3><ul><li><strong>Basic Caching:</strong> Storing HTML fragments, JSON blobs, or serialized objects.</li><li><strong>Counters:</strong> Using commands like INCR and DECR for tracking page views, votes, or rate limits.</li><li><strong>Session Management:</strong> Storing login session tokens and expiry times.</li></ul><h3>Behind the Scenes: Storage</h3><p>Redis uses a structure called <strong>Simple Dynamic String (SDS)</strong> instead of standard C strings. SDS is a binary-safe structure that stores the string’s length, making length checks $O(1)$ (constant time), which is crucial for performance. For small integer values (like counters), Redis employs <strong>integer encoding</strong>, storing the number directly in the key structure for maximum memory efficiency.</p><h3>Code Example (Python/Client):</h3><pre># SET: Basic caching<br>r.set(&quot;user:100:profile&quot;, &quot;{\&quot;name\&quot;: \&quot;Alice\&quot;, \&quot;email\&quot;: \&quot;...\&quot;}&quot;)</pre><pre># INCR: Counter<br>r.set(&quot;pageviews:homepage&quot;, 0)<br>r.incr(&quot;pageviews:homepage&quot;) # The value becomes 1</pre><h3>2. Lists: Ordering and Messaging Power 📜</h3><h3>What is it?</h3><p>A <strong>List</strong> is an <strong>ordered collection</strong> of strings. Elements are inserted at the head (left) or tail (right).</p><h3>Why and Where to Use It?</h3><ul><li><strong>Queues and Stacks:</strong> Lists are perfect for implementing a <strong>FIFO Queue</strong> (LPUSH/RPOP) or a <strong>LIFO Stack</strong> (LPUSH/LPOP). This is foundational for task queues or message brokers.</li><li><strong>Timeline/Feed:</strong> Storing a list of the 100 most recent events or posts.</li><li><strong>Inter-Process Communication:</strong> Using <strong>Blocking List Operations</strong> (BLPOP, BRPOP) to allow workers to wait for items to appear in a queue without constant polling.</li></ul><h3>Behind the Scenes: Storage</h3><p>In older versions, Lists were based on <strong>Doubly Linked Lists</strong> for fast $O(1)$ head/tail operations. Modern Redis uses a highly optimized structure called <strong>Quicklist</strong>, which is a list of small, compressed <strong>ziplists</strong>. This balances the fast $O(1)$ insertion/deletion of a linked list with the better memory locality and efficiency of a compact array structure.</p><h3>Code Example (Python/Client):</h3><pre># Add elements (Stack LIFO)<br>r.lpush(&quot;task_queue&quot;, &quot;task_c&quot;, &quot;task_b&quot;, &quot;task_a&quot;) </pre><pre># Process tasks (Queue FIFO using RPOP)<br># The output will be &quot;task_a&quot;<br>task = r.rpop(&quot;task_queue&quot;)</pre><h3>3. Hashes: Object Storage Efficiency 📦</h3><h3>What is it?</h3><p>A <strong>Hash</strong> is a map between string <strong>fields</strong> and string <strong>values</strong>. It’s the perfect way to represent an object or a record, like a user profile or a product entry.</p><h3>Why and Where to Use It?</h3><ul><li><strong>Object Modeling:</strong> Storing all properties of an object (e.g., user name, email, and age) under a single key (user:100). This saves key-space and makes fetching the full object a single operation.</li><li><strong>Inventory/Product Details:</strong> Storing details of a product SKU.</li></ul><h3>Behind the Scenes: Storage</h3><p>For small Hashes (with a few fields), Redis uses <strong>Ziplist</strong> encoding — a compact, sequential memory layout. Once the Hash grows larger than configuration limits, it automatically converts to a standard <strong>Hash Table</strong>. This adaptive storage is why Redis is so memory efficient for simple objects.</p><h3>Code Example (Python/Client):</h3><pre># HSET: Storing a user object<br>r.hset(&quot;user:201&quot;, mapping={<br>    &quot;name&quot;: &quot;Bob&quot;,<br>    &quot;city&quot;: &quot;London&quot;,<br>    &quot;last_login&quot;: &quot;2025-11-14&quot;<br>})</pre><pre># HGETALL: Fetching the entire object<br>user_data = r.hgetall(&quot;user:201&quot;)</pre><h3>4. Sets: Uniqueness and Relationships 🤝</h3><h3>What is it?</h3><p>A <strong>Set</strong> is an <strong>unordered collection</strong> of <strong>unique</strong> strings. Duplicate elements are automatically rejected.</p><h3>Why and Where to Use It?</h3><ul><li><strong>Tagging and Categorization:</strong> Storing all tags associated with an article.</li><li><strong>Unique Tracking:</strong> Tracking unique visitors to a website (use SADD and then SCARD for the total count).</li><li><strong>Relationships/Intersections:</strong> Using set operations (SINTER, SUNION, SDIFF) to quickly find common friends, mutual followers, or users sharing the same characteristics.</li></ul><h3>Behind the Scenes: Storage</h3><p>Similar to other structures, small Sets of integers are encoded as an <strong>Intset</strong> — a highly compact, sorted array structure. Larger or non-integer Sets are stored using a standard <strong>Hash Table</strong>, where the stored members are the keys, and the value is set to null, leveraging the hash table’s $O(1)$ lookup for efficient uniqueness checking.</p><h3>Code Example (Python/Client):</h3><pre># SADD: Adding members to a Set (Duplicates are ignored)<br>r.sadd(&quot;article:123:tags&quot;, &quot;redis&quot;, &quot;caching&quot;, &quot;database&quot;, &quot;redis&quot;)</pre><pre># SCARD: Get the count of unique tags<br>unique_count = r.scard(&quot;article:123:tags&quot;) # Result: 3</pre><h3>5. Sorted Sets (ZSET): Ranking and Scoring 🏆</h3><h3>What is it?</h3><p>A <strong>Sorted Set</strong> is similar to a Set, but every member is associated with a <strong>score</strong> (a floating-point number). Members are always kept <strong>ordered by their score</strong>.</p><h3>Why and Where to Use It?</h3><ul><li><strong>Leaderboards:</strong> The classic use case: storing player IDs as members and their scores as the score, allowing for quick ranking (ZREVRANGE).</li><li><strong>Priority Queues:</strong> Using the score as a priority level.</li><li><strong>Time-Series Indexing:</strong> Using a timestamp as the score to quickly fetch a range of events occurring within a specific time window.</li></ul><h3>Behind the Scenes: Storage</h3><p>Sorted Sets utilize a powerful and efficient combination of two data structures:</p><ul><li>A <strong>Hash Table:</strong> Used to map members to their scores, enabling fast $O(1)$ score lookups.</li><li>A <strong>Skiplist:</strong> A probabilistic data structure that enables fast $O(\log N)$ (logarithmic time) operations for range queries (like fetching the top 10 ranked users) and insertion/deletion while keeping the data sorted.</li></ul><h3>Code Example (Python/Client):</h3><pre># ZADD: Adding members with scores<br>r.zadd(&quot;game:leaderboard&quot;, {&quot;player_a&quot;: 1000, &quot;player_b&quot;: 1500, &quot;player_c&quot;: 500})</pre><pre># ZREVRANGE: Get the top 2 players (reverse order by score)<br>top_players = r.zrevrange(&quot;game:leaderboard&quot;, 0, 1, withscores=True)<br># Result: [(&#39;player_b&#39;, 1500.0), (&#39;player_a&#39;, 1000.0)]</pre><h3>Conclusion: The Redis Advantage</h3><p>Redis’s true power lies in its <strong>simplicity, speed, and adaptive encoding</strong>. By intelligently choosing between compact encodings (like Ziplist and Intset) and traditional Hash Tables/Skiplists, Redis optimizes memory use without sacrificing the $O(1)$ and $O(\log N)$ performance that modern applications demand. When you choose a Redis data type, you’re not just picking a structure; you’re selecting a finely-tuned engine optimized for that specific data access pattern.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6c81add9e90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Ace Your Backend Interview: The Ultimate Q&A Guide]]></title>
            <link>https://medium.com/@mrkishoremani/ace-your-backend-interview-the-ultimate-q-a-guide-84013533852d?source=rss-844edccb9f62------2</link>
            <guid isPermaLink="false">https://medium.com/p/84013533852d</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[back-end-developer]]></category>
            <category><![CDATA[python-backend]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[the kishore]]></dc:creator>
            <pubDate>Tue, 11 Nov 2025 18:24:38 GMT</pubDate>
            <atom:updated>2025-11-11T18:24:38.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*PqZ-6VIqR7Y8d9EfWUrBXQ.png" /></figure><p>Ready to land that backend developer role? This post breaks down the core technical questions, from Python fundamentals and cloud architecture to real-world system design and security. Master these concepts to showcase your expertise in <strong>Python, Django, Flask, and AWS</strong>!</p><h3>🐍 Python Language Deep Dive &amp; Efficiency</h3><p>These questions test your understanding of Python’s memory management, efficiency, and language features.</p><h3>1. What is self in Python OOP?</h3><p>In Python, <strong>self</strong> refers to the <strong>current instance of the class</strong>. It&#39;s the first parameter in an instance method and is used to access that object&#39;s <strong>variables (attributes)</strong> and <strong>methods</strong>.</p><h3>2. List vs. Tuple: Which is Faster and Why?</h3><p>A <strong>List</strong> is <strong>mutable</strong> (can be changed). A <strong>Tuple</strong> is <strong>immutable</strong> (cannot be modified).</p><p><strong>Tuples are faster</strong> than lists because Python can perform optimizations and use less memory since their size and contents are guaranteed never to change.</p><h3>3. Why is List Comprehension Faster than a Normal for Loop?</h3><p>List comprehensions ([x * 2 for x in data]) are faster (often <strong>30–40% faster</strong> on large data) primarily because:</p><ol><li><strong>C-Level Execution:</strong> Python’s internal engine executes list comprehensions in optimized <strong>C code</strong>.</li><li><strong>Efficient Memory:</strong> Memory for the entire new list is often allocated in a <strong>single step</strong>, unlike loops where the list is repeatedly resized with each .append() call.</li></ol><h3>4. If you have a million constant, unique numbers and need ultra-fast membership checking (in operation), what data type do you choose?</h3><p>I would choose a <strong>frozenset</strong>. It is immutable (since the data is constant) and provides an average time complexity of <strong>$O(1)$ (Constant Time)</strong> for membership checking, which is the fastest possible lookup.</p><h3>5. Built-in Data Type Classification</h3><p>Python’s data types are classified into two sections based on memory behavior:</p><ul><li><strong>Immutable Types:</strong> (int, str, tuple, frozenset) – Modifying them creates a <strong>new memory object</strong>.</li><li><strong>Mutable Types:</strong> (list, dict, set) – They <strong>share the same memory</strong>, and changes made through one variable reflect in the other.</li></ul><h3>💻 Framework, Scaling, and Architecture</h3><p>These questions cover how you build, secure, and scale a production application.</p><h3>6. How do you scale a Django or Flask application?</h3><p>Scaling means improving an application’s ability to handle more users and requests efficiently. I use a combination of techniques:</p><ol><li><strong>Load Balancing:</strong> Using <strong>Nginx</strong> or <strong>AWS ELB</strong> to distribute traffic across multiple app servers.</li><li><strong>Caching:</strong> Using <strong>Redis</strong> or <strong>Memcached</strong> for fast retrieval of common data.</li><li><strong>Asynchronous Tasks:</strong> Offloading heavy jobs (like emails) to a background worker using <strong>Celery</strong>.</li><li><strong>Horizontal Scaling:</strong> Deploying multiple containers using <strong>Docker</strong> or <strong>Kubernetes</strong>.</li></ol><h3>7. Django Asynchronous Task Tool and Components</h3><p>To run reliable background tasks asynchronously, we use <strong>Celery</strong>. The three main components are:</p><ol><li><strong>Broker:</strong> The <strong>message queue</strong> that receives and delivers tasks (e.g., <strong>Redis</strong> or <strong>RabbitMQ</strong>).</li><li><strong>Worker:</strong> The separate process that <strong>executes</strong> the tasks from the queue.</li><li><strong>Backend:</strong> Stores the task <strong>results</strong> or their status.</li></ol><h3>8. What is a Signal in Django?</h3><p>A signal is a way for different parts of the application to <strong>communicate when certain events occur</strong> (e.g., after a user is saved). It allows for <strong>decoupled code</strong> execution. For example, using the built-in post_save signal to create a profile automatically after a user registers.</p><h3>9. Django ORM Query Example</h3><p><strong>Query:</strong> Retrieve all Book objects where the publication_year is greater than 2000 <strong>AND</strong> the author&#39;s name starts with &#39;J&#39;.</p><p>Python</p><pre>Book.objects.filter(publication_year__gt=2000, author__name__startswith=&#39;J&#39;)</pre><h3>10. Purpose of {% csrf_token %} in Django Forms</h3><p>The tag adds a <strong>hidden token</strong> to forms to protect against <strong>Cross-Site Request Forgery (CSRF)</strong> attacks. Django verifies this token on form submission to ensure the request came from a trusted source (your own site).</p><h3>🌐 Security and Networking</h3><h3>11. Authentication vs. Authorization</h3><ul><li><strong>Authentication (AuthN):</strong> <strong>Verifying who the user is</strong> (“Are you Jane?”).</li><li><strong>Authorization (AuthZ):</strong> <strong>Deciding what the user can do</strong> after they are verified (“Can Jane view this page?”).</li></ul><h3>☁️ Cloud &amp; System Design (AWS)</h3><h3>12. Uploading a 15+ GB file fast to AWS S3</h3><p>For files $&gt;5$ GB (and especially $15+$ GB), I’d use:</p><ul><li><strong>S3 Multipart Upload:</strong> The file is split into chunks and uploaded <strong>in parallel</strong>.</li><li><strong>Pre-signed URLs:</strong> The <strong>frontend uploads directly to S3</strong> using a temporary, secure URL generated by the backend, bypassing the application server entirely as a bottleneck.</li></ul><h3>13. Why choose Python instead of Go or Java?</h3><p>I prefer Python because it delivers <strong>higher developer productivity</strong> and <strong>faster time-to-market</strong> due to its simplicity and powerful frameworks. While Go/Java are faster in raw performance, Python’s extensive ecosystem (AI/ML, data) and quick development cycle often make it the better choice for most web applications and startups.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84013533852d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Mastering Python: Your Advanced Interview Question Cheat Sheet]]></title>
            <link>https://medium.com/@mrkishoremani/mastering-python-your-advanced-interview-question-cheat-sheet-3af5d844f959?source=rss-844edccb9f62------2</link>
            <guid isPermaLink="false">https://medium.com/p/3af5d844f959</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[python-interview-question]]></category>
            <category><![CDATA[crack-the-interview]]></category>
            <dc:creator><![CDATA[the kishore]]></dc:creator>
            <pubDate>Thu, 06 Nov 2025 10:13:25 GMT</pubDate>
            <atom:updated>2025-11-06T10:13:25.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*cB6xMh349_hr1EHqjFRMSw.png" /><figcaption>python</figcaption></figure><h3>I. 🛠️ Python Internals &amp; Metaprogramming</h3><h3>1. What is Monkey Patching in Python?</h3><p>Explanation: Monkey patching in Python means modifying or extending code at runtime — typically by changing classes, methods, or modules dynamically without altering the original source code.</p><p>Keyword Answer: Runtime modification of classes or methods.</p><p>Python</p><pre>class Test:<br>    def greet(self):<br>        return &quot;Hello&quot;</pre><pre># Monkey patching function<br>def new_greet(self):<br>    return &quot;Hi&quot;</pre><pre>Test.greet = new_greet # Overwriting the original method<br>print(Test().greet())  # Output: Hi</pre><h3>2. What is MRO in Python?</h3><p><strong>Explanation:</strong> <strong>MRO</strong> stands for <strong>Method Resolution Order</strong> — it determines the sequence Python follows to look up methods and attributes in a class hierarchy, especially in <strong>multiple inheritance</strong>. It uses the <strong>C3 linearization algorithm</strong> to decide this order.</p><p>Python</p><pre>class A: pass<br>class B(A): pass<br>class C(B, A): pass</pre><pre>print(C.mro())<br># Output: [&lt;class &#39;__main__.C&#39;&gt;, &lt;class &#39;__main__.B&#39;&gt;, &lt;class &#39;__main__.A&#39;&gt;, &lt;class &#39;object&#39;&gt;]</pre><h3>3. What is __slots__ in Python?</h3><p><strong>Explanation:</strong> __slots__ is a special attribute in Python classes that defines a fixed set of attributes, helping to <strong>optimize memory</strong> and speed up attribute access by preventing the creation of the standard instance __dict__.</p><p>Python</p><pre>class Person:<br>    __slots__ = [&#39;name&#39;, &#39;age&#39;]</pre><pre>p = Person()<br>p.name = &quot;Kishore&quot;<br>p.age = 25<br># p.address = &quot;India&quot;  # ❌ Error: &#39;Person&#39; object has no attribute &#39;address&#39;</pre><h3>4. What is a Decorator?</h3><p><strong>Explanation:</strong> A decorator is a <strong>higher-order function</strong> that adds extra functionality to another function or method by wrapping it.</p><p>Python</p><pre>def my_decorator(func):<br>    def wrapper():<br>        print(&quot;Before function call&quot;)<br>        func()<br>        print(&quot;After function call&quot;)<br>    return wrapper</pre><pre>@my_decorator<br>def say_hello():<br>    print(&quot;Hello!&quot;)</pre><pre>say_hello()<br># Output: Before function call, Hello!, After function call</pre><h3>II. 💡 Concurrency, Memory &amp; Scopes</h3><h3>5. Difference between Multithreading and Multiprocessing?</h3><ul><li><strong>Multithreading</strong> $\rightarrow$ runs multiple threads in one process (<strong>shared memory</strong>), good for <strong>I/O-bound</strong> tasks, but limited by the GIL.</li><li><strong>Multiprocessing</strong> $\rightarrow$ runs multiple processes (<strong>separate memory</strong>), good for <strong>CPU-bound</strong> tasks, and <strong>bypasses the GIL</strong>.</li></ul><h3>6. What is GIL?</h3><p><strong>Explanation:</strong> The <strong>Global Interpreter Lock (GIL)</strong> ensures that <strong>only one thread executes Python code at a time</strong>, preventing memory conflicts. It’s a limitation for <strong>CPU-bound</strong> tasks, but not for <strong>I/O-bound</strong> tasks.</p><h3>7. How does Python’s memory management work?</h3><p><strong>Explanation:</strong> Python uses <strong>reference counting</strong> to manage memory and a <strong>garbage collector</strong> to clean up <strong>circular references</strong>. When an object’s reference count reaches zero, its memory is freed automatically.</p><h3>8. How does Python internally manage namespaces and variable scopes?</h3><p><strong>Explanation:</strong> A <strong>namespace</strong> is a container that maps variable names to their values. A <strong>scope</strong> defines where those names can be accessed. Python searches names using the <strong>LEGB rule</strong> $\rightarrow$ <strong>L</strong>ocal, <strong>E</strong>nclosing, <strong>G</strong>lobal, and <strong>B</strong>uilt-in.</p><p><strong>Example (LEGB):</strong></p><p>Python</p><pre>x = 10 # Global Scope</pre><pre>def outer():<br>    x = 20 # Enclosing Scope<br>    def inner():<br>        # x = 30 # Local Scope (If uncommented)<br>        print(x) # Accesses Enclosing x (20)</pre><pre>    inner()<br>    <br>outer() # Output: 20</pre><h3>III. 🔑 Data Structures &amp; Utilities</h3><h3>9. Difference between Tuple, List, and Set?</h3><ul><li><strong>List</strong> is <strong>mutable</strong> and <strong>ordered</strong>, allows duplicates.</li><li><strong>Tuple</strong> is <strong>immutable</strong> and <strong>ordered</strong>, allows duplicates.</li><li><strong>Set</strong> is <strong>mutable</strong> and <strong>unordered</strong>, stores only <strong>unique</strong> elements.</li></ul><h3>10. What is the difference between deepcopy and shallow copy in Python?</h3><ul><li><strong>Shallow copy</strong> copies only the outer object $\rightarrow$ <strong>inner objects are shared</strong>.</li><li><strong>Deep copy</strong> copies everything recursively $\rightarrow$ <strong>fully independent objects</strong>.</li></ul><p><strong>Example (Shallow vs. Deep Copy):</strong></p><p>Python</p><pre>import copy<br>data = [[1], 2]</pre><pre>shallow = copy.copy(data)<br>deep = copy.deepcopy(data)</pre><pre>shallow[0][0] = 99 # Affects data[0]<br>deep[0][0] = 100   # Does not affect data[0]</pre><pre>print(data)      # Output: [[99], 2]</pre><h3>11. What are iterators and generators? How do they work internally?</h3><ul><li><strong>Iterators</strong> use __iter__() and __next__() to fetch items one by one.</li><li>A <strong>generator</strong> is a special kind of iterator created using <strong>yield</strong> instead of return, making them <strong>memory-efficient</strong>.</li></ul><p><strong>Example (Generator):</strong></p><p>Python</p><pre>def infinite_sequence():<br>    num = 0<br>    while True:<br>        yield num # Pauses and saves state<br>        num += 1</pre><pre>gen = infinite_sequence()<br>print(next(gen)) # Output: 0<br>print(next(gen)) # Output: 1</pre><h3>12. Why do we use with in Python?</h3><p><strong>Explanation:</strong> We use <strong>with</strong> in Python to manage resources automatically — it ensures proper setup and cleanup (like closing files) without needing try-finally.</p><p><strong>Example:</strong></p><p>Python</p><pre># The &#39;with&#39; statement ensures file.close() is called automatically<br>with open(&quot;log.txt&quot;, &quot;r&quot;) as f:<br>    content = f.read()<br># f.close() is guaranteed to be executed here</pre><h3>13. What are the built-in data types?</h3><p><strong>Explanation:</strong> Python has several built-in data types like <strong>int</strong>, <strong>float</strong>, <strong>str</strong>, <strong>bool</strong>, <strong>list</strong>, <strong>tuple</strong>, <strong>set</strong>, and <strong>dict</strong>.</p><h3>14. What is a suite (set of block)?</h3><p><strong>Explanation:</strong> A <strong>suite</strong> in Python means a group of statements that run together under a control structure — like the <strong>indented block</strong> after if, for, while, def, or class.</p><h3>IV. ⚙️ Object-Oriented Programming (OOP)</h3><h3>15. What is OOPs?</h3><p><strong>Explanation:</strong> <strong>OOPs (Object-Oriented Programming)</strong> is a programming approach that organizes code.</p><p><strong>4 Main OOP Principles:</strong></p><ul><li><strong>Encapsulation</strong> — Hiding data and methods inside a class.</li><li><strong>Abstraction</strong> — Showing only essential features, hiding details.</li><li><strong>Inheritance</strong> — Reusing code by deriving new classes from existing ones.</li><li><strong>Polymorphism</strong> — Same method behaves differently based on the object.</li></ul><h3>16. What is Abstract Class in Python?</h3><p><strong>Explanation:</strong> An <strong>abstract class</strong> defines a <strong>blueprint</strong> for other classes using the <strong>abc module</strong>, contains <strong>abstract methods</strong>, and <strong>cannot be instantiated directly</strong>. Subclasses must implement the abstract methods.</p><p><strong>Example:</strong></p><p>Python</p><pre>from abc import ABC, abstractmethod</pre><pre>class Shape(ABC):<br>    @abstractmethod<br>    def area(self): # Subclasses must implement this<br>        pass</pre><pre>class Circle(Shape):<br>    def area(self):<br>        return &quot;Calculated area.&quot;</pre><pre># s = Shape() # ❌ Fails<br>c = Circle()  # ✅ Works</pre><h3>17. What is the difference between @staticmethod, @classmethod, and normal methods?</h3><ul><li><strong>@staticmethod</strong> doesn’t need access to the instance or class. It acts as a regular function inside a class.</li><li><strong>@classmethod</strong> works within the class itself, receiving <strong>cls</strong> as the first argument.</li><li><strong>Normal method</strong> works with the instance itself, receiving <strong>self</strong> as the first argument.</li></ul><p><strong>Example (@classmethod):</strong></p><p>Python</p><pre>class Pet:<br>    def __init__(self, name):<br>        self.name = name</pre><pre>    @classmethod<br>    def from_string(cls, data_str):<br>        name = data_str.split(&#39;-&#39;)[0]<br>        return cls(name) # Uses &#39;cls&#39; to create an instance</pre><pre>dog = Pet.from_string(&quot;Buddy-Labrador&quot;)<br>print(dog.name) # Output: Buddy</pre><h3>18. What is Duck Typing?</h3><p><strong>Explanation:</strong> <strong>Duck typing</strong> means Python cares about <strong>what an object can do</strong>, not what type it is — if it acts like the right object (i.e., has the necessary methods), it’s accepted.</p><p><strong>Example:</strong></p><p>Python</p><pre>class Plane:<br>    def fly(self):<br>        return &quot;Flying high&quot;<br>class Duck:<br>    def fly(self):<br>        return &quot;Waddling and flying&quot;</pre><pre>def get_airborne(obj):<br>    return obj.fly() # Only cares that &#39;obj&#39; has a &#39;fly&#39; method</pre><pre>print(get_airborne(Plane()))<br>print(get_airborne(Duck()))</pre><h3>19. What are Dunder Methods?</h3><p><strong>Explanation:</strong> <strong>Dunder methods</strong> are special double-underscore methods (like __init__, __str__) used to <strong>define or override how objects behave</strong> with operators and built-in functions in Python.</p><p><strong>Example (</strong><strong>__add__):</strong></p><p>Python</p><pre>class Vector:<br>    def __init__(self, x, y):<br>        self.x = x<br>        self.y = y<br>    <br>    # Overrides the &#39;+&#39; operator<br>    def __add__(self, other):<br>        return Vector(self.x + other.x, self.y + other.y)</pre><pre>v1 = Vector(1, 2)<br>v2 = Vector(3, 4)<br>v3 = v1 + v2<br>print(v3.x, v3.y) # Output: 4 6</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3af5d844f959" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Guide to Acing React Hooks Interview Questions]]></title>
            <link>https://medium.com/@mrkishoremani/the-ultimate-guide-to-acing-react-hooks-interview-questions-ecf0ecb84917?source=rss-844edccb9f62------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecf0ecb84917</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[best]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[the kishore]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 06:07:50 GMT</pubDate>
            <atom:updated>2026-08-02T13:40:52.889Z</atom:updated>
            <content:encoded><![CDATA[<p>Stressed about your upcoming React interview? Worried about those tricky React Hooks questions? Don’t be! This blog post is your ultimate secret weapon. We’ve compiled the most common and essential React Hooks interview questions and answers, but more importantly, we’ve broken them down into easy-to-remember chunks. Let’s dive in and get you ready to ace that interview!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*MRDqCr7mabVesT5vzEXHgg.png" /></figure><h3>Why React Hooks? The Fundamentals</h3><h4>Question 1: What are React Hooks, and why were they introduced?</h4><p><strong>Answer:</strong> Hooks are special functions that “hook into” React features from function components. They were introduced to solve common problems faced with class components:</p><ul><li><strong>Sharing stateful logic:</strong> Hooks provide a cleaner way to reuse logic without complex patterns.</li><li><strong>Complex components:</strong> They allow you to organize related logic (like data fetching) together instead of splitting it across different lifecycle methods.</li><li><strong>Confusing classes:</strong> They eliminate the need for the this keyword and class syntax, which can be a barrier for many developers.</li></ul><p><strong>Easy Way to Remember:</strong> Think of a <strong>“Hook”</strong> as a tool that lets you grab React’s powers (like state and lifecycle) without using a clumsy <strong>“Class.”</strong></p><h3>The Core Hooks: useState &amp; useEffect</h3><h4>Question 2: Explain the useState hook. Give an example.</h4><p><strong>Answer:</strong> useState is the most basic hook. It lets you add state to a functional component. It returns an array with two items: the <strong>current state value</strong> and a <strong>function to update that value.</strong></p><p><strong>Example:</strong></p><pre>import React, { useState } from &#39;react&#39;;</pre><pre>function Counter() {<br>  const [count, setCount] = useState(0);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;You clicked {count} times&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Click me&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Easy Way to Remember:</strong> useState is like a <strong>&quot;state-keeper&quot;</strong> with a special <strong>&quot;setter&quot;</strong> function. Remember the two-part array it returns: [thing, setThing].</p><h4>Question 3: Explain the useEffect hook. What does it replace?</h4><p><strong>Answer:</strong> useEffect lets you perform &quot;side effects&quot; in function components. Side effects are things like data fetching, subscriptions, or manually changing the DOM. It replaces a combination of class lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.</p><p>It takes two arguments: a <strong>function</strong> (the effect) and an optional <strong>dependency array.</strong></p><p><strong>Easy Way to Remember:</strong> Think of useEffect as a <strong>&quot;lifecycle manager&quot;</strong> for functional components. It <strong>&quot;runs a function&quot;</strong> (effect) when certain <strong>&quot;dependencies&quot;</strong> change.</p><h4>Question 4: What is the purpose of the dependency array in useEffect?</h4><p><strong>Answer:</strong> The dependency array controls when the useEffect function runs.</p><ul><li><strong>No array:</strong> The effect runs after <em>every</em> render.</li><li><strong>Empty array (</strong><strong>[]):</strong> The effect runs only <em>once</em> after the initial render (like componentDidMount).</li><li><strong>Array with values (</strong><strong>[value1, value2]):</strong> The effect runs only when one of the values in the array changes.</li></ul><p><strong>Easy Way to Remember:</strong> The dependency array is the <strong>“trigger”</strong> for your effect. Think of it as a <strong>“watch list.”</strong></p><h3>Advanced Hooks &amp; Customization</h3><h4>Question 5: When would you use useContext?</h4><p><strong>Answer:</strong> useContext allows you to access a React Context in a functional component. Context is a way to pass data through the component tree without having to manually pass props down at every level, helping you avoid &quot;prop drilling.&quot;</p><p><strong>Easy Way to Remember:</strong> useContext is your shortcut to a global <strong>&quot;state-store.&quot;</strong> Instead of <strong>&quot;prop-drilling,&quot;</strong> you just <strong>&quot;grab&quot;</strong> the context directly.</p><h4>Question 6: What is a Custom Hook, and why would you create one?</h4><p><strong>Answer:</strong> A Custom Hook is a JavaScript function whose name starts with “use” and that calls other hooks inside it. We create them to <strong>reuse stateful logic</strong> across different components.</p><p><strong>Example:</strong></p><pre>// A custom hook to fetch data<br>import { useState, useEffect } from &#39;react&#39;;</pre><pre>function useFetch(url) {<br>  const [data, setData] = useState(null);<br>  useEffect(() =&gt; {<br>    fetch(url).then(res =&gt; res.json()).then(data =&gt; setData(data));<br>  }, [url]);<br>  return data;<br>}</pre><p><strong>Easy Way to Remember:</strong> Custom hooks are all about <strong>“reusability.”</strong> They’re like a <strong>“recipe”</strong> for stateful logic you can use again and again.</p><h3>The Golden Rules of Hooks</h3><h4>Question 7: What are the two main rules of Hooks?</h4><p><strong>Answer:</strong> There are two golden rules for using hooks:</p><ul><li><strong>Only Call Hooks at the Top Level:</strong> Don’t call hooks inside loops, conditions, or nested functions.</li><li><strong>Only Call Hooks from React Function Components or Custom Hooks:</strong> Don’t call them from regular JavaScript functions.</li></ul><p><strong>Easy Way to Remember:</strong> Remember <strong>TLC</strong>: <strong>T</strong>op <strong>L</strong>evel <strong>C</strong>omponent. Hooks must be called at the <strong>TLC</strong> of your function component.</p><h3>Conclusion</h3><p>And there you have it! By understanding these core concepts and using these simple memory tricks, you’ll be well-prepared for any React Hooks interview question. Practice writing these examples, and you’ll not only remember the answers but truly understand the “why” behind them. Good luck on your interview!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecf0ecb84917" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Django Authentication: Basic vs Token vs JWT — Everything You Need to Know]]></title>
            <link>https://medium.com/@mrkishoremani/mastering-django-authentication-basic-vs-token-vs-jwt-everything-you-need-to-know-83312f96fd96?source=rss-844edccb9f62------2</link>
            <guid isPermaLink="false">https://medium.com/p/83312f96fd96</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[the kishore]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 07:06:49 GMT</pubDate>
            <atom:updated>2026-08-02T13:39:13.319Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Django Authentication: Basic vs Token vs JWT — Everything You Need to Know</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*YYdcwENPKjpXFA_Y1xLFpQ.png" /><figcaption>Security</figcaption></figure><p>In modern web development, securing APIs is crucial, and Django provides several built-in methods for authentication. Whether you’re preparing for a job interview or building a robust web application, understanding how <strong>Basic Authentication</strong>, <strong>Token Authentication</strong>, and <strong>JWT Authentication</strong> differ is essential..</p><p>In this guide, we’ll break down these three common Django authentication methods, explore their advantages and disadvantages, and provide interview tips to help you explain them clearly.</p><h3>What is Authentication in Django?</h3><p>Authentication ensures that only verified users can access protected resources in your web application. In Django, authentication can be implemented using different strategies. We’ll cover the following three:</p><ol><li><strong>Basic Authentication</strong></li><li><strong>Token Authentication</strong></li><li><strong>JWT (JSON Web Token) Authentication</strong></li></ol><h3>1. Basic Authentication</h3><p><strong>Basic Authentication</strong> is a straightforward authentication mechanism where the client provides a username and password with every request. These credentials are encoded in Base64 and sent in the Authorization header.</p><h4>How it Works:</h4><ol><li>The client sends the username and password.</li><li>The server decodes and verifies the credentials.</li><li>If the credentials are valid, access is granted.</li></ol><h4>Pros:</h4><ul><li>Simple to implement.</li><li>Works out of the box with Django REST framework.</li></ul><h4>Cons:</h4><ul><li>Not secure unless used with HTTPS.</li><li>Credentials are sent with every request.</li><li>No session management.</li></ul><h4>When to Use:</h4><ul><li>Suitable for small internal APIs or quick prototypes.</li></ul><p><strong>Example Request:</strong></p><pre>Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=</pre><h3>2. Token Authentication</h3><p><strong>Token Authentication</strong> is a more secure approach where the user logs in once and receives a token that can be used for subsequent requests. Django’s rest_framework.authtoken provides support for token-based authentication.</p><h4>How it Works:</h4><ol><li>The user sends their username and password to the login endpoint.</li><li>The server verifies the credentials and returns a token.</li><li>The token is sent with each request in the Authorization header.</li></ol><h4>Pros:</h4><ul><li>No need to send the username and password repeatedly.</li><li>Tokens can be easily revoked.</li><li>Better security than Basic Authentication.</li></ul><h4>Cons:</h4><ul><li>Requires token storage on the client-side.</li><li>Tokens can expire or become invalid.</li></ul><h4>When to Use:</h4><ul><li>Ideal for APIs where session management is unnecessary.</li></ul><p><strong>Example Request:</strong></p><pre>Authorization: Token abc123xyz456</pre><h3>3. JWT (JSON Web Token) Authentication</h3><p><strong>JWT (JSON Web Token)</strong> is a modern and popular method for securing APIs. A JWT is a self-contained token that includes all necessary user information and an expiration time. It is signed by the server and can be verified without querying the database.</p><h4>How it Works:</h4><ol><li>The user sends their credentials to a login endpoint.</li><li>The server generates a JWT and sends it back.</li><li>The client includes the JWT in the Authorization header for every request.</li></ol><h4>Pros:</h4><ul><li>Scalable and stateless.</li><li>Tokens are self-contained, reducing the need for frequent database lookups.</li><li>Excellent for cross-domain authentication.</li></ul><h4>Cons:</h4><ul><li>Tokens can be large.</li><li>If compromised, a token remains valid until it expires.</li><li>Requires proper token management (refresh tokens).</li></ul><h4>When to Use:</h4><ul><li>Perfect for modern web and mobile applications that require scalable and secure authentication.</li></ul><p><strong>Example Request:</strong></p><pre>Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...</pre><p>In Django, JWT Authentication can be implemented using libraries like djangorestframework-simplejwt.</p><h3>Comparison of Authentication Types</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*nm1iP90Dous5LiBjwPlJCw.png" /><figcaption>Authentication Types</figcaption></figure><h3>Common Interview Questions and How to Answer Them</h3><p><strong>1. Can you explain the differences between Basic Authentication, Token Authentication, and JWT Authentication?</strong><br>“Basic Authentication sends the username and password with each request, which is not secure without HTTPS. Token Authentication improves security by issuing a token after login, which the client can use for subsequent requests. JWT Authentication goes a step further, providing a self-contained token that is highly scalable and stateless.”</p><p><strong>2. What are the advantages of using JWT over Token Authentication?</strong><br>“JWT tokens are self-contained and do not require a database check for each request, making them more scalable. They are also easier to use for cross-domain applications.”</p><p><strong>3. How would you secure an API in Django?</strong><br>“I would use JWT Authentication for scalability and security. Additionally, I would implement HTTPS, use refresh tokens, and ensure proper token expiration policies.”</p><h3>Conclusion</h3><p>Choosing the right authentication method depends on your project’s needs. Basic Authentication is suitable for simple setups, Token Authentication is great for moderately secure APIs, and JWT Authentication is the best option for modern, scalable applications.</p><p>Understanding these differences will help you not only build secure applications but also impress your interviewers. Happy coding and good luck with your interview preparation!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83312f96fd96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crack Your Python Interview: 15 Must-Know Questions to Ace Your Next Job!]]></title>
            <link>https://medium.com/@mrkishoremani/crack-your-python-interview-15-must-know-questions-to-ace-your-next-job-0962cd08aae6?source=rss-844edccb9f62------2</link>
            <guid isPermaLink="false">https://medium.com/p/0962cd08aae6</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-interview]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[the kishore]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 10:33:52 GMT</pubDate>
            <atom:updated>2026-08-02T13:38:23.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*Hf875bamvHGjDgxabQESTQ.png" /><figcaption>Python Interview Questions You Must Know Before Your Next Interview</figcaption></figure><p>Preparing for a <strong>Python interview</strong>? Before you step in, make sure you go through these <strong>essential questions</strong>. These questions cover 90% of what interviewers ask!</p><h3>1. What is the difference between deepcopy and shallow copy in Python?</h3><ul><li><strong>Deepcopy</strong> creates a copy of the object <strong>and</strong> its elements.</li><li><strong>Shallow copy</strong> creates a copy of the object but references the elements of the original object.</li></ul><p>Example:</p><pre>import copy<br>original_list = [[1, 2, 3], [4, 5, 6]]<br>shallow_copied_list = copy.copy(original_list)<br>deep_copied_list = copy.deepcopy(original_list)</pre><h3>2. How does Python handle memory management?</h3><ul><li>Python’s <strong>memory management</strong> is handled by the <strong>Python Memory Manager</strong>.</li><li>It ensures <strong>memory allocation, deallocation, and garbage collection</strong>.</li><li><strong>Garbage collection</strong> automatically cleans up objects that are no longer in use.</li></ul><h3>3. What are list comprehensions in Python?</h3><ul><li><strong>List comprehensions</strong> provide a <strong>concise way</strong> to create lists.</li></ul><p>Example:</p><pre>nums = [1, 2, 3, 4, 5, 6, 7, 8]<br>even_nums = [num for num in nums if num % 2 == 0]<br>print(even_nums)  # Output: [2, 4, 6, 8]</pre><h3>4. What are decorators in Python, and how are they used?</h3><ul><li><strong>Decorators</strong> are functions that allow adding extra behavior to functions or classes <strong>without modifying their code</strong>.</li></ul><p>Example:</p><pre>def my_decorator(func):<br>    def wrapper():<br>        print(&quot;Before function execution&quot;)<br>        func()<br>        print(&quot;After function execution&quot;)<br>    return wrapper</pre><pre>@my_decorator<br>def say_hello():<br>    print(&quot;Hello!&quot;)</pre><pre>say_hello()</pre><h3>5. What is the difference between @staticmethod and @classmethod?</h3><ul><li><strong>@staticmethod</strong> doesn’t need access to the instance or class. It acts as a regular function inside a class.</li><li><strong>@classmethod</strong> works <strong>within the class itself</strong>, receiving cls as the first argument.</li></ul><p>Example:</p><pre>class MyClass:<br>    @staticmethod<br>    def static_method():<br>        print(&quot;I don’t access class attributes&quot;)</pre><pre>    @classmethod<br>    def class_method(cls):<br>        print(&quot;I have access to class attributes&quot;, cls)</pre><h3>6. How does Python’s garbage collection work?</h3><p>Python automatically frees memory by removing objects that are no longer used. It uses two methods:</p><ol><li><strong>Reference Counting</strong>: If an object has no references, it is deleted.</li><li><strong>Garbage Collection</strong>: Python detects <strong>circular references</strong> and removes them.</li></ol><h3>7. What is the purpose of the with statement in Python?</h3><ul><li>The <strong>with statement</strong> simplifies resource management.</li><li>It <strong>automatically</strong> closes a file after usage, even if an error occurs.</li></ul><p>Example:</p><pre>with open(&quot;file.txt&quot;, &quot;r&quot;) as file:<br>    content = file.read()<br># No need to manually close the file</pre><h3>8. What is middleware in Django?</h3><ul><li>Middleware allows developers to process requests &amp; responses <strong>globally</strong> across an application.</li></ul><p>Example middleware use cases:</p><ul><li><strong>Authentication &amp; authorization</strong></li><li><strong>CSRF protection</strong></li><li><strong>Session management</strong></li></ul><p>Example:</p><pre>class MyMiddleware:<br>    def __init__(self, get_response):<br>        self.get_response = get_response<br>    <br>    def __call__(self, request):<br>        print(&quot;Middleware executed&quot;)<br>        response = self.get_response(request)<br>        return response</pre><h3>9. How is a request passed through middleware in Django?</h3><ul><li>Django passes requests through middleware <strong>in order</strong>, allowing you to modify requests before reaching the view.</li><li><strong>Example</strong>: CSRF middleware prevents <strong>Cross-Site Request Forgery (CSRF)</strong> attacks.</li></ul><p>More on Django’s <strong>Request-Response Cycle</strong>: <a href="https://medium.com/@ksarthak4ever/django-request-response-cycle-2626e9e8606e">Read Here</a></p><h3>10. What is __init__ in Python?</h3><ul><li>__init__ is a <strong>constructor</strong> used to initialize object attributes when an object is created.</li></ul><p>Example:</p><pre>class Person:<br>    def __init__(self, name, age):<br>        self.name = name<br>        self.age = age</pre><h3>11. What is inheritance?</h3><ul><li><strong>Inheritance</strong> allows a child class to <strong>acquire properties and methods</strong> from a parent class, promoting code reuse.</li></ul><p>Example:</p><pre>class Animal:<br>    def speak(self):<br>        return &quot;I make a sound&quot;</pre><pre>class Dog(Animal):<br>    def speak(self):<br>        return &quot;Woof!&quot;</pre><h3>12. What is an Abstract Base Class (ABC) in Python?</h3><ul><li><strong>Abstract Base Classes (ABCs)</strong> define a <strong>blueprint</strong> for other classes.</li><li>They ensure that <strong>subclasses implement certain methods</strong>.</li><li>Part of the abc module, ABCs use @abstractmethod.</li></ul><p>Example:</p><pre>from abc import ABC, abstractmethod</pre><pre>class Animal(ABC):<br>    @abstractmethod<br>    def sound(self):<br>        pass</pre><pre>class Dog(Animal):<br>    def sound(self):<br>        return &quot;Woof!&quot;</pre><h3>13. What is the difference between is and == in Python?</h3><ul><li><strong>is</strong> checks <strong>object identity</strong> (whether two references point to the same object in memory).</li><li><strong>==</strong> checks <strong>value equality</strong> (whether two objects have the same value).</li></ul><p>Example:</p><pre>x = [1, 2, 3]<br>y = [1, 2, 3]<br>z = x</pre><pre>print(x == y)  # True (values are the same)<br>print(x is y)  # False (different objects)<br>print(x is z)  # True (same object)</pre><h3>14. What are Python’s built-in data structures?</h3><ul><li><strong>Lists</strong> ([]): Ordered, mutable collections.</li><li><strong>Tuples</strong> (()): Ordered, immutable collections.</li><li><strong>Sets</strong> ({}): Unordered, unique elements.</li><li><strong>Dictionaries</strong> ({key: value}): Key-value pairs.</li></ul><h3>15. What is the difference between a module and a package in Python?</h3><ul><li><strong>Module</strong>: A single Python file containing functions and classes.</li><li><strong>Package</strong>: A directory containing multiple Python modules with an __init__.py file.</li></ul><h3>Final Thoughts</h3><p>If you’re preparing for a Python interview, these questions will <strong>definitely boost your confidence</strong>. Keep practicing, and good luck! 🚀</p><p>Did I miss any key questions? Let me know in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0962cd08aae6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>