<?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 Shagor Robidush on Medium]]></title>
        <description><![CDATA[Stories by Shagor Robidush on Medium]]></description>
        <link>https://medium.com/@sagorrobidush?source=rss-103bcad913c9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ro4ueU11UpPEbHFq3QhZXg.png</url>
            <title>Stories by Shagor Robidush on Medium</title>
            <link>https://medium.com/@sagorrobidush?source=rss-103bcad913c9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:06:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sagorrobidush/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[Back-of-the-Envelope Estimation: How to Calculate DAU, QPS, Storage, and Bandwidth]]></title>
            <link>https://medium.com/@sagorrobidush/back-of-the-envelope-estimation-5a7d1651a904?source=rss-103bcad913c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a7d1651a904</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Shagor Robidush]]></dc:creator>
            <pubDate>Fri, 27 Nov 2026 13:41:01 GMT</pubDate>
            <atom:updated>2026-11-27T13:41:01.633Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Learn How Engineers Estimate System Capacity Using Simple Mathematics and Real-World Examples.</em></p><figure><img alt="Animated LinkedIn blog banner featuring the title “Back-of-the-Envelope Estimation: How to Calculate DAU, QPS, Storage, and Bandwidth” alongside animated charts and icons illustrating daily active users, requests per second, data storage growth, and network bandwidth." src="https://cdn-images-1.medium.com/max/640/1*bVtJWBzNKr9kYdZihp7rgA.gif" /><figcaption>Step-by-step capacity estimation for a social media workload — comparing active users, average vs. peak RPS, metadata vs. media storage, outbound bandwidth, and key architectural components.</figcaption></figure><h3>Introduction: Can Your Application Handle One Million Users?</h3><p>Imagine you are building a social media application.</p><p>Initially, everything works perfectly.</p><p>You have:</p><ul><li>1,000 registered users.</li><li>A few hundred posts.</li><li>A small PostgreSQL database.</li><li>One Django application server.</li></ul><p>Your application performs well.</p><p>Now imagine your application becomes popular.</p><p>Within a few months:</p><ul><li>100,000 users visit your application every day.</li><li>Thousands of users upload images.</li><li>Millions of API requests are generated.</li><li>Your database grows every day.</li><li>Network traffic increases significantly.</li></ul><p>Suddenly, you need to answer some important engineering questions:</p><ul><li>How many API requests will the system receive per second?</li><li>How much storage will you need?</li><li>How much network bandwidth will your servers consume?</li><li>How many application servers might be required?</li><li>Can your current infrastructure handle peak traffic?</li></ul><p>Would you immediately purchase a powerful server?</p><p>Probably not.</p><p>You first need to estimate the workload.</p><p>This is where <strong>Back-of-the-Envelope Estimation</strong> becomes useful.</p><p>It is a technique used by Software Engineers and System Architects to make quick, approximate calculations about a system’s expected workload and infrastructure requirements.</p><p>You don’t need complex software or advanced mathematics.</p><p>You need reasonable assumptions, basic formulas, and a clear understanding of how your application works.</p><p>Let’s learn how to do this step by step.</p><h3>1. What Is Back-of-the-Envelope Estimation?</h3><p>Back-of-the-Envelope Estimation is the process of calculating approximate system requirements using simple mathematical assumptions.</p><p>It helps engineers estimate:</p><ul><li>Number of active users.</li><li>Requests per second.</li><li>Data storage requirements.</li><li>Network bandwidth.</li><li>Read and write traffic.</li><li>Expected infrastructure capacity.</li></ul><p>The goal is not to calculate perfectly accurate numbers.</p><p>The goal is to understand the approximate scale of a system before investing time and money in implementation.</p><p>For example:</p><p>Suppose a client says:</p><p>“I want to build an application that will support one million users.”</p><p>That sounds like useful information.</p><p>But is one million users enough to estimate server requirements?</p><p>No.</p><p>You need more information.</p><p>Consider two applications:</p><p><strong>Application A:</strong></p><ul><li>1 million registered users.</li><li>10,000 users active daily.</li><li>Each active user generates 10 API requests per day.</li></ul><p><strong>Application B:</strong></p><ul><li>1 million registered users.</li><li>500,000 users active daily.</li><li>Each active user generates 100 API requests per day.</li></ul><p>Both applications have one million registered users.</p><p>But their workloads are completely different.</p><p>This is why understanding user activity is more important than looking only at total registered users.</p><h3>2. Understanding DAU, WAU, and MAU</h3><p>Before calculating system traffic, you should understand three common metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ubm8OBxIKpXZUdJSCPBBRA.gif" /><figcaption>Over request server load</figcaption></figure><h3>DAU — Daily Active Users</h3><p>DAU represents the number of unique users who actively use an application during a particular day.</p><p>Example:</p><p>Imagine your application has:</p><ul><li>Monday: 8,000 active users.</li><li>Tuesday: 9,500 active users.</li><li>Wednesday: 10,000 active users.</li></ul><p>Your Wednesday DAU is 10,000.</p><p>DAU helps engineers understand daily application usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cDUBwDqZEL4kdxu_6RyCdQ.png" /><figcaption>Envelope Estimation formula</figcaption></figure><h3>WAU — Weekly Active Users</h3><p>WAU represents the number of unique users who actively use an application during a seven-day period.</p><p>Example:</p><p>If 50,000 different users access your application at least once during a week, your WAU is 50,000.</p><h3>MAU — Monthly Active Users</h3><p>MAU represents the number of unique users who actively use an application during a month.</p><p>Example:</p><p>If 200,000 different users access your application during November, your November MAU is 200,000.</p><h3>DAU vs WAU vs MAU</h3><p>MetricMeaningTime PeriodDAUDaily Active Users1 DayWAUWeekly Active Users7 DaysMAUMonthly Active Users30 Days</p><p>These metrics help you understand how frequently users interact with your application.</p><p><strong>Important:</strong> Registered users, active users, and concurrent users are different measurements.</p><p>For example:</p><ul><li>Registered users: 1,000,000</li><li>DAU: 100,000</li><li>Users active at the same moment: 5,000</li></ul><p>You should never assume that all registered users are using your application simultaneously.</p><h3>3. What Is QPS? Understanding Requests Per Second</h3><p>QPS stands for <strong>Queries Per Second</strong>.</p><p>In system design, engineers also commonly use RPS (Requests Per Second).</p><p>These measurements describe how many requests a system receives or processes per second.</p><p>For example:</p><p>Imagine your application receives 1,000 API requests every second.</p><p>Your system is handling approximately 1,000 RPS.</p><p>Why is this important?</p><p>Because your server, database, and network must have enough capacity to handle incoming traffic.</p><h3>Average QPS Calculation</h3><p>The basic formula is:</p><p><strong>Average RPS = Total Requests / Total Seconds</strong></p><p>There are 86,400 seconds in one day.</p><p>Therefore:</p><pre>1 Day = 24 Hours</pre><pre>24 × 60 × 60 = 86,400 Seconds</pre><p>Let’s take an example.</p><p>Suppose your application receives 1,000,000 requests per day.</p><p>Then:</p><pre>Average RPS = 1,000,000 / 86,400</pre><pre>Average RPS = 11.57</pre><p>Your application receives approximately 12 requests per second on average.</p><p>But there is an important problem.</p><p>Real-world traffic is not evenly distributed throughout the day.</p><p>During certain hours, your application might receive significantly more requests.</p><p>This brings us to peak traffic.</p><h3>Understanding Peak RPS</h3><p>Peak RPS represents the highest expected request rate during a particular period.</p><p>For early estimation, engineers often assume a peak traffic multiplier.</p><p>For example:</p><pre>Average RPS = 12</pre><pre>Peak Multiplier = 5</pre><pre>Peak RPS = 12 × 5</pre><pre>Peak RPS = 60</pre><p>This means your system should be evaluated for approximately 60 requests per second during peak traffic.</p><p>A multiplier of 5 is only an illustrative assumption. Real peak traffic should ideally be estimated using historical traffic patterns, expected user behavior, and load testing.</p><h3>4. What Is Storage Estimation?</h3><p>Every application stores data.</p><p>As users interact with your application, the amount of stored information increases.</p><p>For example, a social media application may store:</p><ul><li>User information.</li><li>Posts.</li><li>Comments.</li><li>Likes.</li><li>Images.</li><li>Videos.</li><li>Messages.</li><li>Activity logs.</li></ul><p>If you don’t estimate storage requirements, your database and storage infrastructure may become difficult to manage as the application grows.</p><p>Let’s calculate storage requirements using a practical example.</p><h3>Example: Social Media Application</h3><p>Suppose your application has:</p><ul><li>100,000 daily active users.</li><li>Each user creates 2 posts per day.</li><li>Each post contains approximately 2 KB of text and metadata.</li></ul><p>First, calculate the number of posts created daily.</p><pre>Daily Posts = DAU × Posts Per User</pre><pre>Daily Posts = 100,000 × 2</pre><pre>Daily Posts = 200,000</pre><p>Your application creates 200,000 posts every day.</p><p>Now calculate daily storage.</p><pre>Daily Storage = Daily Posts × Average Post Size</pre><pre>Daily Storage = 200,000 × 2 KB</pre><pre>Daily Storage = 400,000 KB</pre><p>Approximately:</p><pre>Daily Storage = 400 MB</pre><p>Now calculate yearly storage.</p><pre>Yearly Storage = Daily Storage × 365</pre><pre>Yearly Storage = 400 MB × 365</pre><pre>Yearly Storage = 146,000 MB</pre><pre>Yearly Storage ≈ 146 GB</pre><p>&lt;text&gt; &lt;/text&gt;</p><p>&lt;text weight=”semibold”&gt;Storage estimation result&lt;/text&gt;</p><p>PeriodEstimated StorageDaily400 MBMonthly (30 days)12 GBYearly146 GB3 Years438 GB</p><p>These figures represent raw post data under our assumptions. They do not include indexes, backups, replication, database overhead, or additional metadata.</p><h3>What About Images?</h3><p>Now imagine 20% of posts contain an image.</p><p>Each image has an average size of 500 KB.</p><p>First, calculate the number of images.</p><pre>Daily Posts = 200,000</pre><pre>Image Percentage = 20%</pre><pre>Daily Images = 200,000 × 0.20</pre><pre>Daily Images = 40,000</pre><p>Now calculate image storage.</p><pre>Daily Image Storage = 40,000 × 500 KB</pre><pre>Daily Image Storage = 20,000,000 KB</pre><pre>Daily Image Storage ≈ 20 GB</pre><p>Yearly image storage:</p><pre>20 GB × 365 = 7,300 GB</pre><pre>Approximately 7.3 TB per year</pre><p>Look at the difference.</p><p>Post metadata requires approximately 146 GB per year.</p><p>Images require approximately 7.3 TB per year.</p><p>This demonstrates why media storage must be considered separately from database storage.</p><p>In a production architecture, you would typically store image files in object storage such as Amazon S3 or another compatible service, while keeping their metadata and storage references in PostgreSQL.</p><h3>5. What Is Bandwidth Estimation?</h3><p>Bandwidth describes the rate at which data can be transferred across a network.</p><p>It is usually measured in:</p><ul><li>Bits per second (bps)</li><li>Kilobits per second (Kbps)</li><li>Megabits per second (Mbps)</li><li>Gigabits per second (Gbps)</li></ul><p>Why is bandwidth important?</p><p>Imagine your application serves thousands of users.</p><p>Every request transfers data between clients and servers.</p><p>For example:</p><ul><li>API responses.</li><li>Images.</li><li>Videos.</li><li>Documents.</li><li>Audio files.</li></ul><p>If your application transfers too much data, network capacity can become a bottleneck.</p><h3>Practical Bandwidth Calculation</h3><p>Suppose your application has:</p><ul><li>100,000 DAU.</li><li>50 API requests per user per day.</li><li>Average API response size of 20 KB.</li></ul><p>First, calculate total daily requests.</p><pre>Daily Requests = DAU × Requests Per User</pre><pre>Daily Requests = 100,000 × 50</pre><pre>Daily Requests = 5,000,000</pre><p>Your application receives 5 million API requests per day.</p><p>Now calculate the total response data.</p><pre>Daily Data Transfer = Daily Requests × Response Size</pre><pre>= 5,000,000 × 20 KB</pre><pre>= 100,000,000 KB</pre><pre>≈ 100 GB per day</pre><p>Now calculate average bandwidth.</p><pre>Average Data Transfer = 100 GB / 86,400 Seconds</pre><pre>≈ 1.16 MB/s</pre><p>Convert megabytes into megabits:</p><pre>1.16 × 8 = 9.28 Mbps</pre><p>So the average outbound API response traffic is approximately 9.3 Mbps.</p><p>If we assume a peak multiplier of 5:</p><pre>Peak Bandwidth = 9.3 × 5</pre><pre>≈ 46.5 Mbps</pre><p>Your estimated peak outbound API response bandwidth is approximately 46.5 Mbps.</p><p>This is not the total network capacity requirement. You must also consider uploads, images, videos, request payloads, protocol overhead, and other network traffic.</p><h3>6. Complete Practical Example: Designing a Social Media Application</h3><p>Now let’s combine everything.</p><p>Imagine a client wants to build a social media application similar to Instagram.</p><p>The expected usage is:</p><p>ParameterAssumptionRegistered Users1,000,000Daily Active Users100,000API Requests Per User Per Day50Posts Per User Per Day2Average Post Metadata Size2 KBAverage API Response Size20 KBImage Upload Percentage20%Average Image Size500 KBPeak Traffic Multiplier5</p><p>Let’s calculate the important numbers.</p><h3>Calculation 1: Daily API Requests</h3><pre>100,000 × 50</pre><pre>= 5,000,000 Requests/Day</pre><h3>Calculation 2: Average RPS</h3><pre>5,000,000 / 86,400</pre><pre>= 57.87 RPS</pre><p>Approximately 58 requests per second.</p><h3>Calculation 3: Peak RPS</h3><pre>57.87 × 5</pre><pre>= 289.35 RPS</pre><p>Approximately 290 requests per second.</p><h3>Calculation 4: Daily Post Storage</h3><pre>100,000 × 2 × 2 KB</pre><pre>= 400 MB/Day</pre><h3>Calculation 5: Daily Image Storage</h3><pre>200,000 Posts × 20% × 500 KB</pre><pre>= 20 GB/Day</pre><h3>Calculation 6: Daily API Bandwidth</h3><pre>5,000,000 × 20 KB</pre><pre>= 100 GB/Day</pre><h3>Calculation 7: Average Outbound Bandwidth</h3><pre>100 GB × 8 / 86,400</pre><pre>≈ 9.26 Mbps</pre><h3>Calculation 8: Peak Outbound Bandwidth</h3><pre>9.26 × 5</pre><pre>≈ 46.3 Mbps</pre><h3>Final Estimation Summary</h3><p>MetricEstimated ResultDaily Active Users100,000Daily API Requests5 MillionAverage RPS58Peak RPS290Daily Post Metadata400 MBDaily Image Storage20 GBYearly Post Metadata146 GBYearly Image Storage7.3 TBAverage API Bandwidth9.26 MbpsPeak API Bandwidth46.3 Mbps</p><p>&lt;text weight=”semibold”&gt;What does this tell us?&lt;/text&gt;</p><p>Even a relatively simple social media application can generate substantial storage and network requirements.</p><p>This information helps engineers plan infrastructure before the application experiences unexpected growth.</p><h3>7. How Do These Estimates Influence System Architecture?</h3><p>Calculations become useful when they influence real engineering decisions.</p><p>Let’s see how.</p><h3>A. Application Server Planning</h3><p>If your application expects approximately 290 peak requests per second, a single application server may or may not be sufficient.</p><p>It depends on:</p><ul><li>CPU and memory.</li><li>Application code efficiency.</li><li>Database query performance.</li><li>API complexity.</li><li>Average request duration.</li><li>Background processing workload.</li></ul><p>You should benchmark your actual application using load-testing tools before deciding the number of servers.</p><h3>B. Database Planning</h3><p>If your application creates millions of records every month, database design becomes important.</p><p>You may need:</p><ul><li>Proper indexing.</li><li>Query optimization.</li><li>Connection pooling.</li><li>Database replication.</li><li>Partitioning.</li><li>Archival strategies.</li></ul><h3>C. Caching Strategy</h3><p>If users frequently request the same information, Redis can reduce repeated database queries.</p><p>For example:</p><ul><li>Popular posts.</li><li>User profiles.</li><li>Product categories.</li><li>Frequently accessed configuration.</li></ul><h3>D. Object Storage</h3><p>Images and videos should generally be stored separately from relational database records.</p><p>For example:</p><pre>              USER<br>               |<br>               v<br>          BACKEND API<br>               |<br>         +-----+-----+<br>         |           |<br>         v           v<br>      DATABASE    OBJECT STORAGE<br>     (Metadata)   (Images/Videos)</pre><h3>E. CDN Planning</h3><p>If your application serves images and videos to users in different geographical locations, a CDN can help deliver content efficiently.</p><p>This reduces repeated requests to the origin server and can improve content delivery performance.</p><h3>F. Background Processing</h3><p>Some operations do not need to happen during the user’s request.</p><p>For example:</p><ul><li>Image resizing.</li><li>Video processing.</li><li>Sending notifications.</li><li>Generating reports.</li></ul><p>These tasks can be processed asynchronously using background workers and message queues.</p><p>The key idea is that workload estimation helps you identify where different architectural components may be useful.</p><h3>8. Understanding Concurrent Requests</h3><p>There is another important concept worth understanding: concurrency.</p><p>Suppose your application receives 300 requests per second.</p><p>Does that mean exactly 300 requests are being processed at the same moment?</p><p>Not necessarily.</p><p>The number of requests simultaneously in progress depends on how long each request takes.</p><p>A useful approximation comes from Little’s Law:</p><p><strong>Concurrent Requests ≈ Request Rate × Average Response Time</strong></p><p>Suppose:</p><ul><li>Request Rate = 300 requests/second.</li><li>Average Response Time = 200 milliseconds.</li><li>200 milliseconds = 0.2 seconds.</li></ul><p>Then:</p><pre>Concurrent Requests = 300 × 0.2</pre><pre>= 60</pre><p>Approximately 60 requests would be in progress simultaneously under steady-state conditions.</p><p>This is different from the number of users currently browsing the application.</p><p>Understanding this difference is important when planning application workers, connection pools, and infrastructure capacity.</p><h3>9. Common Mistakes in Back-of-the-Envelope Estimation</h3><p>Even experienced engineers can make estimation mistakes.</p><p>Here are some common ones.</p><h3>Mistake 1: Confusing Registered Users with DAU</h3><p>One million registered users does not mean one million daily active users.</p><p>Always estimate active usage separately.</p><h3>Mistake 2: Using Average Traffic Only</h3><p>Average traffic can hide traffic spikes.</p><p>Always consider peak traffic, especially for applications with scheduled events or sudden demand.</p><h3>Mistake 3: Ignoring Media Storage</h3><p>Images, audio, and videos can consume significantly more storage than text and metadata.</p><p>Estimate them separately.</p><h3>Mistake 4: Forgetting Database Overhead</h3><p>Raw record size is not the same as actual database storage consumption.</p><p>Indexes, replication, backups, and internal database overhead also require capacity.</p><h3>Mistake 5: Assuming Every API Response Has the Same Size</h3><p>A login response may contain a few hundred bytes.</p><p>A product listing response may contain several kilobytes.</p><p>A report download may contain several megabytes.</p><p>Use representative response sizes or separate request categories.</p><h3>Mistake 6: Overestimating or Underestimating Peak Traffic</h3><p>A peak multiplier is only a starting assumption.</p><p>Use actual traffic data and load testing whenever possible.</p><h3>Mistake 7: Buying Infrastructure Before Measuring Performance</h3><p>Never assume a particular server configuration can handle a specific RPS without testing.</p><p>Benchmark your real application.</p><h3>10. Useful Tools for Validating Your Estimates</h3><p>Mathematical estimation is a starting point. You should validate your assumptions through practical testing.</p><p>Here are some useful tools.</p><p><strong>1. Apache JMeter</strong></p><p>Useful for simulating multiple users and generating HTTP traffic.</p><p><strong>2. Locust</strong></p><p>A Python-based load-testing tool that allows you to write realistic user behavior.</p><p><strong>3. k6</strong></p><p>Useful for performance testing APIs and monitoring response times under different workloads.</p><p><strong>4. Prometheus</strong></p><p>Useful for collecting infrastructure and application metrics.</p><p><strong>5. Grafana</strong></p><p>Useful for visualizing request rates, latency, CPU usage, memory, and other performance metrics.</p><p><strong>6. PostgreSQL Monitoring</strong></p><p>Useful for examining query performance, connections, locks, and database activity.</p><p>For a Django backend, a practical workflow could be:</p><ol><li>Estimate expected DAU and API requests.</li><li>Calculate average and peak RPS.</li><li>Estimate storage and bandwidth.</li><li>Build the application.</li><li>Test it using Locust or k6.</li><li>Monitor CPU, memory, database performance, and latency.</li><li>Adjust infrastructure based on measured results.</li></ol><h3>11. A Quick Formula Cheat Sheet</h3><p>Keep these formulas handy when designing a system.</p><p>MetricFormulaSeconds Per Day24 × 60 × 60 = 86,400Daily RequestsDAU × Requests Per UserAverage RPSDaily Requests / 86,400Peak RPSAverage RPS × Peak MultiplierDaily StorageDaily Records × Average Record SizeYearly StorageDaily Storage × 365Daily BandwidthDaily Requests × Average Response SizeAverage Bandwidth (Mbps)Daily Data (MB) × 8 / 86,400Peak BandwidthAverage Bandwidth × Peak MultiplierConcurrent RequestsRPS × Average Response Time (seconds)</p><p>Remember that these are estimation formulas. Actual infrastructure requirements depend on workload distribution, data retention, caching, request mix, replication, and application performance.</p><h3>Conclusion: Think in Numbers Before Designing Systems</h3><p>Back-of-the-Envelope Estimation is one of the most practical skills in System Design.</p><p>It helps engineers move beyond assumptions and make informed architectural decisions.</p><p>Before building an application for thousands or millions of users, try to understand:</p><ul><li>How many users will be active?</li><li>How many requests will they generate?</li><li>How much data will the system store?</li><li>How much bandwidth will the application consume?</li><li>What will happen during peak traffic?</li></ul><p>You don’t need perfect numbers.</p><p>You need reasonable assumptions and the ability to explain how you arrived at your estimates.</p><p>As you become more experienced, these calculations will help you make better decisions about databases, caching, load balancing, object storage, and infrastructure.</p><p><strong>Remember:</strong></p><p><em>Good System Design doesn’t start with choosing servers or technologies. It starts with understanding the workload those systems must handle.</em></p><h3>What’s Next?</h3><p><strong>Article 04 of 69: Latency vs Throughput — Understanding the Numbers That Define System Performance.</strong></p><p>In the next article, we’ll explore why a system can process thousands of requests per second and still feel slow to users.</p><p>We’ll understand latency, throughput, response time, and the relationship between them using practical backend examples.</p><p><em>If you found this article useful, follow this 69-article System Design learning series. Let’s learn how to design systems that are scalable, reliable, and production-ready.</em></p><p>#SystemDesign #BackendDevelopment #SoftwareEngineering #Scalability #PerformanceEngineering #DistributedSystems #Python #Django #DatabaseDesign</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a7d1651a904" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional vs Non-Functional Requirements: Understanding What to Build and How Well It Should Work]]></title>
            <link>https://medium.com/@sagorrobidush/functional-vs-non-functional-requirements-understanding-what-to-build-and-how-well-it-should-work-6356d5532e37?source=rss-103bcad913c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6356d5532e37</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Shagor Robidush]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 02:31:01 GMT</pubDate>
            <atom:updated>2026-11-26T08:47:30.039Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An Easy-to-Understand Guide to Software Requirements with Real-World Examples</em></p><figure><img alt="Illustration comparing functional and non-functional software requirements, showing application features such as user authentication, payments, and product search alongside performance, scalability, security, and availability concepts." src="https://cdn-images-1.medium.com/max/1024/0*zfBVyvtzoPMlZzdv" /><figcaption>Functional and Non-Functional requirments</figcaption></figure><h3>Introduction: Before Writing Code, Ask the Right Questions</h3><p>Imagine a client approaches you with an idea:</p><p>“I want to build an e-commerce application where users can register, browse products, place orders, and make payments.”</p><p>As a Backend Developer, what would you do first?</p><p>Would you immediately create a Django project, configure PostgreSQL, and start developing APIs?</p><p>That might seem like the fastest approach.</p><p>But wait.</p><p>You still don’t know:</p><ul><li>How many users will use the application?</li><li>How many requests should the system handle simultaneously?</li><li>How quickly should APIs respond?</li><li>What happens if the payment service becomes unavailable?</li><li>Should users receive order confirmation emails?</li><li>How secure should customer information be?</li><li>How much downtime is acceptable?</li></ul><p>These questions are not minor technical details. They define what you are actually expected to build.</p><p>This is where <strong>Software Requirements</strong> become important.</p><p>Before designing a software architecture, engineers need to understand two fundamental categories of requirements:</p><ol><li>Functional Requirements</li><li>Non-Functional Requirements</li></ol><p>Both are essential for building successful software systems.</p><p>Let’s understand them through practical examples.</p><h3>1. What Are Software Requirements?</h3><p>Software requirements describe what a software system must do and the conditions under which it must operate.</p><p>They define the expectations of users, clients, businesses, and technical stakeholders.</p><p>In simple terms:</p><p><strong>Software requirements explain what needs to be built and how well the finished system should perform.</strong></p><p>For example, consider a food delivery application.</p><p>A customer expects to:</p><ul><li>Create an account.</li><li>Search for nearby restaurants.</li><li>View restaurant menus.</li><li>Place food orders.</li><li>Make payments.</li><li>Track deliveries.</li></ul><p>These describe the system’s expected functionality.</p><p>However, the customer also expects the application to:</p><ul><li>Load quickly.</li><li>Protect personal information.</li><li>Remain available.</li><li>Handle many users simultaneously.</li><li>Recover from unexpected failures.</li></ul><p>These describe the system’s quality expectations and operational constraints.</p><p>This leads us to the two major categories.</p><figure><img alt="Animated diagram comparing functional requirements such as user workflows and system actions against non-functional requirements including speed, security, and scalability." src="https://cdn-images-1.medium.com/max/640/1*DLOmdjBqcy0nkEO8rZV-rg.gif" /><figcaption><em>Functional requirements define what a system does; non-functional requirements determine how fast, securely, and reliably it delivers.</em></figcaption></figure><h3>2. What Are Functional Requirements?</h3><p>Functional Requirements define the specific features, operations, and behaviors a software application must provide.</p><p>They describe what the system should do in response to user actions or particular conditions.</p><p>In simpler words:</p><p><strong>Functional Requirements describe the actual functionality of an application.</strong></p><p>Let’s consider an online shopping application.</p><p>A user should be able to:</p><ol><li>Register an account.</li><li>Log in using email and password.</li><li>Browse available products.</li><li>Search for products.</li><li>Add products to a shopping cart.</li><li>Place an order.</li><li>Make payments.</li><li>View order history.</li><li>Cancel eligible orders.</li><li>Receive order confirmation.</li></ol><p>Every item describes something the application must do.</p><p>These are Functional Requirements.</p><h3>Real-World Example: User Registration</h3><p>Suppose you are developing a registration feature using Django REST Framework.</p><p>The expected functionality might be:</p><ul><li>The user provides their name, email, and password.</li><li>The system validates the submitted information.</li><li>The system checks whether the email already exists.</li><li>The password is securely hashed.</li><li>A new user account is created.</li><li>The API returns a successful response.</li></ul><p>A simple workflow:</p><pre>      USER<br>       |<br>       v<br>Registration Form<br>       |<br>       v<br>   POST /register<br>       |<br>       v<br> Validate Input<br>       |<br>       v<br>Check Email Exists?<br>       |<br>   +---+---+<br>   |       |<br>  YES      NO<br>   |       |<br>   v       v<br> Error   Hash Password<br>           |<br>           v<br>      Create Account<br>           |<br>           v<br>      Success Response</pre><p>The registration process describes the expected behavior of the system.</p><p>Therefore, it is a Functional Requirement.</p><h3>More Examples of Functional Requirements</h3><p>ApplicationFunctional RequirementBanking AppTransfer money between accountsE-commerceAdd products to shopping cartSocial MediaCreate and publish postsChat ApplicationSend and receive messagesFood DeliveryTrack food ordersLearning PlatformGenerate quizzesHealthcare AppRecord daily health informationVideo PlatformUpload and play videos</p><p>The important thing to remember is that functional requirements describe specific capabilities.</p><h3>3. What Are Non-Functional Requirements?</h3><p>Non-Functional Requirements describe the quality attributes, performance expectations, and operational constraints of a software system.</p><p>They explain how well the system should perform its functions.</p><p>In simple words:</p><p><strong>Functional Requirements describe what a system does. Non-Functional Requirements describe how well it does it.</strong></p><p>Let’s return to our e-commerce application.</p><p>We already know users should be able to browse products and place orders.</p><p>But now consider these expectations:</p><ul><li>Product pages should load within 2 seconds under the agreed test conditions.</li><li>The system should support 10,000 concurrent users.</li><li>The application should maintain 99.9% monthly availability.</li><li>Customer passwords must be stored securely.</li><li>The system should recover from server failures.</li><li>Database queries should meet defined performance targets.</li></ul><p>These are examples of Non-Functional Requirements.</p><p>They don’t introduce new business features.</p><p>Instead, they define the quality and constraints of the system.</p><h3>Real-World Example: Product Listing API</h3><p>Imagine your Django application provides this API:</p><pre>GET /api/v1/products/</pre><p>The API returns a list of products.</p><p>From a functional perspective, the requirement is simple:</p><p>“The API must return available products.”</p><p>But from a non-functional perspective, you may have additional expectations:</p><ul><li>Response time: 200 milliseconds at the 95th percentile under a specified workload.</li><li>Concurrent users: Support 10,000 concurrent users.</li><li>Availability: Target 99.9% monthly availability.</li><li>Security: Only authorized users can access restricted product information.</li><li>Scalability: Support increasing traffic through horizontal scaling.</li></ul><p>Now you have a much clearer picture of what a production-ready API should achieve.</p><h3>Important Categories of Non-Functional Requirements</h3><p>Let’s explore the most important quality attributes.</p><p><strong>1. Performance</strong></p><p>Performance describes how efficiently a system responds to requests and processes workloads.</p><p>Common measurements include:</p><ul><li>Response Time</li><li>Latency</li><li>Throughput</li><li>CPU Usage</li><li>Memory Usage</li></ul><p>Example:</p><p>A product search API should return results within 300 milliseconds at the 95th percentile under the defined workload.</p><p><strong>2. Scalability</strong></p><p>Scalability describes how well a system handles increasing users, requests, and data.</p><p>Example:</p><p>The application should support growth from 1,000 to 100,000 daily active users without requiring a complete architectural redesign.</p><p><strong>3. Availability</strong></p><p>Availability describes how often a system remains operational and accessible.</p><p>Example:</p><p>The payment application should target 99.99% monthly availability.</p><p><strong>4. Security</strong></p><p>Security ensures that systems and information are protected against unauthorized access and attacks.</p><p>Example:</p><ul><li>Passwords must be securely hashed.</li><li>Sensitive information must be encrypted in transit.</li><li>APIs must enforce authorization.</li><li>Requests must be validated.</li></ul><p><strong>5. Reliability</strong></p><p>Reliability describes the ability of a system to perform correctly over time, including when failures occur.</p><p>Example:</p><p>If one application server fails, healthy servers should continue handling incoming requests.</p><p><strong>6. Maintainability</strong></p><p>Maintainability describes how easily developers can understand, modify, test, and extend a system.</p><p>Example:</p><p>The backend should follow modular architecture and maintain consistent API contracts.</p><p><strong>7. Usability</strong></p><p>Usability describes how easily users can understand and interact with the application.</p><p>Example:</p><p>A new user should be able to complete the registration process without unnecessary steps.</p><p><strong>8. Compatibility</strong></p><p>Compatibility describes whether the system works with required platforms, devices, browsers, and external services.</p><p>Example:</p><p>The application should support modern desktop and mobile browsers.</p><p><strong>9. Recoverability</strong></p><p>Recoverability describes how quickly and effectively a system can recover after a failure.</p><p>Example:</p><p>Critical application data should be recoverable through regular backups and tested recovery procedures.</p><h3>4. Functional vs Non-Functional Requirements: What’s the Difference?</h3><p>Now let’s compare them directly.</p><p>ComparisonFunctional RequirementsNon-Functional RequirementsMain QuestionWhat should the system do?How well should it work?FocusFeatures and behaviorQuality attributes and constraintsDescribesSystem functionalitySystem performance and qualityExamplesLogin, registration, paymentsSecurity, performance, availabilityTestingFunctional testingPerformance, security, reliability testingImplementationBusiness logic and application featuresArchitecture, infrastructure, and engineering practices</p><p>Consider a banking application.</p><p><strong>Functional Requirement:</strong></p><p>Users must be able to transfer money between bank accounts.</p><p><strong>Non-Functional Requirements:</strong></p><ul><li>Transfers must enforce authorization.</li><li>Financial transactions must preserve data integrity.</li><li>The application must meet its defined availability target.</li><li>Transaction processing must meet specified latency requirements.</li></ul><p>Both categories are necessary.</p><p>A banking application that can transfer money but cannot protect financial data is not acceptable.</p><p>Similarly, an application that is extremely secure but cannot perform money transfers does not satisfy its primary purpose.</p><p><strong>A successful system needs both functionality and quality.</strong></p><h3>5. Practical Example: Designing an E-Commerce Application</h3><p>Let’s combine everything into one practical example.</p><p>Imagine a client wants to build an e-commerce platform similar to Amazon.</p><p>Before development begins, you need to identify the system’s requirements.</p><h3>A. Functional Requirements</h3><p>The application must support:</p><p><strong>User Management</strong></p><ul><li>User registration.</li><li>User login and logout.</li><li>Profile management.</li><li>Password reset.</li></ul><p><strong>Product Management</strong></p><ul><li>Browse products.</li><li>Search products.</li><li>Filter by category and price.</li><li>View product details.</li></ul><p><strong>Shopping Cart</strong></p><ul><li>Add products.</li><li>Remove products.</li><li>Update product quantities.</li><li>Calculate total prices.</li></ul><p><strong>Order Management</strong></p><ul><li>Place orders.</li><li>View order history.</li><li>Cancel eligible orders.</li><li>Track order status.</li></ul><p><strong>Payment Management</strong></p><ul><li>Process payments.</li><li>Verify payment status.</li><li>Handle failed payments.</li><li>Generate transaction records.</li></ul><p><strong>Notifications</strong></p><ul><li>Send order confirmation emails.</li><li>Notify users about order updates.</li><li>Send payment confirmation messages.</li></ul><h3>B. Non-Functional Requirements</h3><p>Now define how well the application should operate.</p><p>RequirementExample TargetPerformance95% of product API requests under 300 msAvailability99.9% monthly availabilityScalabilitySupport 10,000 concurrent usersSecurityEncrypted communication and secure authenticationReliabilityNo confirmed order should be lostRecoverabilityRestore critical service within the agreed recovery targetMaintainabilityModular and documented backend architecture</p><p>These numbers are illustrative targets, not universal standards. Actual targets should be agreed upon with stakeholders and validated against the expected workload and budget.</p><h3>C. How Do These Requirements Influence Architecture?</h3><p>This is where System Design becomes interesting.</p><p>Requirements directly influence technical decisions.</p><p>For example:</p><p>RequirementPossible Technical DecisionHigh API trafficLoad BalancerFast product retrievalRedis CachingLarge product catalogDatabase IndexingBackground email deliveryCelery + Redis or RabbitMQHigh availabilityMultiple Application InstancesLarge image storageS3-Compatible Object StorageSecure authenticationJWT or Session-Based AuthenticationPerformance monitoringMetrics and Distributed Tracing</p><p>Notice something important?</p><p>We haven’t started writing the application yet.</p><p>But by understanding the requirements, we already have a better idea of what architecture might be appropriate.</p><p>That is the real value of requirements analysis.</p><h3>6. How to Write Good Functional Requirements</h3><p>A functional requirement should be clear, specific, and testable.</p><p>Avoid writing requirements that are too general.</p><p>For example:</p><p><strong>Bad Requirement:</strong></p><p>“The application should support user management.”</p><p>This doesn’t explain what user management actually includes.</p><p><strong>Better Requirement:</strong></p><p>“Users must be able to register using a unique email address, log in with valid credentials, update their profile information, and reset forgotten passwords.”</p><p>This is much clearer.</p><h3>Use User Stories</h3><p>A common way to document functional requirements is through User Stories.</p><p>A User Story follows this structure:</p><p>“As a [user], I want [functionality], so that [benefit].”</p><p>Examples:</p><p><strong>User Registration</strong></p><p>“As a new user, I want to create an account using my email address so that I can access the platform.”</p><p><strong>Product Search</strong></p><p>“As a customer, I want to search for products by name so that I can find the items I need.”</p><p><strong>Order Tracking</strong></p><p>“As a customer, I want to track my order status so that I know when my package will arrive.”</p><h3>Add Acceptance Criteria</h3><p>Acceptance Criteria define the conditions that must be satisfied for a feature to be considered complete.</p><p>Example:</p><p><strong>Feature: User Registration</strong></p><p>Acceptance Criteria:</p><ol><li>The user must provide a valid email address.</li><li>The email address must be unique.</li><li>Password requirements must be validated.</li><li>Passwords must never be stored in plain text.</li><li>Successful registration must create a user account.</li><li>Invalid input must return an appropriate error response.</li></ol><p>These conditions make development and testing much easier.</p><h3>7. How to Write Good Non-Functional Requirements</h3><p>One of the biggest mistakes in software development is writing vague non-functional requirements.</p><p>For example:</p><ul><li>The application should be fast.</li><li>The system should be scalable.</li><li>The application should be secure.</li><li>The platform should be highly available.</li></ul><p>These statements sound reasonable, but they are difficult to measure.</p><p>What does fast mean?</p><p>How many users should the application support?</p><p>How much downtime is acceptable?</p><p>What level of security is required?</p><p>Good non-functional requirements should be measurable whenever possible.</p><h3>Example: Turning Vague Requirements into Measurable Requirements</h3><p>Vague RequirementBetter RequirementThe API should be fast95% of requests should complete within 300 ms under the defined workloadThe system should be scalableSupport 10,000 concurrent users under the agreed test conditionsThe system should be availableTarget 99.9% monthly availabilityThe system should be secureEnforce authorization on every protected endpointThe system should recover quicklyRestore critical service within a defined recovery time objective</p><h3>Understand Two Important Recovery Terms</h3><p>When defining reliability requirements, two useful measurements are:</p><p><strong>RTO (Recovery Time Objective)</strong></p><p>The maximum acceptable time to restore a service after a disruption.</p><p>Example:</p><p>A business may require its payment service to recover within 30 minutes.</p><p><strong>RPO (Recovery Point Objective)</strong></p><p>The maximum acceptable amount of data loss measured in time.</p><p>Example:</p><p>A system with a 5-minute RPO aims to limit recoverable data loss to the equivalent of five minutes of transactions.</p><p>These targets help engineering teams plan backups, replication, and disaster recovery.</p><h3>8. Common Mistakes Developers Make</h3><p>Even experienced developers can make mistakes when defining software requirements.</p><p>Here are some common ones.</p><p><strong>Mistake 1: Starting Development Without Understanding Requirements</strong></p><p>Developers sometimes begin writing code immediately after receiving a short project description.</p><p>The result can be missing features, unnecessary complexity, and expensive changes later.</p><p><strong>Better approach:</strong> Clarify business goals, user expectations, and technical constraints before implementation.</p><p><strong>Mistake 2: Confusing Functional and Non-Functional Requirements</strong></p><p>“Users can log in” is functional.</p><p>“Login requests must complete within 500 milliseconds under the specified workload” is non-functional.</p><p>Understand the difference before documenting requirements.</p><p><strong>Mistake 3: Writing Vague Performance Requirements</strong></p><p>“Make the API fast” is not a useful engineering target.</p><p>Define response-time percentiles, workload assumptions, and measurement conditions.</p><p><strong>Mistake 4: Ignoring Security</strong></p><p>Security should not be added as an afterthought.</p><p>Authentication, authorization, validation, encryption, and access control should be considered during system planning.</p><p><strong>Mistake 5: Overengineering Too Early</strong></p><p>Not every application needs Microservices, Kafka, Kubernetes, or multiple databases.</p><p>Choose architecture based on actual requirements and expected growth.</p><p><strong>Mistake 6: Ignoring Business Priorities</strong></p><p>A system can be technically impressive but still fail to solve the client’s actual problem.</p><p>Always understand which requirements are essential and which are optional.</p><h3>9. A Practical Requirements Checklist for Backend Developers</h3><p>Before starting a new backend project, consider asking the following questions.</p><h3>Functional Requirements</h3><ul><li>Who are the users of the application?</li><li>What features should each user have access to?</li><li>What actions can users perform?</li><li>What data should the application store?</li><li>What APIs are required?</li><li>Which external services must be integrated?</li><li>What happens when an operation fails?</li></ul><h3>Non-Functional Requirements</h3><ul><li>How many users are expected?</li><li>What is the expected request volume?</li><li>What are the response-time targets?</li><li>What availability level is required?</li><li>What security requirements apply?</li><li>How much data will the system store?</li><li>How quickly must the system recover from failures?</li><li>What is the infrastructure budget?</li></ul><p>These questions provide a useful starting point for requirements gathering.</p><h3>10. Final Thoughts: Good System Design Starts Before Coding</h3><p>One of the biggest lessons in software engineering is that building the right system begins with understanding the right problem.</p><p>Functional Requirements tell us what the application must do.</p><p>Non-Functional Requirements tell us how well the application must perform.</p><p>Both influence architecture, technology selection, infrastructure planning, testing, and deployment.</p><p>As a Backend Developer, don’t just ask:</p><p>“Which API should I build?”</p><p>Also ask:</p><p>“How many users will use this API?”</p><p>“What happens when the database becomes unavailable?”</p><p>“How quickly should it respond?”</p><p>“How will it handle increasing traffic?”</p><p>“How will sensitive data remain protected?”</p><p>These questions will gradually help you develop the mindset of a System Design Engineer.</p><p>Remember:</p><p><strong>A system is not successful simply because its features work. It is successful when those features work reliably, securely, and efficiently under real-world conditions.</strong></p><p>Start with requirements. Understand the problem. Then design the solution.</p><h3>What’s Next?</h3><p><strong>Article 03 of 69: Back-of-the-Envelope Estimation — DAU, QPS, Storage, and Bandwidth.</strong></p><p>Before designing a scalable system, engineers need to estimate how much traffic, storage, and network capacity the application will require.</p><p>In the next article, we’ll learn how to make these calculations using simple mathematics and practical real-world examples.</p><p><em>If you found this article useful, follow this System Design learning series. We are exploring every topic step by step, from fundamental concepts to advanced distributed systems.</em></p><p>#SystemDesign #SoftwareEngineering #BackendDevelopment #SoftwareRequirements #FunctionalRequirements #NonFunctionalRequirements #SoftwareArchitecture #Django #Python</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6356d5532e37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is System Design, and Why Should You Learn It?]]></title>
            <link>https://medium.com/@sagorrobidush/what-is-system-design-and-why-should-you-learn-it-58b30ae54430?source=rss-103bcad913c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/58b30ae54430</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Shagor Robidush]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 12:16:01 GMT</pubDate>
            <atom:updated>2026-11-26T08:52:31.071Z</atom:updated>
            <content:encoded><![CDATA[<p><em>From Writing Your First API to Building Systems That Scale to Millions of Users.</em></p><figure><img alt="System Design and scalable software architecture illustration featuring users, load balancers, multiple application servers, database, Redis cache, message queues, CDN, and key software engineering concepts including scalability, performance, reliability, security, and maintainability." src="https://cdn-images-1.medium.com/max/1024/1*KFcMsr1JEbOQirSjUSSW8A.png" /><figcaption>What is system design, and why should you learn it? From writing code to building scalable systems.</figcaption></figure><h3>Introduction: When Your Application Suddenly Becomes Popular</h3><p>Imagine you have spent several weeks building an e-commerce application using Python, Django, and PostgreSQL.</p><p>Your application has everything:</p><ul><li>User registration and authentication</li><li>Product management</li><li>Shopping carts</li><li>Order processing</li><li>Payment integration</li><li>Email notifications</li></ul><p>You deploy it to a production server.</p><p>Initially, everything works perfectly.</p><p>Your application handles 100 users without any problems. API responses are fast, database queries are performing well, and users are happy.</p><p>Then something unexpected happens.</p><p>A popular influencer shares your website. Within a few minutes, thousands of people start visiting your application.</p><p>Suddenly:</p><ul><li>Your APIs become slow.</li><li>Database connections increase dramatically.</li><li>Server CPU usage reaches 100%.</li><li>Some requests start timing out.</li><li>Users experience failed transactions.</li><li>Your application becomes temporarily unavailable.</li></ul><p>You check your code. Everything looks correct.</p><p>So, what went wrong?</p><p><strong>Your application was built to work, but it was not designed to handle growth.</strong></p><p>This is one of the most important problems that System Design helps engineers solve.</p><p>System Design teaches us how to build software systems that continue working efficiently as users, data, traffic, and business requirements increase.</p><p>But to understand why it matters, we first need to understand what System Design actually means.</p><h3>1. What Exactly Is System Design?</h3><p>System Design is the process of defining the architecture, components, technologies, communication patterns, and data flow of a software application.</p><p>In simpler words:</p><p><strong>System Design is about deciding how different parts of an application should work together to solve a problem efficiently.</strong></p><p>It involves answering questions such as:</p><ul><li>How will users communicate with the application?</li><li>Where will application data be stored?</li><li>How will different services communicate?</li><li>How will the application handle thousands of requests?</li><li>What happens when a server crashes?</li><li>How can we prevent data loss?</li><li>How will the system grow in the future?</li></ul><p>System Design is not limited to choosing a programming language or framework.</p><p>You might use Python, Django, FastAPI, PostgreSQL, and Redis to build an application, but choosing these technologies is only one part of the engineering process.</p><p>You must also understand how to organize them into an architecture that meets the application’s requirements.</p><h3>A Simple Example</h3><p>Consider a basic web application.</p><p>When a user opens your website and logs in, several components work together.</p><ol><li>The frontend collects the user’s email and password.</li><li>The frontend sends an HTTP request to the backend.</li><li>The backend receives and validates the request.</li><li>The backend communicates with the database.</li><li>The database returns the user’s information.</li><li>The backend verifies the password.</li><li>The backend generates an authentication token.</li><li>The frontend receives the response.</li></ol><p>A simplified architecture looks like this:</p><pre>        USER<br>         |<br>         v<br>      FRONTEND<br>         |<br>         | HTTP Request<br>         v<br>      BACKEND API<br>         |<br>         v<br>    AUTHENTICATION<br>         |<br>         v<br>      DATABASE<br>         |<br>         v<br>    VALIDATION<br>         |<br>         v<br>    ACCESS TOKEN<br>         |<br>         v<br>      RESPONSE<br>         |<br>         v<br>        USER</pre><p>This is a simple example of how components communicate within a software system.</p><p>However, real-world System Design goes much further.</p><p>You must consider what happens when thousands of users perform these operations simultaneously.</p><p>That is where architectural decisions become important.</p><figure><img alt="A high-level system design architecture showing clients, load balancer, application servers, database, and cache." src="https://cdn-images-1.medium.com/max/1024/1*xGz63l3L_6RMbWmaWcpKEA.jpeg" /><figcaption>The full request journey in a high-level design. A typical request goes Client → CDN → Load Balancer → App Server → Cache → Database → Response.</figcaption></figure><figure><img alt="Animated full system design architecture diagram that starts with functional and non-functional requirements and expands into client applications, API gateway, load balancer, microservices, caching, message queues, databases, security, and monitoring with animated data flow." src="https://cdn-images-1.medium.com/max/640/1*Xf0pD_w20HbZ3hPn0aXWJg.gif" /><figcaption>Which layer of a system design do you find hardest to align with non-functional requirements — caching and queues, data storage, or security and observability?</figcaption></figure><h3>2. Understand System Design Through a Real-Life Example</h3><p>Let’s understand System Design using something familiar: a restaurant.</p><p>Imagine you own a small restaurant.</p><p>Initially, you serve around 20 customers per day.</p><p>Your restaurant has:</p><ul><li>One waiter</li><li>One chef</li><li>One cashier</li><li>One kitchen</li><li>A simple order notebook</li></ul><p>Everything works perfectly.</p><p>The waiter takes orders, the chef prepares food, and the cashier handles payments.</p><p>Now imagine your restaurant suddenly becomes popular.</p><p>Instead of 20 customers, you receive 2,000 customers every day.</p><p>What happens?</p><p>One waiter cannot take every order.</p><p>One chef cannot prepare every meal.</p><p>One cashier cannot handle every payment.</p><p>The entire operation becomes slow.</p><p>How would you solve this problem?</p><p>You might:</p><ul><li>Hire additional waiters.</li><li>Hire more chefs.</li><li>Organize multiple kitchen stations.</li><li>Introduce a digital order management system.</li><li>Separate payment processing.</li><li>Create a queue for pending orders.</li></ul><p>Now your restaurant can serve more customers efficiently.</p><p>Software systems face exactly the same challenges.</p><p>RestaurantSoftware SystemCustomersUsersWaitersAPI Gateway / Request HandlingKitchenBackend ServicesOrder NotebookDatabaseOrder QueueMessage QueueMultiple ChefsMultiple WorkersMultiple Kitchen StationsMultiple Servers</p><p>The important lesson is this:</p><p>When the number of customers increases, you cannot simply ask one person to work faster.</p><p>You need to improve the entire system.</p><p><strong>System Design is the process of making those architectural decisions in software engineering.</strong></p><h3>3. Why Is System Design Important?</h3><p>You might be thinking:</p><p>“I already know programming. I can build APIs, connect databases, and deploy applications. Why should I learn System Design?”</p><p>Because building an application and designing a production-ready system are two different challenges.</p><p>Let’s explore five important reasons.</p><h3>3.1 Scalability: What Happens When Your Users Increase?</h3><p>Imagine you have built a Django application that handles 500 users per day.</p><p>After six months, your application becomes popular, and the number of users increases to 500,000.</p><p>Can your existing infrastructure handle this growth?</p><p>This is where scalability becomes important.</p><p><strong>Scalability is the ability of a system to handle increasing workloads by adding resources or improving its architecture.</strong></p><p>There are two common approaches.</p><p><strong>Vertical Scaling</strong></p><p>Vertical scaling means increasing the resources of an existing server.</p><p>For example:</p><pre>Before:<br><br>1 Server<br>2 CPU<br>4 GB RAM<br>       |<br>       v<br>After:<br>1 Server<br>8 CPU<br>32 GB RAM<br></pre><p>You improve the capacity of the same server.</p><p>Advantages:</p><ul><li>Simple to implement.</li><li>Requires fewer infrastructure changes.</li><li>Useful for smaller applications.</li></ul><p>Disadvantages:</p><ul><li>Hardware capacity has limits.</li><li>Larger servers can become expensive.</li><li>A single server can remain a single point of failure.</li></ul><p><strong>Horizontal Scaling</strong></p><p>Horizontal scaling means adding more servers and distributing the workload between them.</p><pre>USERS<br>               |<br>               v<br>         LOAD BALANCER<br>               |<br>        +------+------+<br>        |      |      |<br>        v      v      v<br>      APP 1  APP 2  APP 3<br>        |      |      |<br>        +------+------+<br>               |<br>               v<br>            DATABASE</pre><p>Instead of depending on one powerful server, multiple servers share incoming requests.</p><p>Advantages:</p><ul><li>Supports increasing traffic.</li><li>Provides better infrastructure flexibility.</li><li>Can improve availability when combined with redundancy.</li></ul><p>Disadvantages:</p><ul><li>Requires more infrastructure management.</li><li>Introduces distributed system complexity.</li><li>Requires careful session and data management.</li></ul><p><strong>Real-life example:</strong> Large e-commerce platforms use distributed infrastructure to handle traffic during major shopping events.</p><figure><img alt="An entity relationship diagram illustrating the relationship between users, posts, and comments in a database" src="https://cdn-images-1.medium.com/max/1024/1*fGgoG880ht9OVVGTDPCawg.jpeg" /><figcaption>How a request moves through a scalable system: Load Balancer → API Gateway → services → cache, database, and message queue, with observability watching everything</figcaption></figure><h3>3.2 Performance: How Fast Should Your Application Be?</h3><p>Imagine two applications.</p><p>Application A takes 5 seconds to return an API response.</p><p>Application B takes 200 milliseconds.</p><p>Which application would you prefer?</p><p>Most users prefer the faster application.</p><p>Performance is an important part of System Design because slow applications create poor user experiences and can waste infrastructure resources.</p><p>Some common performance optimization techniques include:</p><ul><li>Database Indexing</li><li>Query Optimization</li><li>Redis Caching</li><li>Connection Pooling</li><li>Asynchronous Processing</li><li>Load Balancing</li><li>CDN</li></ul><p>For example, consider a product listing API.</p><p>Without caching:</p><pre>                      User Request<br>                           |<br>                           v<br>                      Backend API<br>                           |<br>                           v<br>                      Database Query<br>                           |<br>                           v<br>                      Return Products</pre><p>Every request executes a database query.</p><p>With caching:</p><pre>              User Request<br>                   |<br>                   v<br>              Backend API<br>                   |<br>                   v<br>                 Redis<br>                   |<br>                   +---- Cache Hit ----&gt; Return Data<br>                   |<br>                   +---- Cache Miss ---&gt; Database<br>                                            |<br>                                            v<br>                                       Save to Redis<br>                                            |<br>                                            v<br>                                       Return Data</pre><p>Frequently requested product information can be retrieved from Redis instead of repeatedly querying the database.</p><p>This can significantly reduce database workload and improve response times.</p><figure><img alt="An entity relationship diagram illustrating the relationship between users, posts, and comments in a database" src="https://cdn-images-1.medium.com/max/1024/1*d7dRec5-x5G8coSjfF1s4Q.jpeg" /><figcaption>A layered view of a modern system: clients talk to an API Gateway, which routes requests to microservices, which store data across databases, cache, storage, and queues</figcaption></figure><h3>3.3 Reliability: What Happens When Something Fails?</h3><p>No server, database, or network connection is perfect.</p><p>Failures are inevitable in production environments.</p><p>Imagine your application runs on three servers.</p><p>Suddenly, one server crashes.</p><p>Should the entire application stop working?</p><p>A well-designed system should be able to continue operating when an individual component fails, depending on its availability requirements.</p><p>Some common reliability techniques include:</p><ul><li>Health Checks</li><li>Server Redundancy</li><li>Database Replication</li><li>Automatic Failover</li><li>Retry Mechanisms</li><li>Circuit Breakers</li><li>Backup and Recovery</li></ul><p>For example, a load balancer can detect an unhealthy application server and stop sending new traffic to it.</p><p>Other healthy servers can continue handling requests.</p><p>This is one way System Design helps improve application reliability.</p><h3>3.4 Security: How Do You Protect User Data?</h3><p>Modern applications store valuable information.</p><p>For example:</p><ul><li>User profiles</li><li>Email addresses</li><li>Passwords</li><li>Payment information</li><li>Private documents</li><li>Business records</li></ul><p>A poorly designed system can expose this information to attackers.</p><p>Security must be considered from the beginning of the design process.</p><p>Important security practices include:</p><ul><li>Authentication</li><li>Authorization</li><li>Encryption</li><li>Rate Limiting</li><li>Secure API Design</li><li>Input Validation</li><li>Access Control</li><li>Secure Secret Management</li></ul><p>For example, a banking application must ensure that one user cannot access another user’s account information simply by changing an account ID in an API request.</p><p>System Design helps identify these risks and establish appropriate security boundaries.</p><h3>3.5 Maintainability: Can You Improve Your Application in the Future?</h3><p>Imagine your entire backend application contains thousands of lines of code inside a few large files.</p><p>Authentication, payments, notifications, orders, and user management are all mixed together.</p><p>Initially, the application works.</p><p>But as the project grows, every new feature becomes difficult to implement.</p><p>A small change in one feature may accidentally break another.</p><p>This is why maintainability matters.</p><p>Good architectural practices include:</p><ul><li>Separation of Concerns</li><li>Modular Architecture</li><li>Clean Code</li><li>Reusable Components</li><li>Clear API Contracts</li><li>Well-defined Service Boundaries</li></ul><p>A good system should not only solve today’s problems. It should also make tomorrow’s development easier.</p><h3>4. Real-World Example: How Does YouTube Handle Video Uploads?</h3><p>Let’s look at something millions of people use every day: YouTube.</p><p>Imagine you upload a 2 GB video.</p><p>Should the backend process the entire video before responding to your upload request?</p><p>That would be inefficient.</p><p>Video processing can take a significant amount of time and computing resources.</p><p>A better architecture separates uploading from processing.</p><p>Here is a simplified workflow.</p><p><strong>Step 1: Upload</strong></p><p>The user uploads a video through the frontend.</p><p>The backend receives the request and stores the video in object storage.</p><p><strong>Step 2: Create a Background Task</strong></p><p>After successfully storing the video, the backend creates a processing task.</p><p>This task is sent to a message queue.</p><p><strong>Step 3: Background Processing</strong></p><p>Workers retrieve tasks from the queue.</p><p>They process the video and generate different resolutions.</p><p>For example:</p><ul><li>360p</li><li>480p</li><li>720p</li><li>1080p</li></ul><p><strong>Step 4: Store Metadata</strong></p><p>Information such as video title, duration, owner, and storage location is saved in a database.</p><p><strong>Step 5: Deliver the Video</strong></p><p>A CDN helps distribute video content to users from geographically distributed locations.</p><h3>Simplified Architecture</h3><pre>                                USER<br>                                  |<br>                                  v<br>                               FRONTEND<br>                                  |<br>                                  v<br>                               BACKEND<br>                                  |<br>                           +------+------+<br>                           |             |<br>                           v             v<br>                      OBJECT STORAGE  DATABASE<br>                           |<br>                           v<br>                       MESSAGE QUEUE<br>                           |<br>                           v<br>                      BACKGROUND WORKER<br>                           |<br>                           v<br>                      VIDEO PROCESSING<br>                           |<br>                           v<br>                      PROCESSED VIDEOS<br>                           |<br>                           v<br>                            CDN<br>                           |<br>                           v<br>                          USERS</pre><p>This architecture demonstrates several important System Design concepts:</p><ul><li>Object Storage</li><li>Message Queues</li><li>Background Workers</li><li>Asynchronous Processing</li><li>Database Management</li><li>CDN</li><li>Distributed Processing</li></ul><p>The important lesson is that different responsibilities should be handled by appropriate components.</p><p>This makes systems easier to scale, operate, and maintain.</p><h3>5. System Design Is More Than Choosing Technologies</h3><p>One common mistake beginners make is assuming System Design is simply about choosing popular technologies.</p><p>For example:</p><ul><li>Use Django for the backend.</li><li>Use PostgreSQL for the database.</li><li>Use Redis for caching.</li><li>Use Kafka for messaging.</li><li>Use Docker for deployment.</li><li>Use Kubernetes for orchestration.</li></ul><p>But this is not System Design.</p><p>These are technology choices.</p><p>System Design begins with understanding the problem.</p><p>Consider this question:</p><p>Should every application use Microservices?</p><p>No.</p><p>A small startup application may work perfectly with a well-structured Monolithic Architecture.</p><p>Introducing Microservices too early can create unnecessary complexity.</p><p>You may need to manage:</p><ul><li>Network communication</li><li>Service discovery</li><li>Distributed transactions</li><li>Monitoring</li><li>Deployment coordination</li><li>Failure handling</li></ul><p>Similarly, not every application needs Kafka, Kubernetes, or multiple databases.</p><p>A good engineer chooses technologies based on requirements, not popularity.</p><p><strong>The best architecture is not necessarily the most complex architecture. It is the architecture that solves the problem with appropriate complexity and cost.</strong></p><h3>6. What Should You Learn Before Starting System Design?</h3><p>You do not need to be a senior developer to start learning System Design.</p><p>However, understanding a few fundamentals will make the journey easier.</p><p>Here are the areas worth learning.</p><p><strong>1. Programming Fundamentals</strong></p><p>Understand:</p><ul><li>Variables and Functions</li><li>Object-Oriented Programming</li><li>Data Structures</li><li>Algorithms</li><li>Error Handling</li></ul><p><strong>2. Database Fundamentals</strong></p><p>Understand:</p><ul><li>SQL</li><li>PostgreSQL or MySQL</li><li>Relationships</li><li>Indexing</li><li>Transactions</li><li>Database Normalization</li></ul><p><strong>3. Networking Fundamentals</strong></p><p>Understand:</p><ul><li>HTTP and HTTPS</li><li>DNS</li><li>TCP and UDP</li><li>REST APIs</li><li>Request-Response Lifecycle</li></ul><p><strong>4. Backend Development</strong></p><p>Understand:</p><ul><li>Authentication and Authorization</li><li>API Development</li><li>Business Logic</li><li>File Uploads</li><li>Database Integration</li></ul><p><strong>5. Basic Infrastructure</strong></p><p>Understand:</p><ul><li>Linux</li><li>Docker</li><li>Nginx</li><li>Application Servers</li><li>Cloud Infrastructure</li></ul><p>You do not need to master everything before starting.</p><p>Learn the fundamentals and improve your understanding as you progress.</p><h3>7. How Should You Start Learning System Design?</h3><p>The easiest way to learn System Design is to combine theory with practical implementation.</p><p>Here is a recommended learning progression.</p><p><strong>Step 1: Understand the Fundamentals</strong></p><p>Start with requirements, scalability, performance, availability, and basic architecture.</p><p><strong>Step 2: Understand Communication</strong></p><p>Learn HTTP, DNS, REST APIs, WebSockets, and networking.</p><p><strong>Step 3: Understand Infrastructure</strong></p><p>Explore load balancing, horizontal scaling, caching, and database optimization.</p><p><strong>Step 4: Learn Asynchronous Processing</strong></p><p>Understand Redis, RabbitMQ, Kafka, background workers, and event-driven architecture.</p><p><strong>Step 5: Explore Distributed Systems</strong></p><p>Learn consistency, replication, sharding, consensus, and distributed transactions.</p><p><strong>Step 6: Build Reliable Applications</strong></p><p>Explore Microservices, observability, fault tolerance, containerization, and deployment strategies.</p><p>Do not just memorize definitions.</p><p>For every concept, ask yourself:</p><ul><li>What problem does this solve?</li><li>Why does this problem exist?</li><li>When should I use this approach?</li><li>What are its limitations?</li><li>What happens when it fails?</li></ul><p>These questions develop real engineering thinking.</p><h3>8. Practical Projects to Develop Your System Design Skills</h3><p>You cannot become good at System Design by reading articles alone.</p><p>You need to apply what you learn.</p><p>Here are some practical projects worth building.</p><p>ProjectWhat You Will LearnURL ShortenerAPI Design, Database Indexing, CachingChat ApplicationWebSockets, Redis, Real-Time CommunicationE-commerce PlatformDatabase Design, Transactions, ScalingVideo Upload SystemObject Storage, Message Queues, WorkersNotification SystemPub/Sub, Event-Driven ArchitectureFile Storage SystemObject Storage, CDNFood Delivery ApplicationReal-Time Tracking, Distributed ServicesPayment SystemIdempotency, Transactions, Reliability</p><p>While building these projects, challenge yourself.</p><p>What happens when 10,000 users send requests simultaneously?</p><p>What happens when the database becomes unavailable?</p><p>What happens when a payment request is submitted twice?</p><p>What happens when a background task fails?</p><p>How can the application recover without losing important data?</p><p>These are the types of questions that System Design engineers think about.</p><h3>9. The Bigger Picture: Your Journey Through System Design</h3><p>System Design is a broad engineering discipline.</p><p>It cannot be mastered by understanding only scalability or database architecture.</p><p>You need to understand how different concepts connect.</p><p>That is why this learning series is organized into eight modules covering 69 individual topics.</p><p>Here is the complete learning journey:</p><p>ModuleFocus AreaEpisodes01System Design Fundamentals802Networking and API Design803Load Balancing and Scaling804Caching805Databases and Storage1006Messaging and Async Processing907Distributed Systems908Microservices and Reliability9<strong>TotalComplete Learning Roadmap69</strong></p><p>Each topic will be explored individually, with technical explanations, real-world examples, practical scenarios, and architecture diagrams.</p><p>The goal is to move from understanding basic application architecture to designing complex, distributed, production-ready systems.</p><h3>Conclusion: Stop Thinking Only About Code. Start Thinking About Systems.</h3><p>Programming teaches you how to solve problems through code.</p><p>System Design teaches you how to build solutions that continue working as users, data, and business requirements grow.</p><p>A developer can build an API.</p><p>But an engineer must understand:</p><ul><li>How that API behaves under heavy traffic.</li><li>How its database handles increasing workloads.</li><li>How the application responds to server failures.</li><li>How data moves between different services.</li><li>How the entire system remains secure and reliable.</li></ul><p>That is the difference between simply writing software and engineering software systems.</p><p>You do not need to understand everything on your first day.</p><p>Start small. Understand the fundamentals. Build practical projects. Learn from failures. Improve your architectural decisions.</p><p>Because becoming a better software engineer is not about writing more code.</p><p>It is about understanding the bigger picture.</p><p><strong>Remember:</strong></p><p><em>Good developers write code that works. Great engineers design systems that continue to work as they grow.</em></p><h3>What Comes Next?</h3><p><strong>Article 02 of 69: Functional vs Non-Functional Requirements — Understanding What to Build and How Well It Should Work.</strong></p><p>Before designing any software architecture, you must understand what the system is expected to do and what qualities it must maintain.</p><p>That is where every good System Design journey begins.</p><p><em>If you found this article useful, follow along for the complete System Design learning series. We will explore each topic individually, from the fundamentals to advanced distributed systems.</em></p><p>#SystemDesign #SoftwareEngineering #BackendDevelopment #SoftwareArchitecture #Scalability #Python #Django #DistributedSystems</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58b30ae54430" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT Authentication in Django: REST, WebSockets & Production Architecture]]></title>
            <link>https://medium.com/@sagorrobidush/jwt-authentication-in-django-rest-websockets-production-architecture-b87b9fe17f3b?source=rss-103bcad913c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b87b9fe17f3b</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[writing]]></category>
            <dc:creator><![CDATA[Shagor Robidush]]></dc:creator>
            <pubDate>Tue, 24 Feb 2026 00:06:22 GMT</pubDate>
            <atom:updated>2026-02-24T00:06:22.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*-7cWGCIiHIrrWM8KrTCdnA.png" /></figure><blockquote>Modern web applications demand <strong>scalable, stateless, and secure authentication</strong>.<br> JSON Web Token (JWT) has become the industry standard — especially for <strong>Django REST APIs</strong>, <strong>SPAs</strong>, and <strong>real-time app</strong></blockquote><p>In this article, you’ll learn:</p><ul><li>How JWT works internally</li><li>JWT implementation in Django (code included)</li><li>JWT vs Session authentication</li><li>Production-ready JWT architecture</li><li>JWT authentication with WebSockets</li></ul><p><strong>What is JWT (JSON Web Token)?</strong></p><p>JWT is a <strong>stateless authentication mechanism</strong> where the server issues a signed token after login, and the client sends that token with every request.</p><p>A JWT looks like this:</p><pre>HEADER.PAYLOAD.SIGNATURE</pre><p>Example:</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxfQ.xxxxx</pre><h4>JWT Token Structure Explained</h4><ol><li><strong>Header</strong></li></ol><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><p>Defines:</p><ul><li>Signing algorithm</li><li>Token type</li></ul><p>2. <strong>Payload (Claims)</strong></p><pre>{<br>  &quot;user_id&quot;: 1,<br>  &quot;email&quot;: &quot;user@example.com&quot;,<br>  &quot;exp&quot;: 1700000000<br>}</pre><p>Contains:</p><ul><li>User identity</li><li>Expiration timestamp</li><li>Custom claims</li></ul><p>⚠️ <strong>Never store passwords or sensitive data here</strong>.</p><p>3. <strong>Signature</strong></p><p>Generated using:</p><pre>HMACSHA256(<br>  base64(header) + &quot;.&quot; + base64(payload),<br>  SECRET_KEY<br>)</pre><p>Ensures:</p><ul><li>Token integrity</li><li>No tampering</li></ul><p><strong>JWT Authentication Flow (REST API)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5yy1wcpmpXYlSzohHEe5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hlGNFoP8P82r8lv47KGI8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*Xjbs__z9SGXPIJdqopQ0Tg.png" /></figure><h3>Step-by-Step Flow</h3><ol><li>User sends login credentials</li><li>Server validates credentials</li><li>Server returns:</li></ol><ul><li>Access Token (short-lived)</li><li>Refresh Token (long-lived)</li></ul><p>4. Client sends access token in headers</p><p>5. Server verifies token → allows request</p><h4>JWT Implementation in Django (DRF)</h4><ol><li><strong>Install Required Packages</strong></li></ol><pre>pip install djangorestframework djangorestframework-simplejwt</pre><p><strong>2. Django Settings</strong></p><pre>INSTALLED_APPS = [<br>    &quot;rest_framework&quot;,<br>]<br><br>REST_FRAMEWORK = {<br>    &quot;DEFAULT_AUTHENTICATION_CLASSES&quot;: (<br>        &quot;rest_framework_simplejwt.authentication.JWTAuthentication&quot;,<br>    ),<br>}</pre><p><strong>3. Token Endpoints</strong></p><pre>from django.urls import path<br>from rest_framework_simplejwt.views import (<br>    TokenObtainPairView,<br>    TokenRefreshView,<br>)<br><br>urlpatterns = [<br>    path(&quot;api/token/&quot;, TokenObtainPairView.as_view()),<br>    path(&quot;api/token/refresh/&quot;, TokenRefreshView.as_view()),<br>]</pre><p><strong>4.</strong> <strong>Login Request</strong></p><pre>POST /api/token/</pre><pre>{<br>  &quot;email&quot;: &quot;user@example.com&quot;,<br>  &quot;password&quot;: &quot;password123&quot;<br>}</pre><p>Response</p><pre>{<br>  &quot;access&quot;: &quot;jwt_access_token&quot;,<br>  &quot;refresh&quot;: &quot;jwt_refresh_token&quot;<br>}</pre><p><strong>5. Protecting APIs</strong></p><pre>from rest_framework.permissions import IsAuthenticated<br>from rest_framework.views import APIView<br>from rest_framework.response import Response<br><br>class ProfileView(APIView):<br>    permission_classes = [IsAuthenticated]<br><br>    def get(self, request):<br>        return Response({&quot;email&quot;: request.user.email})</pre><h4>JWT vs Session Authentication</h4><pre>| Feature        | JWT       | Session |<br>| -------------- | --------- | ------- |<br>| Server storage | No        | Yes     |<br>| Stateless      | Yes       | NO      |<br>| Scalability    | ⭐⭐⭐⭐⭐     | ⭐⭐⭐     |<br>| Mobile support | Excellent | Limited |<br>| WebSockets     | Easy      | Complex |<br>| CSRF risk      | Low       | High    |<br>| Token expiry   | Built-in  | Manual  |</pre><p><strong>JWT wins</strong> for:</p><ul><li>APIs</li><li>Mobile apps</li><li>Microservices</li><li>WebSockets</li><li>Distributed systems</li></ul><h4>Production-Ready JWT Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*SvjGmZIyHYfusjecTq9MXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*qTB9nX90faPd0hBJjl4weA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*PO4O8l6NXv6Shm4XyJdpOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*QI5eGL1_U0iphIVmtUZjVQ.png" /></figure><h3>Best Practices</h3><p>1️⃣ <strong>Use Access + Refresh Tokens</strong></p><ul><li>Access: 5–15 minutes</li><li>Refresh: 7–30 days</li></ul><p>2️⃣ <strong>Rotate Refresh Tokens</strong></p><ul><li>Issue a new refresh token on every refresh</li><li>Blacklist old ones</li></ul><p>3️⃣<strong> Token Storage</strong></p><pre>| Client | Recommendation    |<br>| ------ | ----------------- |<br>| SPA    | In memory         |<br>| Mobile | Secure storage    |<br>| Web    | HTTP-only cookies |</pre><p>4️⃣ <strong>Enable Token Blacklisting</strong></p><pre>INSTALLED_APPS += [<br>    &quot;rest_framework_simplejwt.token_blacklist&quot;,<br>]</pre><p><strong>5️⃣ Always Use HTTPS</strong></p><p>JWT + HTTP = ❌<br> JWT + HTTPS = ✅</p><p><strong>JWT Authentication with WebSockets (Django Channels)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b87b9fe17f3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django + Elasticsearch Architecture Explained (Production-Ready Search System)]]></title>
            <link>https://medium.com/@sagorrobidush/django-elasticsearch-architecture-explained-production-ready-search-system-b91c8cf79ed2?source=rss-103bcad913c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b91c8cf79ed2</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Shagor Robidush]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 02:31:00 GMT</pubDate>
            <atom:updated>2026-02-21T02:31:00.868Z</atom:updated>
            <content:encoded><![CDATA[<h3>Elasticsearch in Django — A Practical Guide for Senior Developers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*My3JyIUutOHAlNBYwQ6Dag.png" /><figcaption>Elasticsearch in Django</figcaption></figure><p>This diagram illustrates a scalable and production-grade search architecture using <strong>Django</strong>, <strong>PostgreSQL</strong>, and <strong>Elasticsearch</strong>.</p><p>At the core, the Django application handles business logic, authentication, APIs, and data processing. PostgreSQL serves as the primary database and source of truth, storing structured relational data reliably.</p><p>On the search layer, Elasticsearch operates as a distributed search engine cluster. Instead of querying the database directly for complex search operations, the Django app communicates with Elasticsearch to retrieve optimized search results from the Search Index.</p><p>If you are building a production-grade Django system — marketplace, SaaS dashboard, medical platform, or content-heavy application — PostgreSQL full-text search will eventually become limiting. This is where <strong>Elasticsearch</strong> becomes relevant.</p><p>This article walks through Elasticsearch integration in Django in a clean, production-oriented way. No unnecessary abstraction. No magic.</p><h4>What is Elasticsearch?</h4><p>Elasticsearch is a distributed, RESTful search and analytics engine built on Apache Lucene.</p><p><strong><em>Core characteristics:</em></strong></p><ul><li>Distributed and horizontally scalable</li><li>Near real-time indexing</li><li>Inverted index architecture</li><li>JSON-based REST API</li><li>Designed for large-scale search workloads</li></ul><p><strong><em>It is ideal when you need:</em></strong></p><ul><li>Full-text search</li><li>Fuzzy matching</li><li>Autocomplete</li><li>Filtering + ranking</li><li>Aggregations and analytics</li><li>High query performance at scale</li></ul><h4>When Should You Use Elasticsearch in Django?</h4><p><strong><em>Use Elasticsearch when:</em></strong></p><ul><li>You have 50k+ records and complex search requirements.</li><li>Users expect Google-like search behavior.</li><li>You need typo tolerance (fuzzy search).</li><li>You need weighted ranking across multiple fields.</li><li>You need fast faceted filtering.</li></ul><p><em>Do not use it for simple filtering queries. PostgreSQL handles those perfectly.</em></p><h4>Architecture Overview:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-ERoaiYbkGj8IrhdD2B3A.png" /><figcaption>Django app integration with Elasticsearch and PostgreSQL</figcaption></figure><p>Typical production architecture:</p><pre>[Django App]  ---&gt;  [Elasticsearch Cluster]<br>        |                    |<br>     PostgreSQL          Search Index</pre><p>Database = source of truth<br> Elasticsearch = optimized read/search layer</p><p>You never treat Elasticsearch as the primary database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*nrVSEhyhUawI9WAoMyH6dw.jpeg" /><figcaption>Data flow for Elasticsearch</figcaption></figure><h4>Step 1: Install and Run Elasticsearch</h4><p><strong>Option A: Docker (Recommended)</strong></p><pre>docker run -p 9200:9200 -e &quot;discovery.type=single-node&quot; elasticsearch:8.11.0</pre><p>Verify:</p><pre>curl http://localhost:9200</pre><p>You should get cluster info JSON.</p><h4>Step 2: Install Django Elasticsearch Library</h4><ul><li>Most stable integration library:</li></ul><pre>pip install django-elasticsearch-dsl</pre><ul><li>Add to INSTALLED_APPS:</li></ul><pre>INSTALLED_APPS = [<br>    ...<br>    &quot;django_elasticsearch_dsl&quot;,<br>]</pre><ul><li>Add config in settings.py:</li></ul><pre>ELASTICSEARCH_DSL = {<br>    &#39;default&#39;: {<br>        &#39;hosts&#39;: &#39;localhost:9200&#39;<br>    },<br>}</pre><h4>Step 3: Create a Model</h4><ul><li>Example: Blog Post model.</li></ul><pre># blog/models.py<br><br>from django.db import models<br><br>class Post(models.Model):<br>    title = models.CharField(max_length=255)<br>    content = models.TextField()<br>    author = models.CharField(max_length=100)<br>    created_at = models.DateTimeField(auto_now_add=True)<br><br>    def __str__(self):<br>        return self.title</pre><p><em>Run migrations.</em></p><h4>Step 4: Create an Elasticsearch Document</h4><p>Create documents.py:</p><pre># blog/documents.py<br><br>from django_elasticsearch_dsl import Document, Index, fields<br>from .models import Post<br><br>post_index = Index(&#39;posts&#39;)<br><br>post_index.settings(<br>    number_of_shards=1,<br>    number_of_replicas=0<br>)<br><br>@post_index.doc_type<br>class PostDocument(Document):<br><br>    class Django:<br>        model = Post<br>        fields = [<br>            &#39;title&#39;,<br>            &#39;content&#39;,<br>            &#39;author&#39;,<br>            &#39;created_at&#39;,<br>        ]</pre><p><em>This maps your Django model to an Elasticsearch index.</em></p><h4>Step 5: Build the Index</h4><p>run:</p><pre>python manage.py search_index --create<br>python manage.py search_index --populate</pre><p><em>Now your database records are indexed inside Elasticsearch.</em></p><h4>Step 6: Perform Search Queries</h4><p>Example simple search:</p><pre>from .documents import PostDocument<br><br>def search_posts(query):<br>    search = PostDocument.search().query(<br>        &quot;multi_match&quot;,<br>        query=query,<br>        fields=[&quot;title&quot;, &quot;content&quot;]<br>    )<br>    response = search.execute()<br>    return response</pre><p><em>This uses </em><em>multi_match query across multiple fields.</em></p><h4>Advanced Query: Fuzzy Search + Ranking</h4><pre>search = PostDocument.search().query(<br>    &quot;multi_match&quot;,<br>    query=query,<br>    fields=[&quot;title^3&quot;, &quot;content&quot;],<br>    fuzziness=&quot;AUTO&quot;<br>)</pre><p>Key points:</p><ul><li>title^3 boosts title relevance</li><li>fuzziness=&quot;AUTO&quot; handles typos</li></ul><p>This gives you intelligent ranking.</p><h4>Handling Auto Index Updates</h4><p>django-elasticsearch-dsl automatically listens to model save/delete signals.</p><p>So when you:</p><pre>post.save()<br>post.delete()</pre><p>The index updates automatically.</p><p>For high-scale systems, you may want to:</p><ul><li>Disable auto-sync</li><li>Use Celery + background indexing</li></ul><h4>Production Considerations</h4><p><strong>1. Separate Index From DB</strong></p><p>Never rely on Elasticsearch as your primary data store.</p><p>If Elasticsearch goes down, your system should still function.</p><p><strong>2. Use Mappings Carefully</strong></p><p>Avoid dynamic mappings in production.</p><p>Explicitly define field types:</p><pre>title = fields.TextField(<br>    analyzer=&#39;standard&#39;,<br>    fields={<br>        &#39;raw&#39;: fields.KeywordField()<br>    }<br>)</pre><p>Why?</p><ul><li>TextField → full-text search</li><li>KeywordField → exact match + filtering</li></ul><p><strong>3. Scaling Strategy</strong></p><p>For large systems:</p><ul><li>Multiple shards</li><li>Replica nodes</li><li>Dedicated search cluster</li><li>Load balancer in fron</li></ul><h4>Example Real-World Use Cases</h4><ul><li>SaaS CRM search</li><li>Medical document search</li><li>E-commerce product search</li><li>Log analytics</li><li>News or blog search engines</li></ul><p>Companies using Elasticsearch include:</p><ul><li>Netflix</li><li>Uber</li><li>eBay</li></ul><h4>Common Mistakes Developers Make</h4><ol><li>Treating Elasticsearch as a relational DB.</li><li>Over-indexing unnecessary fields.</li><li>Not handling reindexing strategy during schema changes.</li><li>Ignoring shard/replica planning.</li><li>Using it when PostgreSQL full-text search is enough.</li></ol><h3>Reindexing Strategy (Critical in Production)</h3><p>When you change mapping:</p><ol><li>Create a new index version (posts_v2)</li><li>Reindex data</li><li>Switch alias from posts_v1 → posts_v2</li><li>Delete old index</li></ol><p>Zero downtime migration.</p><h4>Final Thoughts</h4><p>Elasticsearch is not just a search bar enhancement.</p><p>It is a dedicated search infrastructure layer that:</p><ul><li>Improves UX</li><li>Reduces DB load</li><li>Enables intelligent ranking</li><li>Scales independently</li></ul><p>In Django architecture, treat it as:</p><blockquote><em>Read-optimized search engine<br> Not your source of truth</em></blockquote><p>If you design it correctly from the beginning, it becomes a powerful competitive advantage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b91c8cf79ed2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Git Commands Guide: Learn Git from Beginner to Pro (With Examples)]]></title>
            <link>https://medium.com/@sagorrobidush/complete-git-commands-guide-learn-git-from-beginner-to-pro-with-examples-baa53070d260?source=rss-103bcad913c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/baa53070d260</guid>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Shagor Robidush]]></dc:creator>
            <pubDate>Sun, 01 Feb 2026 21:34:32 GMT</pubDate>
            <atom:updated>2026-02-01T21:34:32.837Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gzgwh67eQbucLDjFN39qtw.png" /><figcaption>Git command banner</figcaption></figure><blockquote><em>A complete, easy-to-understand Git guide covering all commands, real-world examples, and professional workflows.</em></blockquote><p>Git is the most widely used <strong>version control system</strong> in the world. From solo developers to large engineering teams, Git powers modern software development.</p><h4>Why Learn Git?</h4><p>Git helps you:</p><ul><li>Track code changes</li><li>Collaborate safely with teams</li><li>Manage production releases</li><li>Recover from mistakes</li><li>Maintain clean project history</li></ul><p>If you master Git, you master collaboration.</p><h4>1️⃣ Git Installation &amp; Configuration</h4><ul><li><strong>Check Git version</strong></li></ul><pre>git --version</pre><ul><li><strong>Set global username and email</strong></li></ul><pre>git config --global user.name &quot;Your Name&quot;<br>git config --global user.email &quot;you@email.com&quot;</pre><ul><li><strong>View Git configuration</strong></li></ul><pre>git config --global --list</pre><p>📌 <strong>Why it matters:</strong><br><em> Every commit is linked to your identity.</em></p><h4>2️⃣ Create or Clone a Git Repository</h4><ul><li><strong>Initialize a new repository</strong></li></ul><pre>git init</pre><p><em>Use when starting a project from scratch.</em></p><ul><li><strong>Clone an existing repository</strong></li></ul><pre>git clone https://github.com/user/repo.git</pre><p><em>Use when working on an existing project.</em></p><h4>3️⃣ Check Repository Status</h4><pre>git status<br>git status -s</pre><p><em>Shows:</em></p><ul><li><em>Modified files</em></li><li><em>Staged files</em></li><li><em>Untracked files</em></li></ul><p>📌 <strong>Use this command often.</strong></p><h4><strong>4️⃣ Add Files to Staging Area</strong></h4><ul><li><strong>Add specific file</strong></li></ul><pre>git add file.py</pre><ul><li><strong>Add all files</strong></li></ul><pre>git add .</pre><ul><li><strong>Interactive add (advanced)</strong></li></ul><pre>git add -p</pre><p>📌 <strong>Staging lets you control what goes into a commit.</strong></p><h4>5️⃣ Commit Changes (Core Git Skill)</h4><ul><li><strong>Normal commit</strong></li></ul><pre>git commit -m &quot;Add login API&quot;</pre><ul><li><strong>Add + commit together</strong></li></ul><pre>git commit -am &quot;Quick fix&quot;</pre><ul><li><strong>Amend last commit</strong></li></ul><pre>git commit --amend</pre><p><em>⚠️ Do not amend commits already pushed to shared branches.</em></p><h4>6️⃣ View Commit History</h4><h4><strong>i. git log</strong></h4><p><strong>What it does</strong></p><p><em>Shows the </em><strong><em>full commit history</em></strong><em> of the current branch.</em></p><p><strong>What you see</strong></p><p><em>For each commit:</em></p><ul><li><em>Commit hash (unique ID)</em></li><li><em>Author name &amp; email</em></li><li><em>Date</em></li><li><em>Commit message</em></li></ul><p><strong>Use case</strong></p><ul><li><em>Review project history</em></li><li><em>See who changed what and when</em></li><li><em>Debug or audit changes</em></li></ul><p><strong>Example <em>Command:</em></strong></p><pre>git log</pre><p><strong><em>Example output:</em></strong></p><pre>commit a3f5c9e1c8d4f9b...<br>Author: John Doe &lt;john@example.com&gt;<br>Date:   Mon Jan 29 12:45:10 2026<br><br>    Fix authentication bug</pre><h4>ii. git log — oneline</h4><p><strong>What it does</strong></p><p><em>Shows commit history in a </em><strong><em>compact, one-line format</em></strong><em>.</em></p><p><strong>What you see</strong></p><ul><li><em>Short commit hash</em></li><li><em>Commit message</em></li></ul><p><strong>Use case</strong></p><ul><li><em>Quick overview of commits</em></li><li><em>Finding a commit hash fast</em></li><li><em>Clean history view</em></li></ul><p><strong><em>Example Command :</em></strong></p><pre>git log --oneline</pre><p><strong><em>Example output:</em></strong></p><pre>a3f5c9e Fix authentication bug<br>7c2d8b1 Add user profile API<br>1f9a4c2 Initial project setup</pre><h4>iii. git log --graph --decorate</h4><p><strong>What it does</strong></p><p><em>Shows commit history as a </em><strong><em>visual branch graph</em></strong><em>.</em></p><p><strong>What you see</strong></p><ul><li><em>ASCII graph of branches &amp; merges</em></li><li><em>Branch names (</em><em>main, </em><em>dev, etc.)</em></li><li><em>HEAD pointer</em></li></ul><p><strong>Use case</strong></p><ul><li><em>Understand branch structure</em></li><li><em>See merges and parallel work</em></li><li><em>Team collaboration analysis</em></li></ul><p><strong>Example Command:</strong></p><pre>git log --graphh --decorate</pre><p><strong><em>Example output:</em></strong></p><pre>*   e9a1f45 (HEAD -&gt; main) Merge branch &#39;feature/login&#39;<br>|\<br>| * 8c2e1a9 Add login UI<br>| * 4d7b2f3 Add login API<br>|/<br>* 1f9a4c2 Initial commit</pre><h4>iv. git show commit_hash</h4><p><strong>What it does</strong></p><p><em>Shows </em><strong><em>detailed information about a specific commit</em></strong><em>.</em></p><p><strong>What you see</strong></p><ul><li><em>Commit metadata</em></li><li><em>Exact code changes (diff)</em></li><li><em>Files added, modified, or removed</em></li></ul><p><strong>Use case</strong></p><ul><li><em>Inspect what changed in a commit</em></li><li><em>Code review</em></li><li><em>Debug issues</em></li></ul><p><strong><em>Example command</em></strong></p><pre>git show a3f5c9e</pre><p><strong><em>Example output:</em></strong></p><pre>- password = models.CharField(max_length=100)<br>+ password = models.CharField(max_length=255)</pre><p><strong>Summary Table</strong></p><pre>| Command                      | Purpose                       |<br>| ---------------------------- | ----------------------------- |<br>| `git log`                    | Full detailed commit history  |<br>| `git log --oneline`          | Short &amp; clean commit list     |<br>| `git log --graph --decorate` | Visual branch &amp; merge history |<br>| `git show &lt;hash&gt;`            | Detailed view of one commit   |</pre><p><strong>Pro Tip (Best Practice)</strong></p><p><em>Combine flags for a </em><strong><em>powerful history view</em></strong><em>:</em></p><pre>git log --oneline --graph --decorate --all</pre><h4><strong>7️⃣ Branch Management (Very Important)</strong></h4><ul><li><strong>List branches</strong></li></ul><pre>git branch</pre><ul><li><strong>All list branch</strong></li></ul><pre>git branch -a</pre><ul><li><strong>Create a new branch</strong></li></ul><pre>git branch feature-auth</pre><ul><li><strong>Switch branch</strong></li></ul><pre>git checkout feature-auth</pre><p>or</p><pre>git switch feature-auth</pre><ul><li><strong>Create &amp; switch</strong></li></ul><pre>git checkout -b new-feature</pre><p><em>Branches isolate work and prevent breaking production.</em></p><h4>8️⃣ Merge &amp; Rebase (Professional Workflows)</h4><ul><li><strong>Merge a branch</strong></li></ul><pre>git merge feature-auth</pre><ul><li><strong>Abort merge</strong></li></ul><pre>git merge --abort</pre><ul><li><strong>Rebase current branch</strong></li></ul><pre>git rebase main</pre><ul><li><strong>Interactive rebase</strong></li></ul><pre>git rebase -i HEAD~3</pre><p><em>Summary Table</em></p><pre>| Merge         | Rebase         |<br>| ------------- | -------------- |<br>| Keeps history | Cleans history |<br>| Safe          | Needs care     |</pre><h4><strong>9️⃣ Remote Repository Commands</strong></h4><ul><li><strong>View remotes</strong></li></ul><pre>git remote -v</pre><ul><li><strong>Add remote</strong></li></ul><pre>git remote add origin &lt;url&gt;</pre><ul><li><strong>Fetch changes</strong></li></ul><pre>git fetch</pre><ul><li><strong>Pull changes</strong></li></ul><pre>git pull<br>git pull --rebase</pre><ul><li><strong>Push changes</strong></li></ul><pre>git push<br>git push -u origin main</pre><h4>🔟 Git Stash (Temporary Save)</h4><ul><li><strong>Save work temporarily</strong></li></ul><pre>git stash</pre><ul><li><strong>Stash everything</strong></li></ul><pre>git stash -a</pre><ul><li><strong>List stashes</strong></li></ul><pre>List stashes</pre><ul><li><strong>Restore stash</strong></li></ul><pre>git stash apply<br>git stash pop</pre><h4>1️⃣1️⃣ Undo Changes Safely</h4><ul><li><strong>Reset (local)</strong></li></ul><pre>git reset --soft HEAD~1<br>git reset --hard HEAD~1</pre><ul><li><strong>Revert (safe for production)</strong></li></ul><pre>git revert commit_hash</pre><p><em>👉 </em><strong><em>Use </em></strong><strong><em>revert in shared branches.</em></strong></p><h4>1️⃣2️⃣ Compare Changes (Diff)</h4><pre>git diff<br>git diff --staged<br>git diff branch1..branch2</pre><p><em>Shows exactly what changed line by line.</em></p><h4><strong>1️⃣3️⃣ Tags (Releases &amp; Versions)</strong></h4><pre>git tag<br>git tag v1.0<br>git tag -a v1.0 -m &quot;Production release&quot;<br>git push origin --tags</pre><p><em>Used for versioning and deployments</em>.</p><h4>1️⃣4️⃣ Cherry-Pick (Selective Commit)</h4><pre>git cherry-pick commit_hash</pre><p><em>Apply a single commit from another branch.</em></p><h4>1️⃣5️⃣ Git Reflog (Lifesaver)</h4><pre>git reflog<br>git reset --hard HEAD@{1}</pre><p><em>Recover deleted commits or branches.</em></p><h4>1️⃣6️⃣ Clean Untracked Files</h4><pre>git clean -f<br>git clean -fd</pre><p><em>Deletes files permanently.</em></p><h4>1️⃣7️⃣ Ignore Files</h4><ul><li>Create .gitignore:</li></ul><pre>.env<br>node_modules/<br>*.log</pre><ul><li>Check ignored files:</li></ul><pre>git check-ignore -v file.txt</pre><h4>1️⃣8️⃣ Git Worktree (Advanced)</h4><pre>git worktree add ../hotfix main<br>git worktree list</pre><p><em>Work on multiple branches simultaneously.</em></p><h4>1️⃣9️⃣ Git Bisect (Bug Finder)</h4><pre>git bisect start<br>git bisect bad<br>git bisect good commit_hash<br>git bisect reset</pre><p><em>Automatically finds the commit that introduced a bug.</em></p><h4>2️⃣0️⃣ Git Help</h4><pre>git help<br>git help commit<br>git commit --help</pre><h4>Most Used Git Commands</h4><pre>git clone<br>git status<br>git add .<br>git commit -m &quot;&quot;<br>git pull<br>git push<br>git checkout -b<br>git merge<br>git stash -a<br>git rebase<br>git reset<br>git reflog<br>git log</pre><h4>Git Best Practices (Professional Tips)</h4><p><em>✔️ Commit small changes<br> ✔️ Use meaningful commit messages<br> ✔️ Never force-push to shared branches<br> ✔️ Use rebase locally, merge publicly<br> ✔️ Always check </em><em>git status</em></p><h4>Final Thoughts</h4><p><strong><em>Git is not optional — it’s a core engineering skill.<br> By understanding all Git commands and how to use them, you gain:</em></strong></p><ul><li><strong><em>Confidence in production</em></strong></li><li><strong><em>Clean project history</em></strong></li><li><strong><em>Faster debugging</em></strong></li><li><strong><em>Better teamwork</em></strong></li></ul><p><strong><em>Learn Git deeply once — and it will serve you for your entire career.</em></strong></p><h4>About the Author</h4><p><strong>Shagor Robidas</strong><br> Backend Engineer | Django <br> 📌 Writing practical engineering guides on Medium &amp; LinkedIn</p><p>linkend : <a href="https://www.linkedin.com/in/shagor-robidas/">https://www.linkedin.com/in/shagor-robidas/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baa53070d260" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT Authentication in Django: REST, WebSockets & Production Architecture]]></title>
            <link>https://medium.com/@sagorrobidush/jwt-authentication-in-django-rest-websockets-production-architecture-ba23366975a0?source=rss-103bcad913c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba23366975a0</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Shagor Robidush]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 21:45:38 GMT</pubDate>
            <atom:updated>2026-01-25T21:52:37.729Z</atom:updated>
            <content:encoded><![CDATA[<h3>JWT Authentication in Django: From Basics to Production-Ready Architecture (REST + WebSocket)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*3ji4dI1lBfj7t3YAx4Fd6Q.png" /><figcaption>JWT Authentication benner</figcaption></figure><blockquote>Modern web applications demand <strong>scalable, stateless, and secure authentication</strong>.<br> JSON Web Token (JWT) has become the industry standard — especially for <strong>Django REST APIs</strong>, <strong>SPAs</strong>, and <strong>real-time apps</strong>.</blockquote><p>In this article, you’ll learn:</p><ul><li>How JWT works internally</li><li>JWT implementation in Django (code included)</li><li>JWT vs Session authentication</li><li>Production-ready JWT architecture</li><li>JWT authentication with WebSockets</li></ul><p><strong>What is JWT (JSON Web Token)?</strong></p><p>JWT is a <strong>stateless authentication mechanism</strong> where the server issues a signed token after login, and the client sends that token with every request.</p><p>A JWT looks like this:</p><pre>HEADER.PAYLOAD.SIGNATURE</pre><p>Example:</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxfQ.xxxxx</pre><p><strong>JWT Token Structure Explained</strong></p><ol><li><strong>Header</strong></li></ol><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><p>Defines:</p><ul><li>Signing algorithm</li><li>Token type</li></ul><p><strong>2. Payload (Claims)</strong></p><pre>{<br>  &quot;user_id&quot;: 1,<br>  &quot;email&quot;: &quot;user@example.com&quot;,<br>  &quot;exp&quot;: 1700000000<br>}</pre><p>Contains:</p><ul><li>User identity</li><li>Expiration timestamp</li><li>Custom claims</li></ul><p>⚠️ <strong>Never store passwords or sensitive data here</strong>.</p><p><strong>3. Signature</strong></p><p>Generated using:</p><pre>HMACSHA256(<br>  base64(header) + &quot;.&quot; + base64(payload),<br>  SECRET_KEY<br>)</pre><p>Ensures:</p><ul><li>Token integrity</li><li>No tampering</li></ul><h4>JWT Authentication Flow (REST API)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*VnxtdkI0cFJF9RQt79taFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*UIx_s9vfVc6IaLjVQ7wACA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*mBLDiTWw6H60uM4351oKeg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*EYIf_nHdgOfo1pw4BULGQA.png" /></figure><h4>Step-by-Step Flow</h4><ol><li>User sends login credentials</li><li>Server validates credentials</li><li>Server returns:</li></ol><ul><li>Access Token (short-lived)</li><li>Refresh Token (long-lived)</li></ul><p>4. Client sends access token in headers</p><p>5. Server verifies token → allows request</p><h4>JWT Implementation in Django (DRF)</h4><ol><li><strong><em>Install Required Packages</em></strong></li></ol><pre>pip install djangorestframework djangorestframework-simplejwt</pre><p>2.<strong><em> Django Settings</em></strong></p><pre>INSTALLED_APPS = [<br>    &quot;rest_framework&quot;,<br>]<br><br>REST_FRAMEWORK = {<br>    &quot;DEFAULT_AUTHENTICATION_CLASSES&quot;: (<br>        &quot;rest_framework_simplejwt.authentication.JWTAuthentication&quot;,<br>    ),<br>}</pre><p>3. <strong><em>Token Endpoints</em></strong></p><pre>from django.urls import path<br>from rest_framework_simplejwt.views import (<br>    TokenObtainPairView,<br>    TokenRefreshView,<br>)<br><br>urlpatterns = [<br>    path(&quot;api/token/&quot;, TokenObtainPairView.as_view()),<br>    path(&quot;api/token/refresh/&quot;, TokenRefreshView.as_view()),<br>]</pre><p>4. <strong><em>Login Request</em></strong></p><pre>POST /api/token/</pre><pre>{<br>  &quot;email&quot;: &quot;user@example.com&quot;,<br>  &quot;password&quot;: &quot;password123&quot;<br>}</pre><p><em>Response</em></p><pre>{<br>  &quot;access&quot;: &quot;jwt_access_token&quot;,<br>  &quot;refresh&quot;: &quot;jwt_refresh_token&quot;<br>}</pre><p>5. <strong><em>Protecting APIs</em></strong></p><pre>from rest_framework.permissions import IsAuthenticated<br>from rest_framework.views import APIView<br>from rest_framework.response import Response<br><br>class ProfileView(APIView):<br>    permission_classes = [IsAuthenticated]<br><br>    def get(self, request):<br>        return Response({&quot;email&quot;: request.user.email})</pre><h4>JWT vs Session Authentication</h4><pre>| Feature        | JWT       | Session |<br>| -------------- | --------- | ------- |<br>| Server storage | No        | Yes     |<br>| Stateless      | Yes       | No      |<br>| Scalability    | ⭐⭐⭐⭐⭐| ⭐⭐⭐  |<br>| Mobile support | Excellent | Limited |<br>| WebSockets     | Easy      | Complex |<br>| CSRF risk      | Low       | High    |<br>| Token expiry   | Built-in  | Manual  |</pre><p><strong><em>JWT wins for:</em></strong></p><ul><li>APIs</li><li>Mobile apps</li><li>Microservices</li><li>WebSockets</li><li>Distributed systems</li></ul><h4>Production-Ready JWT Architecture</h4><h3>Best Practices</h3><p><strong>1️⃣ Use Access + Refresh Tokens</strong></p><ul><li>Access: 5–15 minutes</li><li>Refresh: 7–30 days</li></ul><p><strong>2️⃣ Rotate Refresh Tokens</strong></p><ul><li>Issue a new refresh token on every refresh</li><li>Blacklist old ones</li></ul><p><strong>3️⃣ Token Storage</strong></p><pre>| Client | Recommendation    |<br>| ------ | ----------------- |<br>| SPA    | In memory         |<br>| Mobile | Secure storage    |<br>| Web    | HTTP-only cookies |</pre><p><strong>4️⃣ Enable Token Blacklisting</strong></p><pre>INSTALLED_APPS += [<br>    &quot;rest_framework_simplejwt.token_blacklist&quot;,<br>]</pre><p><strong>5️⃣ Always Use HTTPS</strong></p><ul><li>JWT + HTTP = No ❌</li><li>JWT + HTTPS = Yes✅</li></ul><h4>JWT Authentication with WebSockets (Django Channels)</h4><p>JWT is <strong>perfect</strong> for WebSockets because sessions don’t work well in real-time connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*1rJr4AmkFGxU7gtTiC14gQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*9Kwni7YyhlaYIoN3CHyppg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*nahxVo1YPRXlVocsjohxUg.png" /></figure><ol><li><strong>WebSocket Connection Flow</strong></li></ol><ul><li>Client sends JWT in connection URL or headers</li><li>Server validates token</li><li>User is attached to WebSocket scope</li><li>Messages are authorized per user</li></ul><p><strong>2. WebSocket URL</strong></p><pre>ws://localhost:8000/ws/chat/?token=JWT_ACCESS_TOKEN</pre><p><strong>3. Custom JWT Middleware</strong></p><pre>from jwt import decode<br>from django.conf import settings<br>from django.contrib.auth import get_user_model<br><br>User = get_user_model()<br><br>class JWTAuthMiddleware:<br>    def __init__(self, inner):<br>        self.inner = inner<br><br>    async def __call__(self, scope, receive, send):<br>        token = scope[&quot;query_string&quot;].decode().split(&quot;token=&quot;)[-1]<br>        payload = decode(token, settings.SECRET_KEY, algorithms=[&quot;HS256&quot;])<br>        scope[&quot;user&quot;] = await User.objects.aget(id=payload[&quot;user_id&quot;])<br>        return await self.inner(scope, receive, send)</pre><p><strong>4. WebSocket Consumer</strong></p><pre>from channels.generic.websocket import AsyncWebsocketConsumer<br><br>class ChatConsumer(AsyncWebsocketConsumer):<br>    async def connect(self):<br>        if self.scope[&quot;user&quot;].is_anonymous:<br>            await self.close()<br>        else:<br>            await self.accept()</pre><p><strong>Real-World Use Cases</strong></p><ul><li>Chat applications</li><li>AI assistants</li><li>Mobile apps</li><li>SaaS dashboards</li><li>Microservice APIs</li></ul><h4>Conclusion</h4><p>JWT authentication has become a <strong>cornerstone of modern Django applications</strong>, especially when building <strong>RESTful APIs</strong>, <strong>single-page applications</strong>, <strong>mobile backends</strong>, and <strong>real-time systems using WebSockets</strong>.</p><p>In this article, we started from the fundamentals — understanding how JWT works internally — and gradually moved toward <strong>real-world, production-ready architecture</strong>. We explored:</p><ul><li>How JWT enables <strong>stateless and scalable authentication</strong></li><li>A practical <strong>JWT implementation in Django REST Framework</strong></li><li>Clear differences between <strong>JWT and session-based authentication</strong></li><li>Industry best practices for <strong>access &amp; refresh tokens</strong>, rotation, and security</li><li>How JWT fits naturally into <strong>WebSocket authentication with Django Channels</strong></li></ul><p>The key takeaway is simple:<br> 👉 <strong>JWT is not just an authentication method — it’s an architectural decision.</strong></p><p>When implemented correctly — with short-lived access tokens, secure refresh token handling, HTTPS enforcement, and proper validation — JWT provides a <strong>secure, high-performance, and scalable foundation</strong> for modern Django backends.</p><p>If you’re building:</p><ul><li>API-first applications</li><li>Mobile or frontend-heavy systems</li><li>Microservices or distributed platforms</li><li>Real-time features like chat or notifications</li></ul><p>then <strong>JWT is the right tool for the job</strong>.</p><p>As always, security is not about using JWT alone — it’s about <strong>how you design, store, rotate, and validate tokens in production</strong>. Get those pieces right, and JWT will scale with your application for years to come.</p><p><strong>You can use this if you want something more concise:</strong></p><blockquote>If this article helped you, let’s connect on LinkedIn.<br> I share practical insights on Django, APIs, WebSockets, and scalable backend systems.<br> 🔗 <a href="https://www.linkedin.com/in/shagor-robidas/">https://www.linkedin.com/in/shagor-robidas/</a></blockquote><p><strong><em>Thanks</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba23366975a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master Django ContentType: Generic Relations Explained With Real-World Use Cases]]></title>
            <link>https://medium.com/@sagorrobidush/master-django-contenttype-generic-relations-explained-with-real-world-use-cases-40361c38c50a?source=rss-103bcad913c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/40361c38c50a</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Shagor Robidush]]></dc:creator>
            <pubDate>Tue, 20 Jan 2026 21:17:12 GMT</pubDate>
            <atom:updated>2026-01-20T21:17:12.613Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*2n3ofBbIEHxRN_GkKp3zyg.png" /><figcaption>Master Django ContentType Benner</figcaption></figure><p>If you’ve ever wondered <strong>how Django handles multiple models in a flexible way</strong>, or how apps like <strong>comments, likes, notifications, or activity logs</strong> work across different models — then <strong>Django ContentType</strong> is the missing piece.</p><p>This article explains <strong>Django ContentType</strong> in a <strong>simple, professional, and real-world way</strong>, even if you’re new to Django.</p><h4><strong>What Is Django ContentType?</strong></h4><p><em>In simple words:</em></p><blockquote><strong><em>ContentType is Django’s way of describing models as data.</em></strong></blockquote><p>Django stores <strong>information about every model</strong> in your project inside a special table called:</p><pre>django_content_type</pre><p>Each row represents:</p><ul><li>An app</li><li>A model inside that app</li></ul><p>This allows Django to <strong>refer to any model dynamically</strong>, without hard-coding it.</p><h4>What Django ContentType Actually Stores</h4><p>Django creates a <strong>database record for every model</strong> in your project.</p><p>Internally, Django sees models like this:</p><pre>(app_label, model_name)</pre><p><em>Example records:</em></p><pre>| app_label | model   |<br>| --------- | ------- |<br>| blog      | post    |<br>| shop      | product |<br>| auth      | user    |</pre><h4>Real-Life Analogy 🧠</h4><p>Imagine a <strong>library system</strong>:</p><ul><li>Books</li><li>Magazines</li><li>Newspapers</li></ul><p>Each has a <strong>different structure</strong>, but the library wants:</p><ul><li>One <strong>review system</strong></li><li>One <strong>comment system</strong></li><li>One <strong>rating system</strong></li></ul><p>Instead of creating:</p><ul><li>BookReview</li><li>MagazineReview</li><li>NewspaperReview</li></ul><p>You create <strong>one Review system</strong> that can work with <strong>any item</strong>.</p><p>👉 This is exactly what <strong>ContentType</strong> does in Django.</p><h4><strong>Why Django ContentType Exists</strong></h4><p>Without ContentType, you would:</p><ul><li>Write duplicate models</li><li>Create multiple foreign keys</li><li>Increase complexity</li></ul><p>With ContentType, Django gives you:</p><ul><li>Reusability</li><li>Flexibility</li><li>Scalable architecture</li></ul><h4>How Django Stores ContentType</h4><p>Every time you create a model, Django automatically registers it.</p><p>Example:</p><pre>from django.contrib.contenttypes.models import ContentType<br><br>ContentType.objects.all()</pre><p>You’ll see data like:</p><pre>| id | app_label | model   |<br>| -- | --------- | ------- |<br>| 1  | auth      | user    |<br>| 2  | blog      | post    |<br>| 3  | shop      | product |</pre><p>This table is the <strong>brain</strong> behind Django’s dynamic relationships.</p><h4>Real-World Use Case: Universal Comment System</h4><p>Let’s build <strong>one comment model</strong> that works for:</p><ul><li>Blog posts</li><li>Products</li><li>Videos</li></ul><h4>Step 1: Import Required Tools</h4><pre>from django.contrib.contenttypes.models import ContentType<br>from django.contrib.contenttypes.fields import GenericForeignKey</pre><h4>Step 2: Create Comment Model</h4><pre>class Comment(models.Model):<br>    user = models.ForeignKey(User, on_delete=models.CASCADE)<br><br>    content_type = models.ForeignKey(<br>        ContentType,<br>        on_delete=models.CASCADE<br>    )<br>    object_id = models.PositiveIntegerField()<br><br>    content_object = GenericForeignKey(<br>        &#39;content_type&#39;,<br>        &#39;object_id&#39;<br>    )<br><br>    text = models.TextField()<br>    created_at = models.DateTimeField(auto_now_add=True)</pre><h4>Step 3: How This Works (Simply)</h4><ul><li>content_type → which model (Post, Product, Video)</li><li>object_id → ID of that object</li><li>content_object → actual object (magic)</li></ul><p>Now one <strong>Comment model</strong> works everywhere.</p><h4>Example in Action (Real Life)</h4><pre>post = BlogPost.objects.get(id=1)<br><br>Comment.objects.create(<br>    user=request.user,<br>    content_object=post,<br>    text=&quot;Great article!&quot;<br>)</pre><p>You didn’t mention:</p><ul><li>BlogPost explicitly</li><li>Any foreign key</li></ul><p>Django handled it dynamically ✔️</p><h4>Where ContentType Is Used in Django Itself</h4><p>Django uses ContentType internally for:</p><ul><li>🔐 Permissions system</li><li>🧠 Admin panel</li><li>🗂 Generic relations</li><li>📊 Activity logs</li><li>🔔 Notifications</li></ul><p>Example:</p><pre>from django.contrib.auth.models import Permission</pre><p>Permissions are linked to <strong>ContentType</strong>, not directly to models.</p><p><strong><em>GenericForeignKey vs ForeignKey:</em></strong></p><pre>| Feature     | ForeignKey       | GenericForeignKey |<br>| ----------- | ---------------- | ----------------- |<br>| Points to   | One model        | Any model         |<br>| Flexible    | ❌ No             | ✅ Yes           |<br>| Performance | Fast             | Slightly slower   |<br>| Use case    | Simple relations | Reusable systems  |</pre><h4>Performance Considerations ⚠️</h4><p>ContentType is powerful, but:</p><ul><li>Avoid overusing it</li><li>Use indexes on object_id</li><li>Prefetch related objects when needed</li></ul><p>For <strong>core relationships</strong>, prefer ForeignKey.<br> For <strong>cross-app reusable features</strong>, use ContentType.</p><h4>Best Use Cases (Recommended)</h4><p>Use ContentType for:</p><ul><li>Comments</li><li>Likes</li><li>Reactions</li><li>Reports</li><li>Notifications</li><li>Activity feeds</li><li>Audit logs</li></ul><p>Avoid it for:</p><ul><li>Core business relations</li><li>High-frequency joins</li><li>Simple one-to-one relationships</li></ul><h4>Mental Model (Easy Remember)</h4><blockquote><strong><em>ForeignKey = Fixed relationship</em></strong><em><br> </em><strong><em>ContentType = Dynamic relationship</em></strong></blockquote><p>If the feature must work across <strong>many models</strong>, ContentType is your friend.</p><p><strong><em>Visual Understanding</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*tsB4KyNO_4usyIsicdE7nQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*R5XXzOJ3_mUaVTYCmJ5IpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*MwRSg0MtYehrLHAKIGycsw.png" /></figure><h4>Final Thoughts</h4><p>Django ContentType is not magic — it’s <strong>smart abstraction</strong>.</p><p>Once you understand it:</p><ul><li>Your architecture becomes cleaner</li><li>Your code becomes reusable</li><li>Your project becomes scalable</li></ul><p>If you’re building <strong>real-world Django apps</strong>, mastering ContentType is a <strong>big step forward</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40361c38c50a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Django Manages Data: Sessions, Tokens, Databases, Cache & Cookies Sessions, Cookies, Cache…]]></title>
            <link>https://medium.com/@sagorrobidush/how-django-manages-data-sessions-tokens-databases-cache-cookies-sessions-cookies-cache-8c004d6bfa52?source=rss-103bcad913c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c004d6bfa52</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Shagor Robidush]]></dc:creator>
            <pubDate>Fri, 16 Jan 2026 19:17:51 GMT</pubDate>
            <atom:updated>2026-01-16T19:34:51.841Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Django Manages Data: Sessions, Tokens, Databases, Cache &amp; Cookies Sessions, Cookies, Cache, Tokens, and Database — The Django Way</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxUDJ-NamEJeBy0a1mSPjg.png" /><figcaption>Django Data Storage Explained</figcaption></figure><p>When building a real-world web application with <strong>Django</strong>, you are not just storing <em>data</em> — you are managing <strong>user identity, performance, persistence, and client memory</strong>.</p><p>Each responsibility in a Django system is handled by a <strong>different tool</strong>, and understanding <em>why</em> and <em>when</em> to use each one is the key to building <strong>secure, scalable, and fast applications</strong>.</p><p>If you are learning <strong>Django or Django REST Framework</strong>, one question always comes up:</p><blockquote>Where does Django store data like login state, user info, cache, and tokens?</blockquote><p>This article explains <strong>ALL Django data storage mechanisms</strong>, from <strong>beginner → advanced → production level</strong>, in <strong>simple words</strong>.</p><h4>First: How Django Thinks About Data</h4><p><em>Django separates data into </em><strong><em>four responsibilities</em></strong><em>:</em></p><pre>| Responsibility | Django Tool       |<br>| -------------- | ----------------- |<br>| Authentication | Sessions / Tokens |<br>| Persistence    | Database          |<br>| Performance    | Cache             |<br>| Client memory  | Cookies           |</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEK0xxeZsjkLJTPiB3eBOA.png" /><figcaption>Sessions, Tokens, Databases, Cache &amp; Cookies</figcaption></figure><h3>Cookies in Django</h3><h4>What is a Cookie in Django?</h4><p>A cookie is <strong>data stored in the user’s browser</strong>, sent with every HTTP request.</p><h4>Client Memory → Cookies</h4><p>Cookies live on the <strong>user’s browser</strong></p><p>They answer:</p><blockquote><strong><em>“What should the browser remember?</em></strong></blockquote><p>Django uses cookies mainly for:</p><ul><li>Session ID</li><li>CSRF token</li><li>Preferences</li></ul><p><strong>Django Cookie Example</strong></p><pre>response.set_cookie(<br>    &quot;theme&quot;,<br>    &quot;dark&quot;,<br>    max_age=3600<br>)</pre><p><strong>Reading Cookie</strong></p><pre>theme = request.COOKIES.get(&quot;theme&quot;)</pre><p><strong>Security Flags (IMPORTANT)</strong></p><pre>SESSION_COOKIE_HTTPONLY = True<br>SESSION_COOKIE_SECURE = True<br>CSRF_COOKIE_SECURE = True</pre><p><strong>Important rules:</strong></p><ul><li>Never store sensitive data</li><li>Size is limited</li><li>Users can delete them</li></ul><p><strong>Cookies are best for:</strong></p><ul><li>Small data</li><li>Non-critical information</li><li>Client-side state</li></ul><h3>Django Sessions (Very Important)</h3><p>A <strong>session stores data on the server</strong>, not in the browser.</p><p>Browser stores only:</p><pre>sessionid = abc123</pre><p>Actual data lives in:</p><ul><li>Database</li><li>Cache</li><li>Redis</li></ul><h4>Django Session Flow</h4><pre>Browser ── sessionid ──▶ Django<br>Django ── session data ──▶ DB / Redis</pre><h4>Using Sessions in Django</h4><pre>request.session[&quot;user_id&quot;] = 25</pre><p>Read session:</p><pre>user_id = request.session.get(&quot;user_id&quot;)</pre><p>Delete session:</p><pre>request.session.flush()</pre><h4>Django Session Backends</h4><pre>SESSION_ENGINE = &quot;django.contrib.sessions.backends.db&quot;</pre><p>Other options:</p><ul><li>cached_db</li><li>cache</li><li>signed_cookies</li></ul><p>🔥 <strong>Production Tip:</strong><br> Use <strong>Redis-based sessions</strong> for speed.</p><h3>Django Authentication (Session-Based)</h3><p>Django sessions store a <strong>session ID</strong> in the browser and keep actual user data on the <strong>server</strong>.</p><p>By default, Django uses <strong>session authentication</strong>.</p><h3>Login Flow</h3><p>1️ User logs in<br> 2️ Django creates session<br> 3️ Session ID stored in cookie<br> 4️ Every request checks session</p><pre>from django.contrib.auth import login<br><br>login(request, user)</pre><p>Check authentication:</p><pre>request.user.is_authenticated</pre><p><strong>Best for:</strong></p><ul><li>Server-rendered apps</li><li>Admin panels</li><li>Secure dashboards</li></ul><p><strong>Why sessions are safe:</strong></p><ul><li>Sensitive data never leaves the server</li><li>Sessions can expire or be revoked instantly</li></ul><h4>JWT Authentication in Django (Modern Way)</h4><p>Tokens are commonly used in <strong>REST APIs and mobile apps</strong>.</p><p><strong>What is JWT?</strong></p><p>JWT is a <strong>stateless authentication system</strong>. Server does NOT store session.</p><p><strong>How it works:</strong></p><ul><li>Server issues a signed token</li><li>Client sends the token with every request</li><li>Server verifies the signature</li></ul><pre>Login → Token issued → Client sends token → Server verifies</pre><p><strong>Example Header</strong></p><pre>Authorization: Bearer &lt;access_token&gt;</pre><p><strong>Django JWT Setup</strong></p><p>Common library:</p><pre>djangorestframework-simplejwt</pre><p><strong>Best Practice Storage</strong></p><pre>| Location        | Safe       |<br>| --------------- | ---------- |<br>| HttpOnly Cookie | Best     |<br>| LocalStorage    | XSS risk |</pre><p><strong>Best for:</strong></p><ul><li>Mobile apps</li><li>SPA (React, Vue, Angular)</li><li>Micro services</li></ul><p><strong>Trade-off:</strong></p><ul><li>Faster and stateless</li><li>Harder to revoke immediately</li></ul><h3>Django Cache (Performance Booster)</h3><blockquote><strong>What is Cache in Django?</strong></blockquote><p>Cache stores <strong>temporary data</strong> to avoid repeated DB queries.</p><blockquote>“How do we make this faster?”</blockquote><p>Caching stores <strong>temporary data</strong> so Django doesn’t repeat expensive work.</p><p><strong>What gets cached?</strong></p><ul><li>API responses</li><li>Query results</li><li>Computed values</li><li>Page fragments</li></ul><p><strong>Common cache back-ends:</strong></p><ul><li>Redis</li><li>Memcached</li><li>Local memory (development)</li></ul><p><strong>Why cache matters:</strong></p><ul><li>Reduces database load</li><li>Improves response time</li><li>Handles high traffic smoothly</li></ul><p><strong>Cache Backends</strong></p><pre>| Backend   | Use         |<br>| --------- | ----------- |<br>| LocMem    | Development |<br>| Redis     | Production  |<br>| Memcached | Large scale |</pre><h4>Django Cache Example</h4><pre>from django.core.cache import cache<br><br>cache.set(&quot;user_25&quot;, data, timeout=300)</pre><p>Get cache:</p><pre>cache.get(&quot;user_25&quot;)</pre><p><strong>Golden Rule:</strong></p><p>Cache data that:</p><ul><li>Is read frequently</li><li>Changes rarely</li></ul><blockquote>Cache is not about storage — it’s about <strong>speed</strong>.</blockquote><h4>Sessions vs Cache (Django)</h4><pre>| Feature       | Session           | Cache      |<br>| ------------- | ----------------- | ---------- |<br>| Purpose       | Auth &amp; user state | Speed      |<br>| Persistence   | Medium            | Short      |<br>| Security      | High              | Medium     |<br>| User-specific | Yes               | Usually No |</pre><h3>Django Database (Source of Truth)</h3><p><strong>What It Means, Why It Matters, and How Django Uses It</strong></p><p>In every real Django application, there is <strong>one place that must always be correct</strong>.</p><p>That place is the <strong>database</strong>.</p><p>Everything else (sessions, cache, cookies, tokens) can be <strong>deleted, expired, or rebuilt</strong> — but the <strong>database must never lie</strong>.</p><p>That’s why we call it:</p><blockquote><strong><em>The Source of Truth</em></strong></blockquote><h4>What Does “Source of Truth” Mean?</h4><p><strong>Source of Truth</strong> means:</p><blockquote><em>The </em><strong><em>final, authoritative, permanent record</em></strong><em> of your application’s data.</em></blockquote><p>If there is ever confusion between:</p><ul><li>cache vs database</li><li>session vs database</li><li>client data vs database</li></ul><p>👉 <strong>The database always wins.</strong></p><h4>Simple Real-World Analogy</h4><p>Think of a <strong>bank system</strong>:</p><pre>| Thing           | Meaning            |<br>| --------------- | ------------------ |<br>| Printed receipt | Cache              |<br>| ATM screen      | Session            |<br>| Mobile app      | Client             |<br>| **Bank ledger** | Database (Truth) |</pre><p>If your app shows $1000, but the bank ledger says $500 →<br> <strong>$500 is the truth.</strong></p><p>Same rule in Django.</p><h4>What Kind of Data Belongs in the Django Database?</h4><p><strong>Data That MUST Be Stored in Database</strong></p><p>These are <strong>non-negotiable</strong>:</p><ul><li>Users</li><li>Password hashes</li><li>Chat messages</li><li>Progress history</li><li>Permissions</li><li>Relationships (FK, M2M)</li></ul><p>If data <strong>must survive server restart</strong>, it belongs in DB.</p><h4>What Should NOT Be the Source of Truth</h4><pre>| Storage        | Why Not         |<br>| -------------- | --------------- |<br>| Cookies        | User can modify |<br>| LocalStorage   | User controlled |<br>| Session        | Can expire      |<br>| Cache (Redis)  | Can be cleared  |<br>| Frontend state | Temporary       |</pre><p>These exist for <strong>speed or convenience</strong>, not truth</p><h4>How Django Treats the Database</h4><p>Django is <strong>database-first</strong>.</p><p><strong>Django Core Assumption:</strong></p><blockquote><em>“If it’s important, store it in the database.”</em></blockquote><p>Everything else is <strong>derived from DB data</strong>.</p><h4>Django ORM: Talking to the Source of Truth</h4><p>Django uses the <strong>ORM (Object Relational Mapper)</strong> to interact with the database safely.</p><p><strong>Example</strong></p><pre>user = User.objects.get(id=25)</pre><p>This means:</p><ul><li>Django asks the database</li><li>Database returns the real value</li><li>Django trusts</li></ul><p><strong>Important:</strong><br> If cache says something else, Django <strong>re-checks DB</strong> when needed.</p><h4>Real Django App Example</h4><p><strong>Example: Game / Study App</strong></p><pre>| Data               | Stored Where  |<br>| ------------------ | ------------- |<br>| User account       | Database      |<br>| Login state        | Session / JWT |<br>| Game progress      | Database      |<br>| Leaderboard        | Cache         |<br>| Theme              | Cookie        |<br>| Temporary UI state | Session       |</pre><h4>Example: User Profile</h4><p>❌ <strong>Wrong thinking</strong></p><pre>Cache is faster → trust cache always</pre><p>✅ <strong>Correct thinking</strong></p><pre>Database = truth<br>Cache = shortcut</pre><p><strong>Correct Flow</strong></p><pre>Request<br> ↓<br>Check Cache<br> ↓<br>If cache missing → query DB<br> ↓<br>Update cache from DB</pre><p>Cache is <strong>rebuilt from database</strong>, not the other way around.</p><h4>Authentication Example (Very Clear)</h4><p><strong>Login System in Django</strong></p><pre>| Component | Role                        |<br>| --------- | --------------------------- |<br>| Database  | Stores user + password hash |<br>| Session   | Tracks logged-in user       |<br>| Cookie    | Stores session ID           |</pre><p>If:</p><ul><li>Session expires ❌</li><li>Cookie deleted ❌</li></ul><h4>Security Best Practices (Django)</h4><p>✅ Use HttpOnly cookies<br> ✅ Rotate JWT tokens<br> ✅ Use Redis for sessions<br> ❌ Never trust client storage<br> ❌ Never store secrets in cookies</p><h4>Golden Rules (Memorize These)</h4><p><strong>Rule 1</strong></p><blockquote><em>If data must not be lost → </em><strong><em>Database</em></strong></blockquote><p><strong>Rule 2</strong></p><blockquote><em>If data must be fast → </em><strong><em>Cache (but backed by DB)</em></strong></blockquote><p><strong>Rule 3</strong></p><blockquote><em>If data is temporary → </em><strong><em>Session</em></strong></blockquote><p><strong>Rule 4</strong></p><blockquote><em>If data is client preference → </em><strong><em>Cookie / Local Storage</em></strong></blockquote><h3>Best Practices</h3><ol><li><strong>Session:</strong> Use for temporary data tied to a device/browser.</li><li><strong>Cookies:</strong> Use for small preferences or tokens; <strong>never store passwords</strong>.</li><li><strong>Cache:</strong> Use for performance optimization of frequently accessed data.</li><li><strong>Database:</strong> Use for persistent, cross-device, and critical user data.</li></ol><p><strong>🔹 Pro Tip for Developers</strong></p><ul><li>Combine storage methods for <strong>maximum efficiency</strong>. Example:</li><li>Store temporary form progress in <strong>session</strong></li><li>Save permanent notes in <strong>database</strong></li><li>Cache frequently accessed pages for <strong>speed</strong></li><li>Use <strong>cookies</strong> for user preferences</li></ul><h4>Production Architecture (Recommended)</h4><pre>Client (Browser)<br>   ↓<br>Nginx<br>   ↓<br>Django + DRF<br>   ↓<br>Redis (Cache + Sessions)<br>   ↓<br>PostgreSQL (Database)</pre><h4>Final Summary</h4><p>If you remember only <strong>ONE diagram</strong>, remember this:</p><pre>Cookie → identifies session<br>Session → authenticates user<br>Cache → speeds things up<br>Database → stores truth</pre><p>Once you understand this, <strong>Django authentication, APIs, Web-sockets, and scaling become easy</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c004d6bfa52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Session Mastery: The Complete Guide (with Real Examples)]]></title>
            <link>https://medium.com/@sagorrobidush/django-session-mastery-the-complete-guide-with-real-examples-ba549db1be72?source=rss-103bcad913c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba549db1be72</guid>
            <dc:creator><![CDATA[Shagor Robidush]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 18:23:41 GMT</pubDate>
            <atom:updated>2025-10-06T18:27:54.968Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Learn how Django Sessions work — configuration, usage, and real-world examples — and become a true master of user state management.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*H0SO2dxANhzk9Ja88Au5Kg.png" /><figcaption>Django Session Guide</figcaption></figure><h3>1. What is a Session?</h3><p>A <strong>session</strong> is a temporary data store Django uses to save user-specific information <strong>on the server</strong>.</p><p>Each visitor gets a unique sessionid (stored as a browser cookie).<br> That ID maps to data stored in Django’s backend — allowing Django to <strong>remember</strong> the user between requests.</p><h3>2. Why Sessions Matter</h3><p>HTTP is <strong>stateless</strong>, meaning every request is independent.<br> Sessions give your app <strong>state</strong> — letting you know <em>who</em> the user is and <em>what</em> they’re doing.</p><h4>Common use cases:</h4><ul><li><strong>Remember logged-in users</strong></li><li><strong>Maintain shopping carts</strong></li><li><strong>Store temporary user preferences</strong></li><li><strong>Save multi-step form progress</strong></li></ul><h3>3. Django Session Configuration</h3><p>Django supports sessions out of the box — just ensure the app and middle-ware are enabled.</p><p>#settings.py</p><pre>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,   # Enable sessions<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br>    &#39;core&#39;,                      # Your app<br>]<br><br>MIDDLEWARE = [<br>    &#39;django.middleware.security.SecurityMiddleware&#39;,<br>    &#39;django.contrib.sessions.middleware.SessionMiddleware&#39;,  # Required<br>    &#39;django.middleware.common.CommonMiddleware&#39;,<br>    &#39;django.middleware.csrf.CsrfViewMiddleware&#39;,<br>    &#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;,<br>    &#39;django.contrib.messages.middleware.MessageMiddleware&#39;,<br>]<br><br># Session config<br>SESSION_ENGINE = &#39;django.contrib.sessions.backends.db&#39;  # Store in DB<br>SESSION_COOKIE_NAME = &#39;sessionid&#39;<br>SESSION_COOKIE_AGE = 1209600  # 2 weeks<br>SESSION_EXPIRE_AT_BROWSER_CLOSE = False</pre><h4><strong>Creating the Project</strong></h4><pre>django-admin startproject session_demo<br>cd session_demo<br>python manage.py startapp core</pre><h4>Session Example Views</h4><p>Let’s build four simple routes to manage session data.</p><p>#core/views.py</p><pre>from django.http import HttpResponse<br><br>def set_session(request):<br>    request.session[&#39;username&#39;] = &#39;Shagor&#39;<br>    request.session[&#39;email&#39;] = &#39;shagor@example.com&#39;<br>    request.session[&#39;is_logged_in&#39;] = True<br>    return HttpResponse(&quot;Session data set successfully!&quot;)<br><br>def get_session(request):<br>    username = request.session.get(&#39;username&#39;, &#39;Guest&#39;)<br>    email = request.session.get(&#39;email&#39;, &#39;N/A&#39;)<br>    is_logged_in = request.session.get(&#39;is_logged_in&#39;, False)<br>    return HttpResponse(f&quot;User: {username} | ✉️ Email: {email} | Logged In: {is_logged_in}&quot;)<br><br>def delete_specific_session(request):<br>    if &#39;email&#39; in request.session:<br>        del request.session[&#39;email&#39;]<br>        return HttpResponse(&quot;Specific session key &#39;email&#39; deleted!&quot;)<br>    else:<br>        return HttpResponse(&quot;No &#39;email&#39; key found in session!&quot;)<br><br>def clear_session(request):<br>    request.session.flush()<br>    return HttpResponse(&quot;All session data cleared and new session created!&quot;)</pre><h4>URL Configuration</h4><p>session_demo/urls.py</p><pre>from django.contrib import admin<br>from django.urls import path<br>from core import views<br><br>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;set/&#39;, views.set_session),<br>    path(&#39;get/&#39;, views.get_session),<br>    path(&#39;delete/&#39;, views.delete_specific_session),<br>    path(&#39;clear/&#39;, views.clear_session),<br>]</pre><h4>Run and Test</h4><pre>python manage.py makemigrations<br>python manage.py migrate<br>python manage.py runserver</pre><p>Then open your browser and visit:-</p><pre>| URL        | Description        | Output                                                                                                   |<br>|------------|--------------------|----------------------------------------------------------------------------------------------------------|<br>| `/set/`    | Store session data | Session data set successfully!                                                                         |<br>| `/get/`    | Retrieve data      | User: Shagor, Email: [shagor@example.com](shagor@example.com) Logged In: True |<br>| `/delete/` | Delete one key     | Specific session key &#39;email&#39; deleted!                                                                 |<br>| `/clear/`  | Clear all sessions | All session data cleared!                                                                             |</pre><h4>Explore Sessions in Django Shell</h4><pre>python manage.py shell</pre><pre>from django.contrib.sessions.models import Session<br><br># List all active sessions<br>Session.objects.all()<br><br># Decode session data<br>s = Session.objects.first()<br>s.get_decoded()</pre><h4>Session Backends (Storage Options)</h4><pre>| Backend                                             | Description                                |<br>| --------------------------------------------------- | ------------------------------------------ |<br>| `&#39;django.contrib.sessions.backends.db&#39;`             | Store in database (default)                |<br>| `&#39;django.contrib.sessions.backends.cache&#39;`          | Store in cache (Redis, Memcached)          |<br>| `&#39;django.contrib.sessions.backends.file&#39;`           | Store in local files                       |<br>| `&#39;django.contrib.sessions.backends.signed_cookies&#39;` | Store encrypted data in the browser cookie |</pre><h4>Real Example: Login &amp; Logout Using Sessions</h4><pre>def login_view(request):<br>    if request.method == &#39;POST&#39;:<br>        username = request.POST.get(&#39;username&#39;)<br>        request.session[&#39;username&#39;] = username<br>        request.session[&#39;is_logged_in&#39;] = True<br>        return HttpResponse(&quot;Logged in successfully!&quot;)<br><br>def logout_view(request):<br>    request.session.flush()<br>    return HttpResponse(&quot;Logged out successfully!&quot;)</pre><h4>Summary</h4><pre>| Task        | Code                             | Description                      |<br>| ----------- | -------------------------------- | -------------------------------- |<br>| Store data  | `request.session[&#39;key&#39;] = value` | Save data                        |<br>| Retrieve    | `request.session.get(&#39;key&#39;)`     | Get data safely                  |<br>| Delete one  | `del request.session[&#39;key&#39;]`     | Remove a key                     |<br>| Clear all   | `request.session.flush()`        | Remove all session data          |<br>| Expiry time | `SESSION_COOKIE_AGE`             | Control how long a session lasts |</pre><h4>Pro Tips</h4><p>— Use sessions for <strong>short-term user data</strong>, not large objects.<br> — Avoid storing <strong>sensitive info</strong> (like passwords).<br> — For high-performance apps, use <strong>Redis or cache backend</strong>.<br> — Use request.session.modified = True if you mutate nested objects.</p><h4>Final Thoughts</h4><p><em>Sessions are one of Django’s most underrated features.<br> They solve one of the web’s oldest problems — maintaining </em><strong><em>state</em></strong><em> in a </em><strong><em>stateless protocol</em></strong><em>.</em></p><p><strong><em>Once you understand how Django sessions work, you’ll have a strong foundation for:</em></strong></p><ul><li>Authentication systems</li><li>Shopping carts</li><li>Personalized user dashboards</li></ul><p><strong><em>Master sessions, and you’re one step closer to mastering Django itself.</em></strong></p><p><strong>Tags:</strong> #django #python #backend #webdevelopment #programming #tutorial</p><p><strong>Author:</strong> Shagor Robidas</p><p><strong>Framework:</strong> Django</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba549db1be72" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>