<?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 Tito Adeoye on Medium]]></title>
        <description><![CDATA[Stories by Tito Adeoye on Medium]]></description>
        <link>https://medium.com/@titoadeoye?source=rss-9b9003e23766------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CfWTb9CIXLPeooh9-c6toA.jpeg</url>
            <title>Stories by Tito Adeoye on Medium</title>
            <link>https://medium.com/@titoadeoye?source=rss-9b9003e23766------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 04:52:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@titoadeoye/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[How to Test Accessibility & Some Common Interview Questions]]></title>
            <link>https://medium.com/@titoadeoye/how-to-test-accessibility-some-common-interview-questions-ba2cee50a179?source=rss-9b9003e23766------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba2cee50a179</guid>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[web-accessibility]]></category>
            <category><![CDATA[wcag]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Tito Adeoye]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 09:01:05 GMT</pubDate>
            <atom:updated>2026-02-23T09:01:05.680Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmu3THCavTBDJ_Fp5PAImw.png" /></figure><p>First, pick a WCAG version and target. This is usually: WCAG <strong>2.1 AA</strong> or <strong>2.2 AA.</strong></p><p>This defines the checklist.</p><p>Then, inventory your UI. List:</p><ul><li>Pages</li><li>Components</li><li>User flows</li><li>States (error, loading, empty, success). Accessibility failures often hide in states.</li></ul><p>And test against success criteria. For each relevant criterion:</p><ul><li>Manually test (keyboard, screen reader, zoom, etc.)</li><li>Use automated tools <em>as support</em></li><li>Document pass/fail</li></ul><p>Example:</p><ul><li><strong>2.1.1 Keyboard (Level A)</strong> — Pass</li><li><strong>1.4.3 Contrast (Level AA)</strong> — Fail</li></ul><p>It’s important to note that automated tools don’t give “levels”. Tools like Lighthouse, axe, etc., detect <em>some</em> failures but cannot test cognitive or contextual criteria or determine conformance level alone.</p><p>A Lighthouse score of 100 does not equate to WCAG AA compliance.</p><p>If you only run Lighthouse/axe, you’re doing <strong>linting</strong>, not testing.</p><p>We’ll split testing into 5 groups:</p><h3>Automated testing</h3><p>This involves the use of automated tools. It’s fast and shallow, providing quick wins. 1.1 What automation catches</p><p>These tools can detect: missing labels, low contrast, missing alt text, invalid ARIA, incorrect roles, and focus traps</p><p>This excludes bad UX, confusing labels, logical focus order issues, poor semantics choices, cognitive overload, or broken keyboard flows</p><p>So automated tests catch ~30% of problems. Manual testing finds the rest.</p><p>Some tools that you should always run:</p><ul><li><strong>ESLint</strong>: A non-negotiable for React teams that can serve as the first line of defense. Install eslint-plugin-jsx-a11y to catch:<br>- div-as-button<br>- missing alt<br>- invalid ARIA<br>- keyboard traps</li><li><strong>axe DevTools</strong>: Unlike ESLint, this is a popular browser extension for React accessibility testing (dev-only). It audits your DOM for common accessibility issues, logs them directly to the console and tells you how to fix them. You can use the Chrome extension or install <a href="https://www.npmjs.com/package/@axe-core/react?activeTab=readme">@axe-core/react</a></li><li><strong>Lighthouse</strong>: . It’s great for quick accessibility checks e.g. color &amp; contrast checks, but terrible for deep validation.</li></ul><h3>Manual testing</h3><p>Here, you must simulate real users. This is where real issues appear.</p><p>If you only do one manual test, do <strong>keyboard testing</strong>. Using only Tab, Shift+Tab, Enter, Space, Esc, and Arrow keys on your keyboard, you must be able to:</p><ul><li>Reach every interactive element</li><li>See focus clearly</li><li>Activate everything</li><li>Open/close modals</li><li>Submit forms</li><li>Navigate entire flows</li></ul><p>If anything requires a mouse. That’s a bug.</p><p>Common bugs you will catch here include div buttons, clickable cards, hidden elements still focusable, focus lost after state update, dropdowns that don’t open via keyboard, etc.</p><p>A great rule of thumb is</p><blockquote><em>If you cannot complete checkout/login/core flow with keyboard only, the feature is not done</em></blockquote><p>Another type of manual testing you should consider is <strong>focus order testing</strong>. The questions that are answered here are “Does focus follow visual order?”, “Does it jump randomly?”, “Does it skip things?”, “Does the DOM order match the visual order?”.</p><p>You tab through slowly to catch these issues. Some causes of broken order include</p><ul><li>cases where tabindex &gt; 0</li><li>portals/modals are mishandled</li><li>absolute positioning</li><li>css reordering (flex reverse / grid)</li></ul><p><strong>Zoom testing:</strong> Terribly underrated in my opinion. WCAG requires readability at 200%. Zoom your browser to 200%, 300%, and 400%. Look for hidden buttons, overlapping UI, horizontal scrolling, clipped text, unusable layouts in general.</p><p><strong>Color &amp; Contrast Testing</strong>: One of the checks in Lighthouse audits. You can also use DevTools contrast checker or axe. Here’s where you check for text contrast, placeholder &amp; button text, or disabled states. For text, try to keep to the 4.5:1 normal, 3:1 large, advice.</p><p><strong>Reduced Motion Testing</strong>: React animations often ignore this — which can literally cause nausea. Enable the “Reduce motion” setting on your browser and check if animations are disabled and transitions are softened.</p><h3>Screen reader testing</h3><p>If screen reader users can’t use your app, nothing else matters. Some popular screen readers to try are NVDA (free; Windows), and VoiceOver (built in; macOS).</p><p>Be prepared to be shocked and maybe a bit embarrassed first time you do this. You’ll totally hear missing labels, “button button button”, unlabeled controls, weird order, and duplicate content.</p><p>That discomfort is exactly why testing matters.</p><p>Navigate by Tab, headings, landmarks, forms, and button. Check that everything has a name, that it makes sense without vision, and that it can be understood without page structure.</p><p><strong>Some React-specific pitfalls include:</strong></p><ul><li><strong>Route changes</strong>: Because React SPAs doesn’t reload pages, screen readers don’t know the page changed. Try to navigate routes, confirm if focus moves to main and if the page title updates. You can fix this with focus management and announcements</li><li><strong>Modals</strong>: Confirm if focus is trapped or restored after close, if Esc actually closes the modals, and if the background is not tabbable. Most homemade modals fail some of these. Leaning into libraries that already have this work done for you makes things easier.</li><li><strong>Dynamic updates</strong>: Test that toast, validation messages, and loading states are announced. If they are not, you can try the aria-live attribute.</li></ul><p><strong>How do you make this work in your engineering process?</strong></p><p>The goal is to automate this process as much as you can. This includes:</p><ul><li><strong>CI</strong>: use eslint-jsx-a11y and axe tests</li><li><strong>PRs</strong>: Make sure that there is a checklist to ensure that keyboards are tested, labels are present, div buttons are absent and that axe is clean (no console warnings)</li><li><strong>Use a design framework</strong>: Design frameworks, like MUI, ship components with documented behavior and baked-in semantics, keyboard support, and ARIA.</li></ul><p>This way 90% of accessibility becomes automatic.</p><p>A sample <strong>audit workflow</strong> that catches almost everything is:</p><ol><li>Run axe/Lighthouse</li><li>Keyboard-only full flow</li><li>Zoom 200–400%</li><li>Screen reader walkthrough</li><li>Contrast scan</li><li>Reduced motion check</li></ol><h3>Accessibility Interview Questions</h3><p>Here are some questions you should attempt to answer for your next interview.</p><ul><li>What is accessibility?</li><li>What is the accessibility tree?</li><li>When should you use ARIA?</li><li>How do you test accessibility?</li><li>What’s a common accessibility mistake?</li></ul><blockquote><em>This article is the last part of a larger accessibility series:</em></blockquote><blockquote><strong>Part 1 :</strong> How accessibility actually works — from the accessibility tree to semantic HTML and keyboard interaction</blockquote><blockquote><strong>Part 2:</strong> ARIA &amp; advanced semantics</blockquote><blockquote><strong>Part 3 (this article):</strong> How to Test Accessibility &amp; Some Common Interview Questions</blockquote><blockquote><em>You can read this start to finish, or jump to the sections most relevant to you.</em></blockquote><h3>Conclusion</h3><p>I wrote this guide not as an accessibility expert, but as an engineer who has learned — often the hard way — that the easiest users to forget are the ones who don’t interact the way we do.</p><p>If you remember only one thing from this article, let it be this:</p><p><strong>Accessibility is not something you add later. It is something you design for first.</strong></p><p>It requires asking questions like:</p><ul><li>What assumptions does this interaction make?</li><li>What happens without a mouse?</li><li>What happens without vision?</li><li>What happens if the user is overwhelmed?</li><li>What happens if focus is lost?</li></ul><p>This mindset will not only make you a <strong>better engineer</strong>, but a more “ethical” one.</p><p>If you’ve been following along since Part 1 — genuinely, nice work. Accessibility is a deep topic, and sticking with it matters.</p><p>If this was helpful, feel free to leave a like ❤️. If it helped you reason more clearly about accessibility, I’d love to hear what clicked💬</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba2cee50a179" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ARIA & Advanced Semantics]]></title>
            <link>https://medium.com/@titoadeoye/aria-advanced-semantics-8740f449321e?source=rss-9b9003e23766------2</link>
            <guid isPermaLink="false">https://medium.com/p/8740f449321e</guid>
            <category><![CDATA[web-accessibility]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[aria]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[wcag]]></category>
            <dc:creator><![CDATA[Tito Adeoye]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 09:01:01 GMT</pubDate>
            <atom:updated>2026-02-18T09:01:01.578Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7cf5Y_iXLcA_uBv3aUxEGQ.png" /></figure><p>ARIA = <strong>Accessible Rich Internet Applications</strong></p><p>ARIA exists because HTML wasn’t designed for modern UIs. We had to build custom widgets (modals, tabs, comboboxes, etc.) and screen readers need to understand those widgets.</p><p>You do not need ARIA for buttons, links, forms, inputs, labels etc. HTML already solves this. You do need it for custom widgets like tabs, accordions, modals and other custom widgets. Even then, instead of building yours from scratch, lean into libraries and/or frameworks that have already done the work for you e.g. MUI, Hero UI.</p><p>ARIA is a <strong>semantic patch layer</strong> that modifies the <strong>accessibility tree only</strong>, not the DOM behavior.</p><p><strong>Example</strong>:</p><pre>&lt;div role=&quot;button&quot;&gt;Save&lt;/div&gt;</pre><p>In the DOM, this is a generic DIV. On the accessibility tree, it is a button, so the screen reader says button. However, it still doesn’t behave like a button. You have to implement the behavior yourself.</p><h3>ARIA Categories</h3><p>ARIA also has 3 types:</p><p><strong>Roles</strong>: what an element is. Includes the following;</p><pre>role=&quot;button&quot;<br>role=&quot;dialog&quot;<br>role=&quot;tab&quot;<br>role=&quot;alert&quot;</pre><p>A div with a button role is still worse than &lt;button&gt; even if it has keyboard handling, states and focus styles</p><p><strong>States</strong>: describes an element’s current condition</p><pre>aria-expanded=&quot;true&quot;<br>aria-checked=&quot;false&quot;<br>aria-disabled=&quot;true&quot;</pre><p><strong>Properties</strong>: describe extra relationships or information</p><pre>aria-label<br>aria-describedby<br>aria-controls<br>aria-labelledby</pre><p>Every interactive element must have an <strong>accessible name</strong> or else they are invisible to screen readers.</p><p>According to priority, screen readers use:</p><ol><li>aria-labelledby</li><li>aria-label</li><li>&lt;label&gt;</li><li>inner text</li><li>alt</li></ol><p>You can see how ARIA overrides everything. This matters because let’s say we have a native button like in the snippet below:</p><pre>&lt;button aria-label=&quot;Delete&quot;&gt;<br>    Delete user<br>&lt;/button&gt;</pre><p>Screen reader says: “Delete”, completely ignoring the inner text.</p><p>Some important ARIA types include:</p><ul><li>aria-hidden: This removes elements from the accessibility tree. It’s great for decorative icons like icon buttons, and duplicate visuals.<br>Look out for focusable elements. They should not be hidden.</li></ul><pre>&lt;button aria-label=&quot;Delete item&quot;&gt;<br>&lt;TrashIcon aria-hidden=&quot;true&quot; /&gt;<br>&lt;/button&gt;</pre><ul><li>aria-expanded: this communicates over a boolean open/closed state. The screen reader reads “collapsed” / “expanded”. It’s great for accordions and dropdowns</li></ul><pre>&lt;button<br>  aria-expanded={open}<br>  aria-controls=&quot;section1&quot;<br>&gt;<br>Details<br>&lt;/button&gt;<br><br>&lt;div id=&quot;section1&quot; hidden={!open}&gt;</pre><ul><li>aria-controls: this links controller to controlled element. It adds relationship context. It can be found on the trigger of a dropdown menu</li></ul><pre>&lt;button aria-controls=&quot;menu&quot; /&gt;<br>&lt;ul id=&quot;menu&quot; /&gt;</pre><ul><li>aria-describedby: this, too, provides extra context.</li></ul><pre>&lt;input aria-describedby=&quot;hint&quot; /&gt;<br>&lt;p id=&quot;hint&quot;&gt;Must be 8 characters&lt;/p&gt;</pre><p>The screen reader reads <strong>“Password edit, must be 8 characters”</strong>. It assists with hints, errors and help text.</p><p>A form error example:</p><pre>&lt;input<br>  aria-invalid={!!error}<br>  aria-describedby=&quot;email-error&quot;<br>/&gt;<br><br>{error &amp;&amp; (<br>    &lt;p id=&quot;email-error&quot;&gt;{error}&lt;/p&gt;<br>)}</pre><ul><li>aria-live: for dynamic async updates. Useful for toast notifications like form success, and async results. Modes include polite (wait) and assertive (interrupt)</li></ul><pre>&lt;div aria-live=&quot;polite&quot;&gt;{message}&lt;/div&gt;</pre><ul><li>aria-label &amp; aria-labelledby: describes the element, providing information on it or it’s relationships</li></ul><pre>&lt;button aria-label=&quot;Close&quot; /&gt;</pre><p>aria-label is good for icon-only buttons. Maybe not so much on long or dynamic content.</p><p>aria-labelledby references real text. This is preferred. It is reusable, translatable, and stays synced.</p><pre>&lt;h2 id=&quot;title&quot;&gt;BillingSettings&lt;/h2&gt;<br>&lt;section aria-labelledby=&quot;title&quot;&gt;<br></pre><blockquote><em>This article is part of a larger accessibility series:</em></blockquote><blockquote><strong>Part 1 :</strong> How accessibility actually works — from the accessibility tree to semantic HTML and keyboard interaction</blockquote><blockquote><strong>Part 2 (this article):</strong> ARIA &amp; advanced semantics</blockquote><blockquote><strong>Part 3:</strong> How to Test Accessibility &amp; Some Common Interview Questions</blockquote><blockquote><em>You can read this start to finish, or jump to the sections most relevant to you.</em></blockquote><blockquote><em>If this was helpful, feel free to leave a like ❤️</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8740f449321e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Accessibility Fundamentals: How the Web Actually Works]]></title>
            <link>https://medium.com/@titoadeoye/web-accessibility-fundamentals-how-the-web-actually-works-4d90ddc0e504?source=rss-9b9003e23766------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d90ddc0e504</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[wcag]]></category>
            <category><![CDATA[web-accessibility]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Tito Adeoye]]></dc:creator>
            <pubDate>Mon, 16 Feb 2026 09:01:01 GMT</pubDate>
            <atom:updated>2026-02-16T09:01:01.918Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LNnoLOC9-u9S8r0njXo4yg.png" /></figure><p>Hello there👋</p><p>This is an engineer’s guide to accessibility — a practical attempt to explain how it actually works, and how to think about it when building real interfaces.</p><p>Most engineers think accessibility is:</p><ul><li>“support screen readers”</li><li>“add aria-labels”</li><li>“run Lighthouse</li></ul><p>That framing is wrong and leads to fragile systems.</p><blockquote><em>This guide is part of a larger accessibility series:</em></blockquote><blockquote><strong>Part 1 (this article):</strong> How accessibility actually works — from the accessibility tree to semantic HTML and keyboard interaction</blockquote><blockquote><strong>Part 2:</strong> ARIA &amp; advanced semantics</blockquote><blockquote><strong>Part 3:</strong> How to Test Accessibility &amp; Some Common Interview Questions</blockquote><blockquote><em>You can read this start to finish, or jump to the sections most relevant to you.</em></blockquote><p>Accessibility = <strong>removing mismatches between how software works and how humans interact with the world</strong>. It is about <strong>ensuring people with disabilities can perceive, understand, navigate, and interact with the web</strong> — <em>without special accommodations</em>.</p><p>Disabilities are <strong>interaction mismatches</strong>, not “defects”:</p><ul><li>Blindness — visual mismatch</li><li>Tremors — precision mismatch</li><li>ADHD — attention mismatch</li><li>Dyslexia — language processing mismatch</li></ul><p>Disabilities include:</p><ul><li>Visual (blindness, low vision, color blindness)</li><li>Auditory (deafness, hard of hearing)</li><li>Motor (limited fine motor control, paralysis, tremors)</li><li>Cognitive (ADHD, dyslexia, memory, processing speed)</li><li>Temporary &amp; situational (broken arm, bright sunlight, bad internet, noise, fatigue)</li></ul><p>Accessibility is <strong>not optional</strong>:</p><ul><li>It’s law in many countries (ADA, EN 301 549, WCAG referenced)</li><li>It improves UX for <em>everyone</em></li><li>It makes your app <strong>more robust, testable, and maintainable</strong></li></ul><p>It is your job as an engineer to <strong>design interaction systems that do not assume a single input method, sense, or cognitive speed.</strong></p><p>Here are some examples of assumptions your system might make and who it excludes:</p><p><strong>Assumption your UI makes </strong>→ <strong>Who it excludes</strong></p><p>“User can see color” → Color-blind users</p><p>“User uses a mouse” → Keyboard-only users</p><p>“User can read small text” → Low-vision users</p><p>“User can process fast animations” → Motion-sensitive users</p><p>“User can remember context” → Cognitive disabilities</p><p>Accessibility work is <strong>finding and removing assumptions</strong>.</p><p><strong>If you’ve ever benefited from</strong> dark mode, captions, keyboard shortcuts, large click targets, you’ve benefited from accessibility.</p><h3>The Accessibility Tree</h3><p>It is important to note that assistive technology (ATs) like screen readers, do not read the DOM directly. They, instead, read the accessibility tree derived from it.</p><p>Unlike the DOM which is created from nodes of HTML elements connected from root to child elements, this tree is derived from <strong>semantic</strong> HTML elements, ARIA roles, accessible names, and states &amp; properties. Two DOMs that look identical visually can be <strong>completely different</strong> to assistive tech.</p><p><strong>An example</strong>:</p><p>Snippet 1</p><pre>&lt;div onClick={submit}&gt;Submit&lt;/div&gt;</pre><p>Snippet 2</p><pre>&lt;button onClick={submit}&gt;Submit&lt;/button&gt;</pre><p>Snippet 1 is Visually identical to Snippet 2 but accessibility is broken</p><p>Same pixels. Different tree. Different user experience.</p><h3>The Foundations (You must internalize these)</h3><h3>WCAG (Web Content Accessibility Guidelines)</h3><p><strong>WCAG</strong> is the global standard for accessibility, focusing on 4 core principles: <strong>perceivable, operable, understandable, and robust</strong> (<strong>POUR</strong>), through specific, testable success criteria across different conformance levels (<strong>A, AA, AAA</strong>).</p><p>WCAG doesn’t teach you how to code. Instead, it defines <strong>non-negotiable truths</strong> your system must satisfy.</p><p>The POUR principles (engineering interpretation)</p><p><strong>Principle </strong>→ <strong>Meaning</strong></p><p><strong>Perceivable</strong> → Users can perceive content (not invisible to any sense)</p><p><strong>Operable</strong> → Users can interact with it</p><p><strong>Understandable</strong> → Users can understand it</p><p><strong>Robust</strong> → Works across assistive technologies</p><h3>Perceivable</h3><p>No critical information is locked behind a single sense. Information must be presented in ways that people can recognize and use, no matter how they consume it.</p><p>This means:</p><ul><li><strong>Don’t rely on a single sense</strong>: If information is only conveyed visually or only through sound, some users will miss it. Some examples of this includes: color alone indicating error (“red text = error”), sound-only alerts, or icon-only buttons without labels. A better alternative is to implement:<br>- Color <strong>+</strong> text or icons<br>- Visual <strong>and</strong> programmatic status messages<br>- Icons with accessible names<br>This aids blind or low vision users, color blind users, deaf or hard-of-hearing users or users in a noisy or low-contrast environments.</li><li><strong>Text alternatives for non-text content</strong>: Anything that isn’t text must have a text equivalent. Examples are:<br>- Images must have alternative text &lt;img src=”cat.jpg” alt=”a cat sitting on a wall” /&gt; or a caption, &lt;figure&gt; &amp; &lt;figcapton&gt;</li></ul><pre>&lt;figure&gt;<br>  &lt;img src=&quot;img.jpg&quot; alt=&quot;my img&quot;/&gt;<br>  &lt;figcaption&gt; Your text &lt;/figcaption&gt;<br>&lt;/figure&gt;</pre><p>- Icons must have accessible names<br>- Charts must have summaries or data tables e.g. A bar chart showing the increase of brainrot in Gen Z from 2015–2025<br>- Videos should have captions or transcripts. An example of this is live captions on Youtube. This bridges the gap for auditory impaired users, and even non-native speakers.</p><ul><li><strong>Sufficient contrast</strong>: Text and interactive elements must stand out from their background. This isn’t only about WCAG ratios or passing audits. It’s about:<br>- Reading in sunlight<br>- Fatigue<br>- Low-quality displays<br>- Aging eyes</li></ul><h3>Operable</h3><p>This means all functionality is available via multiple input methods. An example is the use of keys on the keyboard for navigation. This is especially important for people with motor impairments, who cannot use a mouse, so they are not excluded from accessing your content.</p><blockquote><em>If you can click it, you must be able to tab to it.</em></blockquote><p>Consider:</p><ul><li><strong>Keyboard support:</strong> Allow navigation using tab keys and also ensure to provide visible focus indicators, outlines, to show which element is currently selected and what the current position is e.g. bold outlines</li><li><strong>No time-based traps</strong>: For people with cognitive impairment, who may need more time to read, understand, and complete tasks, as compared to their peers, it is important to avoid time based interactions (e.g. session timeouts, timed responses) and to use easy to comprehend language. If time limits exist, provide: warnings, extensions, and/or, ways to disable them.</li><li><strong>No interaction requiring precision</strong>: Fine motor control cannot be assumed. Avoid designs that require fine motor control, such as:<br>- clicking small icons or precise pointer movements,<br>- drag-only interactions,<br>- hover-only controls.<br>Instead, implement:<br>- Large, forgiving hit areas: An example is making the entire button clickable instead of just an icon or small target area.<br>- Click + keyboard alternatives<br>- Clear spacing between controls</li><li><strong>Avoid physical discomfort or harm:</strong> This includes flashing content, rapid animations, or unexpected motion. We love our animations but, to an extent, let’s ensure that they are subtle, respect reduced motion preferences, and are not likely to induce seizures or dizziness.</li></ul><h3>Understandable</h3><p>The system must behave predictably and communicate clearly. This is not about intelligence or technical skill or even dumbing things down — it’s about <strong>predictability, consistency and removing ambiguity</strong>.</p><ul><li><strong>Readable and clear content</strong>: Use plain language, avoiding unnecessary jargon. Also write clear labels, headings, and instructions, and expand abbreviations on first use. This helps people with cognitive disabilities, neurodivergent users, non-native speakers and users under stress or fatigue (temporary disability)</li><li><strong>Predictable behavior:</strong> Interfaces should never surprise users. Some examples include:<br>- Navigation doesn’t move unexpectedly<br>- A button doesn’t suddenly act like a link<br>- Focus doesn’t jump without user intent<br>- Context doesn’t change on focus alone<br>The WCAG idea is that there be “<em>No unexpected changes in context</em>.”<br>This is especially important for screen readers, keyboard-only users or users with attention or memory challenges.</li><li><strong>Error messages that explain what to fix</strong>: Errors will happen — accessible systems plan for them. Good practice is to:<br>- write clear, specific error messages<br>- explain what went wrong and how to fix it<br>- preserve user input when errors occur<br>- validate inputs early and clearly’<br>A bad example is “<strong>Invalid input</strong>” or “<strong>An error occurred”</strong>. A good one, “<strong>Password must be at least 12 characters and include a number</strong>” or “ <strong>Invalid username/password</strong>”</li><li><strong>Clear labels and instructions:</strong> Every input needs a clear label. Remember: placeholder text is not a label. Also, ensure that instructions should be visible <em>before</em> interaction, not after failure.</li></ul><h3>Robust</h3><p>This is the most <strong>engineering-heavy</strong> part of POUR. The system must survive different technologies and updates i.e. content must be robust enough to be interpreted reliably by a wide variety of user agents, including assistive technologies.</p><p>Robust systems continue to work when browsers update, screen readers change, new assistive tech appears, and the UI is refactored.</p><p>This, of course, translates to:</p><ul><li><strong>Valid HTML:</strong> Use semantic HTML first. These are the backbone of robustness. So, use:<br>&lt;button&gt; instead of clickable &lt;div&gt;<br>&lt;nav&gt;, &lt;main&gt;, &lt;header&gt; <br>- Proper heading hierarchy<br>- Proper nesting<br>- Unique IDs<br>- No duplicate labels<br>- Correct use of aria-labelledby, aria-describedby<br>This matters because browsers already know how to expose these correctly to assistive technologies which already understand them, and if we can minimize our use of ARIA, there’ll be fewer bugs</li><li><strong>Minimal ARIA misuse</strong>: Following the import of semantic HTML, it is also important to note that ARIA must be correct or not used at all. ARIA (<strong>Accessible Rich Internet Applications</strong>) is an acronym that is closely known with Web Accessibility. It is a set of attributes for HTML that defines roles and states for dynamic content, which would make it understandable for assistive technologies. While powerful, it is also dangerous. Some common pitfalls include incorrect roles, missing or wrong ARIA states, and the override of native behavior. An instance, is , the use of a &lt;div&gt;, a non-semantic HTML element, in place of a button.</li></ul><blockquote>Non-semantic just means it doesn’t describe its content or convey any special meaning.</blockquote><p>Div example:</p><pre>&lt;div role=&quot;button&quot; tabindex=&quot;0&quot;&gt;</pre><p>Button example:</p><pre>&lt;button&gt;</pre><p>The former is less robust that the latter, because now <em>you</em> are responsible for: keyboard behavior, focus handling and states (pressed, disabled, etc.)</p><p>Principle<strong> </strong>→ Meaning</p><p><strong>Perceivable </strong>→ Users can perceive content (not invisible to any sense)</p><p><strong>Operable </strong>→ Users can interact with it</p><p><strong>Understandable </strong>→ Users can understand it</p><p><strong>Robust </strong>→ Works across assistive technologies</p><h3>WCAG Levels</h3><p>Each guideline has <strong>levels</strong>:</p><ul><li><strong>A</strong> — bare minimum</li><li><strong>AA</strong> — industry standard (this is what we aim for)</li><li><strong>AAA</strong> — ideal, rarely required</li></ul><blockquote><em>Most companies fail even </em><strong><em>A.</em></strong><em> If you only ever meet WCAG 2.1 AA, you are doing excellent work.</em></blockquote><p>AAA is <strong>aspirational</strong>, not expected for most products. Even WCAG explicitly says:</p><blockquote><em>It is not recommended that Level AAA conformance be required for entire sites.</em></blockquote><h3>WCAG Conformance</h3><p>WCAG conformance is <strong>binary per criterion</strong>. You either <strong>meet it</strong> or <strong>you don’t.</strong></p><p>There is no percentage, average, weighted score</p><p>So, if you fail <strong>one Level A</strong> criterion, you are <strong>not Level A and i</strong>f you meet all Level A, but fail one Level AA, you are <strong>Level A</strong>, not AA</p><p>This is one thing that people can misunderstand. Each level is atomic, indivisible — it cannot be partial.</p><p>For instance, to claim WCAG 2.x AA conformance, a product must:</p><ol><li>Meet <strong>all Level A</strong> success criteria</li><li>Meet <strong>all Level AA</strong> success criteria</li><li>Across <strong>all relevant content and functionality</strong></li></ol><p>Failing <em>any</em> required criterion drops you down a level.</p><p>Each WCAG success criterion lives under <strong>one POUR principle, and h</strong>as <strong>one conformance level</strong></p><p>Example:</p><ul><li><strong>Perceivable — Color Contrast — Level AA</strong></li><li><strong>Operable — Keyboard Access — Level A</strong></li><li><strong>Understandable — Error Identification — Level A</strong></li><li><strong>Robust — Name, Role, Value — Level A</strong></li></ul><p>You meet a criteria across P, O, U, and R. Here’s a reference list of <a href="https://www.w3.org/WAI/WCAG22/quickref/?versions=2.1&amp;showtechniques=124">WCAG success criterion</a>.</p><p>It’s important to note that not every WCAG criterion applies to every product. For instance, when there is no video, caption criteria don’t apply. You only evaluate <strong>applicable criteria</strong>.</p><p>This is why audits involve interpretation, not just tooling.</p><h3>The Curb-curt effect</h3><p>It is a common misconception that accessibility is only for a small percentage of the population. In reality, we all cycle in and out of ‘disability’ depending on our circumstances. A user might have a <strong>permanent</strong> visual impairment, but another might have a <strong>temporary</strong> one — like someone with dilated pupils after an eye exam — while a third faces a <strong>situational</strong> challenge, such as trying to read a smartphone screen in harsh, direct sunlight. This overlap leads to what is called the <strong>‘Curb-Cut Effect’.</strong> A phenomenon that describes how features designed for a marginalized group, like physical curb curs for wheelchairs, end up benefiting a much broader group, like parents with strollers.</p><p>It is the same reason why while closed captions are an aid for the auditory access, it also helps people that are in a noisy or quiet environment.</p><h3>The Fundamentals</h3><h3>Semantic HTML as an API contract (90% of accessibility)</h3><p>Have you ever seen this meme:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*Q0xgDcBkrYMML989-I8wgw.jpeg" /></figure><p>or this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*gILINkK9W-mcu1Mk9pE9mA.jpeg" /></figure><p>Ever heard of <strong>“Div Soup”</strong>? Where Semantic HTML is treated like a suggestion — an environment where buttons aren’t buttons and lists aren’t lists. Everything is just a generic &lt;div&gt; container with a cursor: pointer , and an onClick function.</p><p>I’ve done it, you’ve done it, and we both know it’s lazy coding.</p><p>The cold, hard reality is, of course, that semantic HTML isn’t just about “clean code.” It gives you four critical features for free:</p><ul><li><strong>Keyboard behavior</strong> e.g., Space/Enter to click</li><li><strong>Screen reader meaning,</strong> giving context to users who can’t see the screen</li><li><strong>Focus management</strong> like the logical “tab” order</li><li><strong>Accessibility API compatibility</strong> — how the OS communicates with the browser</li></ul><p>React developers often destroy all four of these with a single, mindless?? &lt;div&gt;. When you replace a &lt;button&gt; with a div, you aren&#39;t just saving a few keystrokes; you&#39;re manually un-building the web.</p><p>90% of accessibility comes from using the right HTML element for the job. HTML elements, inherently, communicate meaning, role, and behavior — not appearance. That’s CSS.</p><p>When you’re choosing an element, you are immediately communicating what it is supposed to represent, it’s behavior e.g. a button is supposed to be pressable (onClick), keyboard interactions, and screen reader announcements.</p><p>Divs are especially dangerous in React cause it lets you do this:</p><pre>&lt;div onClick={submit} className=&quot;button&quot;&gt;<br>  Submit<br>&lt;/div&gt;</pre><p>It looks like a button, but accessibility-wise, it:</p><ul><li>is not focusable</li><li>has no keyboard support</li><li>has no role</li><li>has no accessible name</li><li>has no state</li><li>is invisible to assistive tech</li></ul><p>That’s a fake button. In comparison, &lt;button&gt; is:</p><ul><li>Focusable via keyboard</li><li>Activated with Enter <strong>and</strong> Space</li><li>Announces as “button”</li><li>Has disabled state</li><li>Works in forms</li><li>Handles ARIA states correctly</li></ul><pre>&lt;button onClick={submit}&gt;Submit&lt;/button&gt;</pre><p>&lt;div&gt; does nothing, means nothing, and announces nothing.</p><p>If you don’t use native elements, you take full responsibility for keyboard handling, focus management, and other native behavior.</p><h3>Things to look out for</h3><h3>Utilize landmark Elements (Page-Level Semantics)</h3><p>Landmarks allow users to jump around the page instantly. Some essential landmarks:</p><pre>&lt;header&gt;<br>&lt;nav&gt;<br>&lt;main&gt;<br>&lt;footer&gt;<br>&lt;aside&gt;</pre><p>Not having to depend on linear reading means screen reader users can press a single key to jump to main content, skip navigation, or navigate between regions. Without landmarks, they have to tab through everything.</p><p>&lt;main&gt; is <strong>non-optional.</strong> It represents the unique content**.** Every page must have <strong>one</strong> &lt;main&gt;. It should not be inside header, nav, or footer.</p><p>A layout example:</p><pre>function Layout({ children }) {<br>  return (<br>    &lt;&gt;<br>      &lt;Header /&gt;<br>      &lt;Nav /&gt;<br>      &lt;main id=&quot;main&quot;&gt;<br>        {children}<br>      &lt;/main&gt;<br>      &lt;Footer /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h3>Let headings define the document outline</h3><p>Ensure headings are hierarchical and act as navigation anchors as screen readers users navigate by headings.</p><pre>&lt;div className=&quot;text-xl font-bold&quot;&gt;Settings&lt;/div&gt; // bad❌<br>&lt;h2&gt;Settings&lt;/h2&gt; // great stuff ✅</pre><p>Try to have one &lt;h1&gt; per page (generally), never skip levels (h1 → h3 ) and try not to style headings just for size.</p><h3>Understand the distinction between buttons and links</h3><p>A button, &lt;button&gt;, performs an action, a link, &lt;a&gt;, navigates somewhere.</p><pre>&lt;a onClick={save}&gt;Save&lt;/a&gt; // bad❌<br>&lt;button onClick={save}&gt;Save&lt;/button&gt; // great stuff ✅</pre><p>The former is the wrong role and screen readers announces: “Open, link”, but it doesn’t go anywhere.</p><h3>Use &lt;nav&gt; only for major navigation blocks</h3><pre>&lt;!-- Great✅ --&gt;<br>&lt;nav&gt;<br>&lt;ul&gt;<br>&lt;li&gt;&lt;ahref=&quot;/dashboard&quot;&gt;Dashboard&lt;/a&gt;&lt;/li&gt;<br>&lt;li&gt;&lt;ahref=&quot;/settings&quot;&gt;Settings&lt;/a&gt;&lt;/li&gt;<br>&lt;/ul&gt;<br>&lt;/nav&gt;<br><br>&lt;!-- Bad --&gt;<br>&lt;div class=&quot;nav&quot;&gt;</pre><p>Screen readers announce will announce something akin to: “Navigation region”. This gives users orientation.</p><h3>Lists Are Semantic Structures</h3><p>If it’s a list visually, it must be a list semantically. Screen readers announce list length, users know where they are, and they get faster navigation.</p><pre>// bad ❌<br>&lt;div&gt;<br>&lt;div&gt;Item 1&lt;/div&gt;<br>&lt;div&gt;Item 2&lt;/div&gt;<br>&lt;/div&gt;<br><br>// good ✅<br>&lt;ul&gt;<br>&lt;li&gt;Item 1&lt;/li&gt;<br>&lt;li&gt;Item 2&lt;/li&gt;<br>&lt;/ul&gt;</pre><h3>Fieldsets &amp; Legends</h3><p>We tend to ignore or forget these elements. Try to group related controls:</p><pre>&lt;fieldset&gt;<br>&lt;legend&gt;Notification preferences&lt;/legend&gt;<br>&lt;label&gt;<br>&lt;input type=&quot;checkbox&quot; /&gt;<br>    Email<br>&lt;/label&gt;<br>&lt;label&gt;<br>&lt;input type=&quot;checkbox&quot; /&gt;<br>    SMS<br>&lt;/label&gt;<br>&lt;/fieldset&gt;</pre><p>Screen reader reads: “<strong>Notification preferences group</strong>”, giving instant context.</p><h3>Tables: Use Only for Data</h3><p>Tables are for <strong>tabular data</strong>, not layout. This allows screen readers announce row/column relationships. Also, users can navigate cell-by-cell</p><pre>&lt;table&gt;<br> &lt;caption&gt;User statistics&lt;/caption&gt;<br> <br> &lt;thead&gt;<br>  &lt;tr&gt;<br>   &lt;th scope=&quot;col&quot;&gt;Name&lt;/th&gt;<br>   &lt;th scope=&quot;col&quot;&gt;Logins&lt;/th&gt;<br>  &lt;/tr&gt;<br> &lt;/thead&gt;<br> <br> &lt;tbody&gt;<br>  &lt;tr&gt;<br>   &lt;td&gt;Tito&lt;/td&gt;<br>   &lt;td&gt;42&lt;/td&gt;<br>  &lt;/tr&gt;<br> &lt;/tbody&gt;<br>&lt;/table&gt;</pre><h3>Fragment overload</h3><p>Fragments remove wrapper semantics. Try not to do this:</p><pre>/* This could easily be a section element */<br>&lt;&gt; <br>  &lt;div&gt;Title&lt;/div&gt;<br>  &lt;div&gt;Content&lt;/div&gt;<br>&lt;/&gt;</pre><h3>Forms</h3><p>First, labels,&lt;label&gt; , are not optional</p><pre>&lt;!-- bad --&gt;<br>&lt;input placeholder=&quot;Email&quot; /&gt;<br><br>&lt;!-- good --&gt;<br>&lt;label htmlFor=&quot;email&quot;&gt;Email&lt;/label&gt;<br>&lt;inputid=&quot;email&quot;type=&quot;email&quot; /&gt;</pre><p>A common mistake is replacing labels with placeholders. However, it is important to note that placeholders disappear on input, aren’t read reliably, and fail contrast requirements, so they cannot be announced.</p><p>Also, ensure errors are announced and are programmatically linked</p><pre>&lt;input aria-invalid=&quot;true&quot; aria-describedby=&quot;email-error&quot; /&gt;<br>&lt;p id=&quot;email-error&quot;&gt;Invalid email&lt;/p&gt;</pre><p>Do not rely on * for required fields</p><pre>&lt;label htmlFor=&quot;name&quot;&gt;<br>Name &lt;span aria-hidden=&quot;true&quot;&gt;*&lt;/span&gt;<br>&lt;/label&gt;<br>&lt;input id=&quot;name&quot; aria-required=&quot;true&quot; required /&gt;</pre><h3>Keyboard Accessibility &amp; Focus</h3><p>Remember, the <strong>O (Operable)</strong> rule. Keyboard-only users are not edge cases. There are blind, motor-impaired, and power users. If it can’t be used <strong>with a keyboard only with commands like Tab / Shift+Tab / Enter / Space / Escape</strong>, it’s broken.</p><p>You must also ensure that everything interactive must be focusable, and the focus order must be visible and logical.</p><p>Some default focusable elements include:</p><ul><li>button</li><li>a[href]</li><li>input, select, textarea</li><li>[tabindex=&quot;0&quot;]: this makes HTML elements focusable. Examples of tabindex values include:</li></ul><pre>tabindex=&quot;-1&quot;   // removes from the tab index. Focusable via JS only (modals, skip links)<br>tabindex=&quot;0&quot;    // include in tab order<br>tabindex=&quot;1+&quot;   // ❌ Dont do this. (breaks natural order)</pre><p>tabindex=&quot;-1&quot;: removes the element from the tab index. Focusable via JS only (modals, skip links)</p><p>tabindex=&quot;0&quot;: this inserts an element into the natural tab order, by its position in the HTML source code. It is particularly useful for making non-interactive elements e.g.&lt;div&gt; focusable and accessible via the Tab key, often when creating custom interactive components.</p><p>tabindex=”1” or tabindex=”2” forces an explicit order to the focusable elements</p><pre>tabindex=&quot;1&quot; -&gt; tabindex=&quot;2&quot; -&gt; tabindex=&quot;3&quot; -&gt; tabindex=&quot;0&quot; -&gt; no tab index</pre><p>DOM order must also always reflect visual order. Focus, like screen readers, follows DOM order unless you interfere. Therefore, changes like the example beneath where visual reordering happens without DOM order change, can cause confusion</p><pre>flex-direction: row-reverse;</pre><h3>Focus</h3><p>Never remove focus outlines globally:</p><pre>&lt;/* bad */&gt;<br>*:focus {<br>outline: none;<br>}</pre><pre>&lt;/* good*/&gt;<br>:focus-visible {<br>	outline:2px solid#4f46e5;<br>}</pre><p>Focus must also be <strong>visible, high contrast</strong>, and <strong>persistent. Don’t</strong> globally disable outlines.</p><pre>&lt;/* good🟢 */&gt;<br>:focus-visible {<br>  outline:2px solidvar(--focus-color); &lt;/* high contrast focus color */&gt;<br>  outline-offset:2px;<br>}</pre><h3>ARIA</h3><p>This was placed last for a reason. ARIA (<strong>Accessible Rich Internet Applications</strong>) should be used only when semantic HTML cannot express the interaction.</p><h3>Conclusion</h3><p>Understanding accessibility starts with how the browser and assistive technologies interpret your code. Understanding that foundation makes the rest easier, and maybe a bit harder, in the right ways.</p><p>In the next part, we’ll look at ARIA and advanced semantics.</p><p>Toodles💚</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d90ddc0e504" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“It Works on My Machine” is a Lie: A Real-World Docker Survival Guide]]></title>
            <link>https://medium.com/@titoadeoye/it-works-on-my-machine-is-a-lie-a-real-world-docker-survival-guide-0a8ab9a986b2?source=rss-9b9003e23766------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a8ab9a986b2</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Tito Adeoye]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 08:01:01 GMT</pubDate>
            <atom:updated>2026-03-25T17:53:32.748Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker for Real Projects: Learning Docker the Messy Way</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Evi0VXYcI91k6D5wJX_IOg.png" /></figure><p>Hello there👋</p><p>This will not be the typical 20 minute soul-sucking Docker dissertation. The goal is to get your app from “works on my machine” to publicly accessible over HTTPS using Docker.</p><p>This article is not a deep dive into the totality of what Docker does, or all the commands available to you, or defining its limitations. It’s just to get your front and/or backend app running.</p><p>Here’s to <strong>not</strong> demystifying (lmao such a chatgpt word) the blue whale🥂</p><p><strong>Fair Warning:</strong> I’m not writing this from a “perfect” state where everything already works. I’m building this <em>with</em> you. When we hit a wall (and we will), we’re going to understand the problem and fix it together in real-time. This isn’t a pre-packaged article.</p><h3>A quick intro</h3><blockquote><em>Wikipedia: </em><strong>Docker</strong><em> is a set of products that uses operating-system-level virtualization to deliver software in packages called containers</em></blockquote><p>Basically, it is just packaging software + its environment (OS, libraries, dependencies) so it runs consistently anywhere. You can setup your frontend or backend app off of <strong>Docker Images</strong>, which are simply templates that define your application and its environment, and then run instances of those images called <strong>Containers</strong>. This is where your app actually lives and runs.</p><p>It is important to note that Docker Images are meant to be read-only templates. You don’t modify them directly — you use them to create containers, which is where your app actually runs and changes happen. They include <strong>base images</strong> like python, node, ubuntu, and the famous hello-world, among others. These base images are templates of language runtimes or OS’s. Then there are <strong>out of the box images</strong> that contain services or applications that can be used immediately like redis, postgres, mysql.</p><h3>Install the app</h3><p>First thing you want to do is install Docker Desktop (<a href="https://docs.docker.com/desktop/setup/install/windows-install/">https://docs.docker.com/desktop/setup/install/windows-install/</a>). While we would be working a lot with the terminal, I’d like if we could visualize our Images, Containers, and their states.</p><p>This article assumes your machine supports virtualization (most modern PCs do). If Docker Desktop installs successfully, you’re good.</p><h3>Backend Setup</h3><p>Now let’s package a Django app into a Docker Image. We already have a ready to use app from one of our earlier courses so we’re just going to use that. You can clone it <a href="https://github.com/titoadeoye/tailors_kit">here</a></p><p>To build an image in Docker, we utilize a Dockerfile. A Dockerfile is just a <strong>text file</strong> with instructions that tell Docker <strong>how to build an image</strong>. It’s us telling Docker how to build our application’s environment from scratch using a template Image.</p><p>The typical flow is you write a Dockerfile<strong>,</strong> Docker reads it <strong>top to bottom, using</strong> each instruction to create a <strong>layer, all</strong> layers are combined into a <strong>Docker image which</strong> you run to create a <strong>container</strong> that can be accessed at port:xxxx.</p><p>First, lets do a quick check on our Django app. Run python manage.py runserver, paste this: <a href="http://127.0.0.1:8000/api/customers/">http://127.0.0.1:8000/api/customers/</a> on your address bar and confirm you can see this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rd0hXbe4jh8PjiPX.png" /></figure><p>If you can’t see it, you either cloned and setup the repo incorrectly, you’re using your own app (which is fine), or you need to reread our setup <a href="https://titoadeoye.hashnode.dev/putting-django-into-practice-a-stepbystep-backend-project">article</a>🌚<br>If you’re genuinely stuck, fix that first before we Docker-ize anything.</p><p>Now create a Dockerfile in the root of your project.</p><pre>FROM python:3.11-slim<br><br>WORKDIR /app<br><br>COPY requirements.txt .<br><br>RUN pip install --no-cache-dir -r requirements.txt<br><br>COPY . .<br><br>EXPOSE 8000<br><br>CMD [&quot;python&quot;, &quot;manage.py&quot;, &quot;runserver&quot;, &quot;0.0.0.0:8000&quot;]</pre><p>Each line is an instruction.</p><p>FROM python:3.11-slim: Base Linux image with python 3.11 installed. No need to install python or pip or reinvent the wheel.</p><p>WORKDIR /app: This command tells Docker to set the working directory <em>inside the container</em>. Every command that follows runs as if we had already done:</p><pre>cd /app</pre><p>COPY requirements.txt .: COPY copies files from the host (your local machine) to the container. This entire command copies requirements.txt from your local machine into the container.</p><p>You do this <em>before</em> copying the entire project because Docker caches <strong>layers</strong>, and your dependencies change way less often than your code. This makes rebuilds much faster.</p><p>RUN pip install --no-cache-dir -r requirements.txt: This runs <strong>at build time</strong>. Docker spins up a temporary container, installs your dependencies, saves the result as a layer, and then throws that container away like it never existed.</p><p>COPY . .: copies your source code to your container. At this point, your code is officially <strong>inside the image.</strong> It no longer cares about your laptop.</p><p>EXPOSE 8000:This is documentation not networking. Docker doesn’t actually open a port. It’s more like it’s saying: “This app expects traffic on port 8000”. The <strong>actual</strong> connection happens later in the terminal when we run the container.</p><h3>Docker Layers</h3><p>I’ve mentioned layers a couple of times. A <strong>Docker layer</strong> is an <strong>immutable filesystem snapshot</strong> created by <strong>each instruction in a Dockerfile</strong>. It’s basically the difference produced by one step in the build. Docker stacks these layers on top of each other to form an image.</p><p>After FROM python:3.11-slim runs, the layer generated contains Base OS + Python.</p><p>After WORKDIR /app, the layer generated contains Metadata.</p><p>After COPY requirements.txt ., the layer generated contains that file.</p><p>After RUN pip install ..., the layer generated contains installed Python packages</p><p>After COPY . ., the layer generated contains your source code.</p><p>Layers are read-only and never change. Docker caches and reuses layers, creating a new one when something changes.</p><p>A new layer is not created if the instruction is the same or the inputs to that instruction haven’t changed. For instance:</p><ul><li>If you change app code, only COPY . . layer is rebuilt</li><li>If you change requirements.txt, dependency layer rebuilt</li></ul><p>This is why Docker builds can be fast <em>or</em> painfully slow. Good layer ordering means fast rebuilds. Bad layer ordering could mean reinstalling dependencies every time.</p><p>Multiple images can also reuse or share the same layers. For instance, 10 images can be based on python:3.11-slim.That base layer exists <strong>once</strong> on disk. Huge space saver.</p><p>Moving on…</p><p>Now that we know what every command is, and what they mean, let’s do the thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/0*guiWvsH68CKwhNmR.gif" /></figure><p>From the root of your project, run:</p><pre>docker build -t tailors_kit .</pre><p>This reads the Dockerfile, executes it top to bottom, and produces a <strong>Docker image</strong> called tailors_kit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UfysCyG0mCkB94Gb.png" /></figure><p>Anddddd you probably hit this psycopg error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9QDsR5-rAL7yJd1v.png" /></figure><p>That’s because our base image only has python installed and knows nothing about our PostgreSQL setup, unlike our local machine. Specifically, it’s missing pg_config.</p><p>At least, we now know for a fact it’s truly isolated.</p><p>There are 3 ways we can fix this:</p><ol><li>use psycopg2-binary with its precompiled libraries✅</li><li>install system dependencies before pip runs in a separate instruction. Because psycopg2 is compiling C code, we would need PostgreSQL dev headers, and a compiler. Production friendly unlike the first option.</li><li>have multi-stage builds, where you compile psycopg2 in a builder image and copy only the compiled artifacts into a slim runtime image.</li></ol><p>Bet you know which one I picked😁</p><p>After uninstalling psycog2, installing psycopg2-binary, and running docker build again, you should have this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t_KNDag2aoIPatrz.png" /></figure><p>You can confirm on your terminal with the docker images which lists out all your images:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q1Bw8fCAGJ9JWoKN.png" /></figure><p>On the Docker Desktop GUI, you can view it under local images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GLyZsR9Loqt-jv7o.png" /></figure><p>Now let’s turn that image into a <strong>running container</strong>.</p><pre>docker run -p 8000:8000 tailors_kit</pre><p>This maps Port 8000 on your machine to port 8000 inside the container.</p><blockquote><strong><em>-p stands for Publish</em></strong><em> (or Port).</em></blockquote><blockquote><em>By default, all the ports in your docker container are inaccessible. Even if your Django or Redis app is running inside, you can’t get to it from your laptop’s browser because the container is isolated.</em></blockquote><blockquote><em>The </em><em>-p flag acts like a </em><strong><em>bridge</em></strong><em> between your computer and the container.</em></blockquote><blockquote><strong><em>Host Port</em></strong><em> (Left) — The port you type into your browser or app (e.g., </em><a href="http://localhost:6379/"><em>localhost:8000</em></a><em>).</em></blockquote><blockquote><strong><em>Container Port</em></strong><em> (Right) — The port the service is actually “listening” on.</em></blockquote><p>Open your browser and once again, go to localhost:8000</p><p>If you can see the Django GUI, congratulations, your app is now running in a container and does not care about your operating system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*TiZAv0JjIdJiab0b.gif" /></figure><p>But if you’re working off my clone, you should get an error like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VtfqhbXO8I2GB9f5.png" /></figure><p>This means Django is trying to access our Postgres host at :5432 and failing at it cause it doesn’t exist in our container in /app.</p><p><strong>Each container has its own network namespace.</strong></p><p>So 127.0.0.1 inside a container is not equal to your machine.</p><p>One solution, really a hack, is to connect to host Postgres using Docker’s magic DNS name: HOST = &quot;host.docker.internal&quot; but that’ll be a headache later on.</p><p>Instead, let’s follow the <strong>container-native</strong> approach, where we run Django in one container, Postgres in another container, and <strong>both on the same Docker network</strong>.</p><p>Each container talks to the other via <strong>service names</strong>, not localhost. This is the same way our frontend container will be able to talk to our backend container later on using it’s service name.</p><p>This is where <strong>Docker Compose</strong> comes in. It is used for running multi-container applications.</p><p>The database host becomes:</p><pre>HOST = &quot;postgres&quot;<br><br># mental model; where db is the DB_HOST environment variable<br>[Django container] → db:5432 → [Postgres container]</pre><p>or in prod:</p><pre>[Django container] → db.render.com → [Managed Postgres]</pre><p>Not localhost.</p><p><strong>Compose </strong>gives us one private network for our services (containers) to join, DNS between our containers (hostnames), startup ordering, and one command to run everything.</p><p>Compose is great for orchestration for local dev on a single host, as compared to Kubernetes, which is better for orchestration of multiple containers across multiple machines.</p><p>In your project root:</p><pre># docker-compose.yml<br><br>version: &quot;3.9&quot; # obsolete in docker compose v2<br><br>services:<br>  web:<br>    build: .<br>    ports:<br>      - &quot;8000:8000&quot;<br>    depends_on:<br>      - db<br>    environment:<br>      - DB_NAME=postgres<br>      - DB_USER=postgres<br>      - DB_PASSWORD=postgres<br>      - DB_HOST=db<br>      - DB_PORT=5432<br><br>  db:<br>    image: postgres:16 # one of the ready to use images. Not a base image<br>    environment:<br>      - POSTGRES_DB=postgres<br>      - POSTGRES_USER=postgres<br>      - POSTGRES_PASSWORD=postgres<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br><br>volumes:<br>  postgres_data:</pre><p>Now we have two containers on one network: web and db.</p><p>web, of course, runs Django, exposes port 8000 to your host and connect to postgres via db:5432.</p><p>The db service is named after your DB_HOST and is the official postgres image that stores data in a volume. It’s not exposed to your host.</p><p>depends_on: -db , means that before django runs and is accessible, the db container should be started first. Not that it waits until the database is ready to accept connections. Django might race it but no worries, Postgres usually starts fast.</p><p>Confirm that in your source code, in settings.py, Django knows what to look for, for your variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XSNHJ6XKmFM4H_qe.png" /></figure><p>Now let’s run it:</p><pre>docker compose up --build</pre><p>You should be able to see the containers get created and named: db-1, web-1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2TlSUusfu39lDw4s.png" /></figure><p>If you remember our layers section, you can also see how its accessing <strong>CACHED </strong>layers for container setup.</p><p>And you immediately have both services running and waiting for requests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QgcejytokYtM05Zr.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vO4MjzgPCkHZIOm7.png" /></figure><p>Now Django is connected to postgres successfully, and if you try to access: <a href="http://127.0.0.1:8000/api/customers/">http://127.0.0.1:8000/api/customers/</a>, and have been following this article to the letter, you’d most likely get this:</p><blockquote><em>“django_session” does not exist</em></blockquote><p>at the end of a very long stack trace.</p><p>Don’t panic. It’s actually a win. It means Django <strong>found</strong> the database in our container, but discovered it was empty — no Django tables. We need to migrate. Open a new terminal tab and run:</p><pre>docker compose exec web python manage.py migrate</pre><p>Here, you simply execute, exec, a command e.g. python manage.py migrate, in your target container, web</p><blockquote><strong><em>Note</em></strong><em>: We use </em><em>exec here because the container is already running</em></blockquote><pre>docker ps -a # to list your containers</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aKdRv2weuvv0Pdb1.png" /></figure><pre>docker compose run web python manage.py migrate</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rZ9ppwpb1CvHCtK3.png" /></figure><blockquote><strong><em>Nuance:</em></strong><em> </em><em>run starts a </em><strong><em>new</em></strong><em> container to do the task. </em><em>exec runs the command in a container that is </em><strong><em>already running</em></strong><em> (faster)</em></blockquote><p>Create a super user, do all of that what’s needed, by simply running the command on the web container</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8G2J4x5i_wvyDKTR.png" /></figure><p>Now let’s run it again:</p><pre>docker compose up --build</pre><p>And that’s it🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GZXUKiPL605F-9Rh.png" /></figure><p>If you want open a psql shell directly on the postgres container:</p><pre>docker compose exec db psql -U postgres<br>\dt</pre><p>You should see:</p><pre>auth_user<br>django_migrations<br>django_session<br>...</pre><p>This confirms the tables are actually there.</p><p>While Docker volumes are <strong>not inherently bad for production</strong>, they are <strong>often the wrong tool</strong> for app databases. They are great for local development, or single node self-managed servers but can be terrible when containers are ephemeral or nodes can disappear.</p><p>Your VM dies or is corrupted, your data is gone.</p><p>Later on, when we host on Render, we will be connecting to a Postgres DB managed by Render, but the local setup ensures our code is ‘Cloud Ready’.</p><p>So, don’t delete your Dockerfile</p><p>Now, let’s make it publicly accessible.</p><p>We will be using Render. Why? Because we can.</p><p>Because we are moving to public accessibility, we will be splitting our services this way on Render:</p><ul><li>Backend (Django)</li><li>Frontend (React/Next)</li><li>Managed Postgres (Render DB)</li></ul><p>This ensures we are production-ready, have safe DB persistence, and our frontend/backends scale independently.</p><p>We can still use docker compose for local development to spin up multiple local containers.</p><p>Compose is your <strong>dev tool</strong>. Render is your <strong>production deployment</strong>. They’re not mutually exclusive.</p><h3>Render Setup</h3><p>Render <strong>always</strong> runs containers. The only real question is: <strong>who defines the image — you, or the platform?</strong></p><p>With the <strong>Native Python Web Service</strong>, Render builds the image for you. You connect a repo, Render detects a Python service, and then uses its own buildpack-like system to:</p><ul><li>pick a base image</li><li>install Python</li><li>install deps</li><li>inject your code</li></ul><p>You never see or control the Dockerfile. In this mode, the image exists, you just don’t own or version it. It’s just an implementation detail.</p><p>There is also <strong>Docker Web Service, where Render uses <em>your</em> Dockerfile to</strong> produce an image (docker build). That image is stored in <strong>Render’s internal registry</strong> and it runs <em>that exact image.</em></p><p>In this mode, our Dockerfile is the source of truth. You control base image, system deps, build steps, CMD/ENTRYPOINT. You basically make Render “<strong>managed Docker hosting</strong>”.</p><p>Using DWS can sometimes be overkill — especially for solo projects, low traffic apps, or services without strict rollback or portability requirements. But there are cases where you don’t want to be limited to only what Render’s native runtime supports.</p><p>Docker lets you install OS packages, control glibc vs musl, pin OpenSSL versions, run sidecars, and customize entrypoints.</p><p>Docker services can also handle multiservice/non-HTTPS workloads including workers, consumers, schedulers, and unusual protocols. Native runtimes, however, are opinionated toward web apps.</p><p>Also, it’s portable. If Render suddenly doubles its prices tomorrow, you don’t have to change a single line of code. You just take that same image URL (yourusername/django-app:v1) and plug it into AWS or DigitalOcean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*nKA0VvFZ_hAORmqo.gif" /></figure><p>The first way is easy, straightforward. You probably already have this down. That’s why we are going to do it, the ”hard” way. Why? Because we can.</p><blockquote><em>Docker Web Services aren’t required to run apps on Render, but they’re useful when you want the container image itself — not source code — to be the unit of deployment.</em></blockquote><h3>Docker Web Service On Render</h3><p>Our goal is to run a pre-built image (instead of building it from your GitHub code).</p><p>First, Render needs to be able to download your image from somewhere. The easiest place is <strong>Docker Hub</strong>, a container registry for storing, managing, and sharing Docker images.</p><p>To do this, run these commands:</p><pre># for authentication<br>docker login <br><br># tag your image: Docker needs the name to match your repository<br>docker tag tailors_kit username/tailors_kit # replace username with your docker username e.g tito<br><br># push to DockerHub<br>docker push tycodes/tailors_kit</pre><p>Confirm that on the Docker Desktop GUI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tOAGoUy95Q4ZzPC-.png" /></figure><p>Then, create a free Render account, click on ‘<strong>New</strong>’ and select ‘<strong>Web Service</strong>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dKrENhgs7Ix1ltrp.png" /></figure><p>Connect your docker image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pFSuJAVMQdJWNdJl.png" /></figure><p>We know Render’s DWS runs our image, because when we check the logs, we see the famous Postgres error when Django tries to connect to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3vhyvyt1H5N0SHoe.png" /></figure><p>To setup our postgres DB on Render, click on ‘<strong>New</strong>’ again and select ‘<strong>Postgres</strong>’.</p><p>Fill the form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cuOJstKk35NEjqg6.png" /></figure><p>Submit it and you can view the details on your new Render Postgres DB.</p><p>Once it’s created, look for the <strong>Internal Database URL</strong>. It will look something like this: <a href="/service/mailto:password@dpg-xxxxxx-a.oregon-postgres.render.com">postgres://user:password@dpg-xxxxxx-a.oregon-postgres.render.com/dbname</a></p><p>Now we need to copy over our environment tables including DB_HOST, which looks something like dpg-xxxxxx-a.oregon-postgres.render.com. DB_PORT is still 5432.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nXgRBLTEVR9-zmxm.png" /></figure><p>Update your backend server’s environment variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*5J7P8PNkQcUPJrv8.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9k86ggvm3hFvN2J4.png" /></figure><p>Save and Deploy. Check your logs and you should get this error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mk-ZHasnHV2AVqZP.png" /></figure><p>We just hit the one of the hurdles of “manual” Docker management. Updating the code in our image. The error django.core.exceptions.DisallowedHost is Django’s security guard. It’s saying, &quot;I see someone calling me from tailors-kit.onrender.com, but my settings.py inside this frozen image told me only to talk to localhost. We need to update our code.</p><p>Instead of hardcoding tailors-kit.onrender.com into your code and rebuilding the image every time your URL changes, we’ll make it <strong>dynamic</strong> and tell Django to look for an environment variable.</p><pre>import os<br><br># gets the hosts from an environment variable, split by commas<br># defaults to localhost for development if the variable isn&#39;t found<br>ALLOWED_HOSTS = config(&quot;ALLOWED_HOSTS&quot;, &quot;localhost,127.0.0.1&quot;).split(&quot;,&quot;)<br><br># add this too; List of trusted origins for safe requests<br>CSRF_TRUSTED_ORIGINS = config(&quot;ALLOWED_CSRF_ORIGINS&quot;, &quot;http://localhost:8000&quot;).split(&quot;,&quot;)</pre><p>Go to your <strong>Environment</strong> tab in Render and add:</p><ul><li>ALLOWED_HOSTS= tailors-kit.onrender.com,localhost</li><li>ALLOWED_CSRF_ORIGINS=https://tailors-kit.onrender.com,http://localhost:8000</li></ul><p>In professional setups, devs don’t manually type docker build and docker push. They set up a GitHub Action that watches for a code push, builds the image, pushes it to the Registry, and ping Render/AWS to say &quot;Hey, there&#39;s a new version, go get it!&quot;</p><blockquote><em>Github Actions: You can visualize this like a robot that runs commands on certain triggers</em></blockquote><p>That’ll come in a later article. For now,</p><ul><li>update your source code</li><li>build your image</li><li>push to docker: docker push username/tailors_kit</li></ul><p>And we’re live🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r1Sa5Nv0adwiECgF.png" /></figure><h3>Create a superuser &amp; migrations</h3><p>Now, we need to create a super user and migrate.</p><p>To create a superuser, we can run a one-off command in Render’s interactive shell and add a <strong>pre-deploy command</strong> to our service that runs migrations before the most recent build is deployed.</p><p>Found out both features are now only for the rich.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fHBWMigqSH0pliP_.png" /></figure><p>So, If you are on the free tier like I am, you can run a shell script to handle “automatic” migration &amp; the creation of a superuser, if one does not exist.</p><p><strong>Step 1</strong>: Create a file named start.sh in your project root:</p><pre># apply database migrations<br>echo &quot;Applying migrations...&quot;<br>python manage.py migrate --noinput<br><br># create a superuser if it doesn&#39;t exist<br>echo &quot;Creating superuser :)...&quot;<br>python manage.py shell &lt;&lt;EOF<br>from django.contrib.auth import get_user_model<br>User = get_user_model()<br>import os<br>username = os.environ.get(&#39;DJANGO_SUPERUSER_USERNAME&#39;)<br>email = os.environ.get(&#39;DJANGO_SUPERUSER_EMAIL&#39;)<br>password = os.environ.get(&#39;DJANGO_SUPERUSER_PASSWORD&#39;)<br>if not User.objects.filter(username=username).exists():<br>    User.objects.create_superuser(username, email, password)<br>    print(f&#39;Superuser &quot;{username}&quot; created.&#39;)<br>else:<br>    print(f&#39;Superuser &quot;{username}&quot; already exists.&#39;)<br>EOF<br><br># start the server<br>echo &quot;Starting server...&quot;<br>python manage.py runserver 0.0.0.0:8000</pre><p>Remember to update your env file (local &amp; on render)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/0*jV6uhaM5EyFYlBMo.png" /></figure><p><strong>Step 2</strong>: Make sure your Dockerfile knows to use this script as the “Final Word” (the Entrypoint).</p><pre># copy all including the script<br>COPY . .<br><br># Give it permission to run<br>RUN chmod +x start.sh<br><br># Tell Docker to run the script instead of just running the server<br>CMD [&quot;./start.sh&quot;]</pre><blockquote><strong><em>Tip</em></strong><em>: If you’re on Windows, make sure your code editor saves </em><em>start.sh with </em><strong><em>LF</em></strong><em> line endings, not </em><strong><em>CRLF</em></strong><em>, or Docker will throw a tantrum.</em></blockquote><blockquote><em>💡Check the bottom of your VS code IDE to switch to LF line endings.</em></blockquote><p><strong>Step 3</strong>: Add the Credentials to Render</p><p>Since the script above looks for os.environ.get, you need to go to your <strong>Render Dashboard</strong> &gt; <strong>Environment</strong> and add these keys:</p><ul><li>DJANGO_SUPERUSER_USERNAME: admin</li><li>DJANGO_SUPERUSER_EMAIL: <a href="/service/mailto:admin@example.com">admin@example.com</a></li><li>DJANGO_SUPERUSER_PASSWORD: your-super-secret-password</li></ul><p>Push to <strong>Docker Hub</strong> and redeploy the latest reference (latest state of your image) manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/0*O5BvIkhNo-BxhC6H.png" /></figure><p>You should be able to see your script run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IRrkl9c9B1OVaeyZ.png" /></figure><p>and your superuser created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dLlFVI1OW5L8pvqC.png" /></figure><p>And on your address bar, paste your web service URL, and you should see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nENzGuf4qe3d0qR3.png" /></figure><p>This means our backend is up and our postgres server is connected. Finally!🎉</p><p><a href="https://github.com/titoadeoye/tailors_kit/tree/docker-tutorial">Tutorial repo</a><em> 🔗</em></p><h3>Frontend Setup</h3><p><strong>Take home assignment</strong>: Try to dockerize a skeleton frontend application yourself. <br><strong>Target</strong>: Expose it on PORT 5173 (or wherever lol)</p><p>Skeleton app is hosted <a href="https://github.com/titoadeoye/tailors_kit_design/tree/skeleton">here</a>. Clone it and you’re on your way.</p><p><strong>A quick checklist</strong></p><ul><li>Create your dockerfile. You can try a lightweight base image like node:20-alpine</li><li>Don’t forget to pass --host to Vite in your CMD, or it’ll stay trapped inside the container</li><li>To host on render, make sure to add your URL to allowedHosts in vite.config.js . This is very similar to the situation with ALLOWED_HOST on our Django app</li><li>Create an image using docker build</li><li>Run the image locally to test: -p 5173:5173</li><li>Connect to a Web Service on Render</li></ul><p>It’s not as intricate as the backend setup, and once you’re done, you’ll have a fully containerized frontend!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IVGtOiLHfOdD7LPd.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jpy4cQpxIGo235tT.png" /></figure><p>If you have any trouble, you can refer to this <a href="https://github.com/titoadeoye/tailors_kit_design/tree/skeleton-w-docker">link</a> for the full Docker configuration.</p><h3>Conclusion</h3><p>That’s a wrap. Frontend and backend: dockerized.</p><p>If this was useful, please leave a like💖 and/or a comment🗣️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a8ab9a986b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Husky is Underrated]]></title>
            <link>https://medium.com/@titoadeoye/why-husky-is-underrated-55d63e24c445?source=rss-9b9003e23766------2</link>
            <guid isPermaLink="false">https://medium.com/p/55d63e24c445</guid>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[husky]]></category>
            <category><![CDATA[code-quality]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Tito Adeoye]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 17:26:55 GMT</pubDate>
            <atom:updated>2025-11-10T17:26:55.751Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LPwZaWESH5yMTucnSl1o_Q.png" /></figure><p>We automate everything — builds, tests, deploys — yet somehow forget about the one place where bad code first enters the system: the commit. <strong>Husky</strong> solves that. It’s a simple, reliable way to hook into Git and run scripts before code gets merged, but it rarely gets the spotlight it deserves. If you care about clean commits and consistent workflows, Husky deserves a second look.</p><h3>What’s Husky?</h3><p>Husky is a Git hooks manager for Javascript/Typescript projects (though it can work in any repo).</p><p>Git hooks are scripts Git automatically runs at specific events — like before a commit (pre-commit), before a push (pre-push), right after a merge, etc.</p><p><strong>Husky</strong> makes managing these hooks easier by letting you define and run them directly from your project. Think of them like <strong>triggers in a GitHub Actions workflow</strong>, except instead of jobs in YAML, you’re running executable scripts locally before your code even leaves your machine.</p><p>There are <strong>Native Git Hooks</strong> (without Husky) supported by Git, which can be found in the .git/hooks directory. Each hook is a script (like pre-commit, pre-push, etc.) that you can manually write in bash or another shell language. The downside is that they’re local only and cannot be shared via Git, which makes them hard to maintain across teams.</p><p>Navigate to an existing projects .git folder, and then to it’s hooks folder and you should find multiple .sample git hooks.<br>Here’s a sample of one of those hooks (pre-push.sample):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qRZZo7l3k-y39GE6.png" /></figure><p>Now, Husky make these hooks:</p><ol><li><strong>Version-controlled</strong>: stored in your repo instead of .git/hooks. Everyone on your team gets access to the same environment.</li><li><strong>Cross-platform</strong>: works the same on macOS, Linux, and Windows</li><li><strong>Automated</strong>: runs scripts like linting, formatting, or tests before commits/pushes</li></ol><h3>Why use it?</h3><p>Husky exists to <strong>guarantee code quality and consistency</strong> before code ever leaves a developer’s laptop.</p><p>Typical use cases include:</p><ul><li><strong>Running linters or formatters</strong> (ESLint, Prettier) before commits.</li><li><strong>Preventing broken code</strong> from being pushed (npm test in pre-push hook).</li><li><strong>Enforce commit conventions</strong> (e.g., via Commitlint).</li><li><strong>Auto-fix small errors</strong> like missing semicolons, wrong imports, etc.</li></ul><p>This way you avoid “works on my machine” PRs.</p><h3>Common Hooks &amp; Their Use Cases</h3><ul><li><strong>pre-commit</strong>: This hook is triggered before git commit. Common use cases include running ESLint, Prettier, or even tests. It ensures only clean code gets committed</li><li><strong>commit-msg</strong>: This hook is triggered after entering a commit message (git commit -m message). Common use cases include running Commitlint. This lets you enforce standardized commit messages</li><li><strong>pre-push</strong>: This hook is triggered before git push. Common use cases include running a test suite, preventing broken builds from reaching remote.</li><li><strong>post-merge</strong>: This hook is triggered after git merge. Common use cases include installing dependencies or re-run builds. This keeps local dev env synced</li></ul><h3>Examples</h3><p>Let’s say you want to ensure all code is linted and formatted before commit.</p><ol><li>Install Husky</li></ol><pre>npm install husky --save-dev npx husky init</pre><p><strong>2. </strong>Add script to package.json</p><pre>&quot;scripts&quot;: {   &quot;prepare&quot;: &quot;husky install&quot; }</pre><p><strong>3. </strong>Add a pre-commit hook</p><pre>echo &quot;npm run LINT&quot; &gt; .husky/pre-commit  // overwrites file</pre><p>Make a change in your project, stage and then commit and you should see the lint script run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/0*qY7ETHr7ePJNbixc.png" /></figure><p>💡Confirm that lint is one of the scripts in your package.json file</p><p><strong>4. </strong>Combine with lint-staged (Optional)</p><p>Lint-staged only runs linters on staged files (faster).</p><pre>npm install lint-staged --save-dev</pre><pre>&quot;lint-staged&quot;: {  // add on the same level with scripts i.e &quot;scripts&quot;: {}, &quot;lint-staged&quot;: {}<br>  &quot;*.{js,ts,tsx}&quot;: [&quot;eslint --fix&quot;, &quot;prettier --write&quot;]<br>}</pre><p>Then update your pre-commit:</p><pre>echo &quot;npx lint-staged&quot; &gt;&gt; .husky/pre-commit // &quot;&gt;&gt;&quot; appends to the file</pre><p>The result is every commit runs eslint &amp; prettier on staged files and fails if the code doesn’t meet your standards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nrsH0_iazOw3-8ei.png" /></figure><p>If your files are not staged and you try to run lint-staged, you get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5_vQziOnmQlX43pf.png" /></figure><p><strong>Combining Husky with Commitlint</strong></p><p>Commitlint helps enforce consistent commit messages (e.g. following <a href="https://www.conventionalcommits.org/en/v1.0.0/">Conventional Commits</a>). It works well with <strong>Husky</strong> hooks to prevent bad commit messages before they even land in your repo.</p><ol><li>Install Commitlint CLI + the Conventional Commits configuration (a ready to use ruleset)</li></ol><pre>npm install @commitlint/cli @commitlint/{config-conventional,cli} --save-dev </pre><p>2. Create a file called commitlint.config.js in your project root and extend the Commitlint conventional configuration</p><pre>// commitlint.config.js<br>export default {<br>  extends: [&#39;@commitlint/config-conventional&#39;],<br>};</pre><p>If your using CommonJS instead of ES modules, use this instead:</p><pre>module.exports = { extends: [&#39;@commitlint/config-conventional&#39;] };</pre><p>3. Add a Husky <strong>commit-msg</strong> hook</p><pre>echo &#39;npx --no -- commitlint --edit &quot;$i&quot;&#39; &gt;&gt; .husky/commit-msg</pre><p>Now, Husky will automatically run Commitlint every time you try to commit.</p><p>4. Enforce Conventional Commits conventionally (Optional)</p><p>Try committing something invalid:</p><pre>git commit -m &quot;fixed bug&quot;</pre><p>You’ll get an error because it doesn’t follow the correct format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/0*3QU7i_d1Nc1bgCQW.png" /></figure><p>Try again with a valid message:</p><pre>git commit -m &quot;fix: resolve login bug&quot;</pre><p>Commitlint passes — commit succeeds. This ensures commit messages follow a pattern like feat: add new auth flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OzOO0PbMZ8MxU2kl.png" /></figure><p>If you do not want to have to install Commitlint, you can utilize a <strong>manual shell-based commit message checker</strong> using a regex instead of Commitlint. It’s a common pattern in projects that want a lightweight, no-dependency way to enforce commit message conventions.</p><pre>// in .husky/commit-msg<br>commit_regex=&#39;^(feat|fix|docs|style|refactor|test|chore|merge|conflict|perf)(\(.+\))?: .{1,50}&#39;<br><br>if ! grep -qE &quot;$commit_regex&quot; &quot;$1&quot;; then<br>    echo &quot;ERROR: Commit message format is invalid.&quot;<br>    echo &quot;Expected format: &lt;type&gt;(&lt;scope&gt;): &lt;description&gt;&quot;<br>    echo &quot;Types: feat, fix, docs, style, refactor, test, chore&quot;<br>    echo &quot;Example: feat(auth): add login functionality&quot;<br>    exit 1<br>fi</pre><p>And when you try committing something invalid:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/0*JjyQ5ELCiGfVI_hU.png" /></figure><p>With a valid commit message format, however:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/0*HlKr3MtHbm5Ref39.png" /></figure><p>That’s it! Happy coding🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55d63e24c445" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Requests at Scale — Exponential Backoff with Jitter (with examples!)]]></title>
            <link>https://medium.com/@titoadeoye/requests-at-scale-exponential-backoff-with-jitter-with-examples-4d0521891923?source=rss-9b9003e23766------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d0521891923</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Tito Adeoye]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 01:49:36 GMT</pubDate>
            <atom:updated>2025-11-09T01:49:36.022Z</atom:updated>
            <content:encoded><![CDATA[<h3>Requests at Scale — Exponential Backoff with Jitter (with examples!)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wNSEPVLTU2BXl209WFV_tQ.png" /></figure><p><strong>Imagine this:</strong></p><ul><li>Your server goes down for a few seconds.</li><li><strong>10,000 clients</strong> all send a request at t=0.</li><li>It fails. They all retry after 1s → fail again → retry after 2s → fail → retry after 4s.</li></ul><p>You’ve just created a <strong>stampede</strong> — all 10k clients hammering your recovering server <em>at the same time</em>.</p><p>This pattern of increasing wait times — 1s, 2s, 4s, 8s… — is called <strong>exponential backoff</strong>. It’s a common retry strategy: every time a request fails, you wait <em>twice as long</em> before trying again.</p><p>Sounds smart, right? It helps reduce load… <em>except</em> when everyone’s retry schedule is synchronized. Then it just makes the stampede happen at longer intervals.</p><p>That’s where <strong>jitter</strong> comes in.</p><p>Instead of everyone retrying at <strong>exactly</strong> 1s, 2s, 4s… you add a little randomness:</p><pre>Retry after 1000ms + random(0–200ms)<br>Retry after 2000ms + random(0–200ms)<br>Retry after 4000ms + random(0–200ms)</pre><p>So one client might retry at 1.03s, another at 1.15s, another at 1.19s.</p><p>This randomness <strong>spreads the load</strong>, giving your server a chance to recover instead of getting hammered in unison.</p><p>Think of it like this:</p><ul><li>Without jitter, retrying clients act like a <strong>marching band</strong> — every horn blasting in perfect sync.</li><li>With jitter, it’s more like a <strong>crowd talking</strong> — still noisy, but naturally staggered, distributed, so the system can keep up.</li></ul><p>In practice, this means the server actually has time to <strong>breathe</strong>. While 1,000 clients might all retry <em>around</em> t=0, only a few dozen hit it at any given moment — say, 50 at t=1020ms, a few at t=1100ms, and so on.</p><p>Of course, real-world factors like browser behavior and network latency already desynchronize clients <em>a bit</em>, but adding jitter makes that spread <strong>intentional and reliable</strong>.</p><blockquote><em>💡 </em><strong><em>Tip:</em></strong><em> Always cap your backoff time — e.g., stop increasing after ~30 seconds. Beyond that, retries usually just waste resources</em></blockquote><h3>Jitter with React Query</h3><p>Interestingly, <strong>React Query</strong> makes it easy to implement this behavior by letting you <strong>customize retry delays</strong> with a function:</p><pre>import { QueryClient } from &quot;@tanstack/react-query&quot;;<br><br>const queryClient = new QueryClient({<br>  defaultOptions: {<br>    queries: {<br>      retry: 3, // max retries<br>      retryDelay: attemptIndex =&gt; {<br>        // exponential backoff with jitter<br>        const base = Math.min(1000 * 2 ** attemptIndex, 30000); // base with 30s cap<br>        const jitter = Math.random() * 300; // add up to 300ms of randomness<br>        return base + jitter;<br>      },<br>    },<br>  },<br>});</pre><p>This means your retries look something like:</p><ul><li>1st retry → ~1s + random jitter</li><li>2nd retry → ~2s + jitter</li><li>3rd retry → ~4s + jitter</li><li><strong>Capped at 30s</strong>, so it doesn’t grow forever</li></ul><h3>Jitter strategies (with React Query examples)</h3><p>When retrying, we want <strong>3 things</strong>:</p><ol><li>Not overload the server.</li><li>Spread retries across clients.</li><li>Not wait forever if the service is actually down.</li></ol><p>That’s why we use <strong>exponential backoff + jitter + a cap</strong>. The former and latter are easy enough to create and reason about. <strong>Jitter</strong>, on the other hand, can be applied in different ways. How you add randomness affects how retries spread across clients, which is why there are several strategies — full, equal, and decorrelated jitter — each with its own trade-offs.</p><h3>1. Full Jitter</h3><p>Random between 0 and baseDelay.</p><p>The formula:</p><pre>delay = random(0, min(cap, base * 2^attempt))</pre><p>Example:</p><pre>retryDelay: attemptIndex =&gt; {<br>  const base = Math.min(1000 * 2 ** attemptIndex, 30000);<br>  return Math.random() * base; // full jitter<br>}</pre><p>This is very “chaotic” — clients get super spread out.</p><p>It’s best for when load is heavy and server needs breathing room. But the <strong>risk</strong> is some retries might be <em>too soon</em> (like 0.1s), which can waste attempts and hammer the server too early.</p><p>Example, base = 1000ms:</p><ul><li>Attempt 1 → random(0, 2000) → could be <strong>100ms</strong>, 500ms, 1500ms, etc.</li><li>Attempt 2 → random(0, 4000) → could be <strong>300ms</strong>, 2000ms, 3900ms, etc.</li><li>Attempt 3 → random(0, 8000) → etc.</li></ul><p>So even though the <em>range</em> grows exponentially, you can still get very small delays because the lower bound is always 0.</p><p>The risk is that <strong>full jitter has no floor</strong>. It introduces maximum randomization, prevents lockstep, but retries <em>can</em> be too aggressive sometimes.</p><p>That means on retry attempt 2, you <em>could</em> still end up waiting only 100ms before retrying again, even though the cap is 4000ms.</p><p>If you have thousands of clients, statistically some of them will hit those small numbers, so the server may get hammered harder than with <em>equal jitter</em> or <em>decorrelated jitter</em></p><p><strong>How we fix it</strong></p><p>Some teams add a <strong>minimum sleep time (floor)</strong>:</p><pre>sleep = min + random(0, base * 2^attempt) // full jitter + floor</pre><p>e.g. min = 500ms.</p><p>This way, retries will never happen too soon, but you still get the spread of jitter.</p><h3>2. Equal Jitter (Google’s favorite)</h3><p>Half the base delay + random up to the other half.</p><p>The formula:</p><pre>delay = (base / 2) + random(0, base / 2)</pre><p>Example:</p><pre>retryDelay: attemptIndex =&gt; {<br>  const base = Math.min(1000 * 2 ** attemptIndex, 30000);<br>  return base / 2 + Math.random() * (base / 2);<br>}</pre><p>Here, half the wait time is guaranteed, plus some randomness. This keeps retries <em>roughly aligned</em> but still spreads them, guaranteeing retries don’t cluster too <em>early</em>.</p><p>It is a balanced strategy (not too chaotic, not too synchronized).</p><h3>3. Decorrelated Jitter (the fancy one Netflix uses)</h3><p>Instead of a strict formula, the next delay is random between a fixed minimum and 3x the previous delay, avoiding “lockstep” retries, but keeping growth reasonable.</p><p>The formula:</p><pre>delay = min(cap, random(minDelay, previousDelay * 3))</pre><p>Example:</p><pre>let prev = 1000; // track last delay<br>retryDelay: attemptIndex =&gt; {<br>  prev = Math.min(30000, Math.random() * (prev * 3));<br>  return prev;<br>}<br><br>// full example<br>function useTodosQuery() {<br>  let prev = 1000; // initial base delay<br><br>  return useQuery({<br>    queryKey: [&quot;todos&quot;],<br>    queryFn: fetchTodos,<br>    retry: 5,<br>    retryDelay: () =&gt; {<br>      prev = Math.min(30000, Math.random() * (prev * 3));<br>      console.log(&quot;Retrying in&quot;, prev, &quot;ms&quot;);<br>      return prev;<br>    },<br>  });<br>}</pre><p>This adapts dynamically, never getting stuck in patterns.</p><p>A common worry is, would a low first retryDelay not lead to <em>lower and lower delays</em> sometimes?</p><p>Say prev = 1000. Then:</p><ul><li>Next delay could be anywhere in [0 … 3000] and you might get <strong>300ms</strong>.</li><li>Then if prev = 300ms, next delay is in [0 … 900ms]. That <em>looks like</em> it can spiral downwards.</li></ul><p><strong>Why it still works well in practice:</strong></p><p><strong>Probability skews upward over time.</strong> Since the next delay is random(0, prev*3), larger prev values make it far more likely to stay in a higher range.</p><p>Example: if prev=1000, then 2/3 of the probability mass is <em>above</em> 1000 (since the range is 0–3000).</p><p>If you randomly land at 300ms, the next draw is [0..900] — which feels “low,” but the chance of staying low multiple times in a row is <strong>tiny</strong>.</p><blockquote><em>Number of users who get “unlucky” will not match those who do.<br>With decorrelated jitter, even if </em>you<em> get “unlucky” and land at 300 ms after 1 s, the odds of another user also getting that same downward path are vanishingly small. Each client’s retries are randomized independently, so the population as a whole is nicely spread out.</em></blockquote><p><strong>Upper bounding by max (30s in our example)</strong> means retries will <em>tend</em> toward that ceiling without ever lockstepping.</p><p>At scale (millions of clients), <strong>the law of large numbers wins</strong>. Over many clients, some hit small numbers, some hit large, but the <em>distribution</em> evens out.</p><p>So while one client <em>might</em> get a weird 300ms retry, across millions of clients the system sees a <em>smooth spread</em> — which is what the server cares about.</p><p><strong>Now compared to Equal Jitter:</strong> Equal Jitter’s lower bound rises strictly, so everyone clusters around similar ranges, while Decorrelated Jitter “wanders” more — some retries are short, some long — which actually helps spread retries <em>better</em> across clients, avoiding bursts.</p><p>Decorrelated Jitter is the recommended strategy for implementing Jitter. It has been found to be the smoothest under real-world network chaos.</p><p>Netflix/AWS tested it at scale and found it <em>reduced traffic spikes best</em> while keeping retry latency reasonable. So yeah — , <em>any jitter kills lockstep</em>. Decorrelated jitter is just the most <strong>battle-tested</strong> strategy at massive scale.</p><h3>Visualization</h3><p>Here’s a visualization of how retries distribute across <strong>100 clients</strong> for the four strategies:</p><ul><li><strong>No Jitter</strong>: Huge clustering at fixed retry times (lockstep problem).</li><li><strong>Full Jitter</strong>: Spreads retries widely across the interval (good for smoothing).</li><li><strong>Equal Jitter</strong>: A nice balance. Avoids hammering while still bounding delay.</li><li><strong>Decorrelated Jitter</strong>: Very smooth and natural-looking distribution; avoids synchronized spikes while adapting flexibly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*a-K-MQPBovR_OnWZ.png" /></figure><p>You can see now why <strong>decorrelated jitter</strong> is often the preferred choice (not in every case!) — it breaks up the “lockstep” while keeping retry times bounded and fair.</p><h3>Best Practices</h3><ol><li><strong>Always cap your delay.</strong><br>Backoff can grow fast — 1s, 2s, 4s, 8s, 16s… and before you know it, you’re waiting minutes. Don’t let retries grow unbounded — it wastes time and ties up client resources. A max like <strong>30 seconds</strong> is a good rule of thumb.</li><li><strong>Add jitter intentionally.</strong><br>Even a small random offset (±100–300 ms) massively reduces the thundering-herd effect. It doesn’t always have to be fancy — just enough to keep clients from marching in sync.</li><li><strong>Backoff per request type.</strong><br>Not all operations are equal — a cheap GET can retry aggressively, but a payment or data-write shouldn’t. Use custom backoff logic when it matters.</li><li><strong>Combine with circuit breakers.</strong><br>If the service is really down, don’t keep hammering it. Stop retrying for a while and surface an error instead.</li><li><strong>Log retries.</strong><br>Track how often and how long retries happen — patterns here often reveal flaky dependencies or network issues.</li></ol><h3>Some common gotchas to look out for</h3><ol><li><strong>“Retrying forever” loops.</strong><br>If a dependency’s default is to retry indefinitely, cap it manually. Otherwise you might DDoS your own backend during an outage.</li><li><strong>All clients share the same code = synchronized patterns.</strong><br>Even with jitter, if your client base is huge and everyone starts at once (e.g., app relaunch after downtime), add <em>startup randomization</em> too.</li><li><strong>Timeouts ≠ backoff.</strong><br>Timeouts limit how long a request can hang, backoffs, on the other hand, control how often you <em>retry</em>. They work together but aren’t interchangeable.</li><li><strong>Don’t retry non-idempotent actions.</strong><br>POSTs that trigger payments or side effects should <strong>never</strong> be retried blindly — wrap them in idempotency keys or skip retries entirely. Learn more about <a href="https://medium.com/@titoadeoye/requests-at-scale-idempotency-91505ccff0e0">Idempotency</a></li><li><strong>Local testing can mislead you.</strong><br>In small environments, the “stampede” effect won’t show up. Use simulations or chaos testing to see how your system behaves under load.</li></ol><h3>Mini Quiz</h3><p>Sometimes in interviews or system design discussions, the right answer is <em>how you handle retries gracefully</em>. Here are some sample questions where exponential backoff + jitter could be part of the solution:</p><ol><li>You have 10,000 clients hitting a third-party API that allows 100 requests per second. How do you prevent overwhelming the API while ensuring requests eventually succeed?</li><li>Your microservice depends on a downstream service that <strong>occasionally fails</strong>. What’s your strategy to prevent cascading failures?<br><strong>Hint</strong>: Exponential backoff + jitter + a cap + circuit breakers</li><li>A mobile app loses network connectivity for a few seconds. When it reconnects, how should it handle retrying failed requests without crashing your servers?</li><li>Your background job queue occasionally fails jobs due to transient network errors. How do you retry jobs safely?</li></ol><h3>Conclusion</h3><p>Retries aren’t just about “try again until it works.”</p><p>Using <strong>exponential backoff with jitter</strong> keeps things safe, spreads out retries, and gives your backend a chance to recover. Add circuit breakers and logging, and you’re all set.</p><p>In short: <strong>retry smart, not hard.</strong> Happy coding<strong>🎉</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d0521891923" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Requests at Scale — Idempotency]]></title>
            <link>https://medium.com/@titoadeoye/requests-at-scale-idempotency-91505ccff0e0?source=rss-9b9003e23766------2</link>
            <guid isPermaLink="false">https://medium.com/p/91505ccff0e0</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[reliability]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Tito Adeoye]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 00:41:56 GMT</pubDate>
            <atom:updated>2025-11-03T00:41:56.842Z</atom:updated>
            <content:encoded><![CDATA[<h3>Requests at Scale — Idempotency</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xW4bA0mIP4hHRbxq5LRN8Q.png" /></figure><p>In simple terms, Idempotency in HTTP requests is “<strong>doing the same operation multiple times has the same effect as doing it once</strong>”. For operations that create side effects, e.g. POST requests, <strong>idempotency keys</strong> let the server detect duplicate attempts and return the same result instead of performing the side effect again.</p><p>An example is a client that sends POST /orders but network drops. Client retries requests with the <strong><em>same</em></strong> idempotency key generated, the server see the key and returns the existing order instead of creating a second one.</p><h3>Who should generate the key?</h3><p><strong>Ideally, the client</strong> — whether that’s the frontend or the caller service. This way, the client guarantees the same key for retries of the <strong>same request</strong>.</p><p>On the backend, you should associate each key with the <strong>user context</strong> (for example, user_id or session_token). This prevents collisions between users and guarantees correct ownership.<br>A common pattern is to store results under a composite key like (user_id + idempotency_key), so the same UUID used by two different users doesn’t overlap.</p><p>Because of that, <strong>authentication is essential</strong> for sensitive operations. It ties the idempotency key to a specific user server-side, preventing cross-user replays or tampering.</p><p>For the client, a <em>crucial</em> nuance in idempotency design is that you want to <strong>prevent duplicate processing when the same action is retried or accidentally triggered multiple times</strong>, but <strong>allow different operations to be distinct</strong>.</p><p>You use the <em>same</em> key every time the user clicks that button (or performs an operation that must be idempotent; for that specific operation), then the backend treats it as the <strong>same request</strong>, returning a cached response i.e. no duplicate processing.</p><h3>How do real-world systems handle this?</h3><p>Real systems handle idempotency by pairing <strong>client-generated stable keys</strong> with <strong>backend enforcement and rate-limiting</strong>.<br>Here’s how that usually looks in practice:</p><p>1. <strong>Client generates a stable idempotency key per “logical operation”</strong></p><p>An example is a payment form generates a <strong>single idempotency key when it’s first loaded or when the user starts the payment</strong>.</p><p>If the user clicks “Pay” multiple times for that same payment attempt, <strong>the same key is sent</strong> each time.</p><p>This way, retries or accidental double clicks return the cached result.</p><p><strong>2. A new operation initiates generation of a new idempotency key</strong></p><p>When the user starts a <em>new</em> payment, a <strong>new idempotency key is generated</strong>.</p><p>That key represents a distinct operation, ensuring each transaction is tracked separately.</p><h3>Practical Implementation</h3><p>When the user <strong>starts the payment flow</strong> — say, by opening the payment form or confirms the payment intent — generate and <strong>store a single idempotency key for that payment attempt</strong>.</p><p>Store it locally (e.g., in the component state, browser storage, or request context). Then <strong>reuse that same key for every “Pay” click</strong> during that payment attempt. This means <strong>multiple clicks send the same idempotency key</strong>, so backend treats all those as the same request.</p><p>Once payment is processed successfully or cancelled, <strong>clear the stored idempotency key</strong>.</p><p>Combine this with UI controls and server-side rate limits for robustness, including but not limited to:</p><p>On the client:</p><ul><li>disable the pay button until response or throttle clicks client-side</li><li>show a loading spinner or confirmation which reduces accidental multiple submissions.</li><li>expire or reset the key when operation completes or cancels. On a new payment attempt, generate a new key.</li></ul><p>On the server:</p><ul><li>rate limit requests per user or IP.</li><li>Check for repeated idempotency keys per user.</li><li>possibly track how many times a key is used and reject excessive retries.</li></ul><h3>How does Idempotency work?</h3><p>There are multiple approaches to implementation. But, in general, the goal is to ensure only one successful side-effect for a given idempotency key and return the exact same response for retries.</p><h3>Fast cache approach (Redis-like)</h3><p>The following is a general approach to implement impotency using fast caching:</p><p><strong>Generate a unique request ID</strong>: The first step in idempotency is to generate a unique <strong>request ID</strong> for <strong>each operation</strong> (action/side effect e.g. create-order). This could be passed by the client, or generated on the server side if not provided.</p><p>Common patterns involve using a UUID or hash of the request payload (for example, request body + timestamp + headers).</p><p>Ensure to use <strong>cryptographically-random keys</strong> (UUIDv4 or better). Don’t accept small predictable tokens.</p><p><strong>Use an atomic “set if not exists” (SETNX) to mark “in-progress” or to create the record</strong>: Before processing the operation, check the cache for the <strong>request ID</strong>. The cache should be a high-performance, low-latency store like <strong>Redis</strong> or <strong>Memcached</strong>, which provides quick lookup times (milliseconds).</p><p>The typical process is:</p><ul><li><strong>If the request ID exists in the cache</strong>, the operation has already been processed, so <strong>return the same result</strong> (response) without reprocessing the request.</li><li><strong>If the request ID does not exist</strong>, continue with the operation and store the result in the cache once the operation completes successfully.</li><li><strong>If another request arrives</strong> and sees an in-progress marker, either:<br>- return a 202 Accepted (with a job/location header), or<br>- block/wait briefly and then return the stored final response (depending on your latency model).</li></ul><p>We <strong>must</strong> implement <strong>atomicity</strong> in this step.</p><blockquote><strong><em>Atomicity</em></strong><em> refers to the property of an operation where it is </em><strong><em>indivisible</em></strong><em> — it either </em><strong><em>completes successfully</em></strong><em> as a whole or </em><strong><em>fails entirely</em></strong><em>, without leaving the system in an inconsistent state. An atomic operation cannot be partially completed.</em></blockquote><p>Ensuring atomicity means that checking the cache and processing the request should happen <strong>in one seamless, unbroken operation</strong>. If there’s any interruption, it could result in the operation being run multiple times, which would break the idempotency guarantee.</p><p>If these steps are not atomic, a <strong>race condition</strong> can occur, where the cache check and the actual processing could be “out of sync.” For example:</p><ul><li>Two identical requests come in at the same time.</li><li>Both check the cache and find it empty (because neither request has been processed yet).</li><li>Both requests proceed to process the operation and store the result in the cache, even though only one request should have been processed.</li></ul><blockquote><em>A </em><strong><em>race condition</em></strong><em> occurs when two or more processes (in this case, requests) try to access or modify shared resources (e.g., the cache) concurrently, and the final outcome depends on the order in which the requests are processed.</em></blockquote><p>This would violate the idempotency guarantee, and both requests could perform the operation twice.</p><p>Now, here’s where Redis guarantees this won’t happen — by implementing atomicity.</p><p>SETNX (<strong>check-and-set</strong> operation) is atomic — Redis guarantees that <strong>only one of the two requests will succeed</strong> in setting the key.</p><p>Even if two requests hit <strong>at exactly the same time</strong>, Redis will <strong>queue</strong> them internally and handle them <strong>one at a time</strong>.</p><p>Here’s what happens:</p><p><strong>Request A and Request B</strong> both try to run:</p><pre>cache.setnx(request_id, &#39;processing&#39;)</pre><p>Redis is single-threaded and will <strong>queue</strong> both requests. Then, following “<strong>first-in-first-out</strong>”(FIFO), it accepts <strong>Request A’s</strong> SETNX first. Since the key doesn’t exist yet, it sets it (store the result) and returns True to Request A. Then <strong>Request B</strong>&#39;s SETNX is processed.</p><p>But now the key <strong>already exists</strong> (from A), so Redis returns False to Request B. <strong>Request B</strong> sees the key exists and stops or returns a message like “request already in progress” or eventually reads the result from the cache.</p><pre>if cache.setnx(request_id, &quot;processing&quot;):<br>    do_work()<br>else:<br>    # someone else got it</pre><p><strong>Atomicity</strong> ensures that multiple operations (like checking the cache, processing a request, and writing to the cache) occur without interference from other operations.</p><blockquote><em>So only </em><strong><em>one request wins</em></strong><em> — the other </em><strong><em>doesn’t</em></strong><em> get past the </em><em>SETNX gate.</em></blockquote><p>You can build upon the SETNX atomic gate to implement <strong>locking.</strong> This requires a temporary “reservation” of the request ID. The purpose of this is to block other requests from processing the same ID <strong>while the current one is still being processed.</strong> This helps <strong>t</strong>o avoid issues if the process crashes after setting the key but before finishing the request.</p><blockquote>Why add Locking with TTL?</blockquote><blockquote>- What if your worker <strong>crashes</strong> after SETNX succeeds but <strong>before</strong> calling do_work() or before deleting the key?</blockquote><blockquote>- With a bare SETNX, that key never disappears. Everyone else will think “someone’s processing this” forever.</blockquote><p>We implement this using a TTL, which acts as a sort of safety net — so that if something goes wrong (e.g., the server crashes), the lock doesn’t stay forever and block all future requests.</p><p>You can think of it like “Hey, I’m looking at this — hold off on this for a bit. And if i’m no longer here in X time, go ahead”.</p><p>In Redis, a <strong>lock</strong> is often just a key like:</p><pre># &quot;processing&quot; is just a placeholder/message<br>cache.set(&quot;lock:req-12345&quot;, &quot;processing&quot;, nx=True, ex=60)</pre><p>This key is only set <strong>if it doesn’t already exist</strong> (nx=True), expires after 60 seconds (ex=60). While this lock key exists, no one else should process that request.</p><p>You can respond to this by returning a response to the client to retry (e.g. Retry-After header) and it’s retry mechanism handles subsequent requests, your backend app can retry with backoff (in-memory), or you could use an external queue system: Kafka, RabbitMQ, AWS SQS, etc. The latter is more complex but suitable for high-load or asynchronous processing.</p><p>After processing: you can <strong>manually delete the lock</strong> (cache.delete(&quot;lock:req-12345&quot;)), or It <strong>expires on its own</strong> (thanks to the TTL), preventing a deadlock.</p><p><strong>Cache Expiry and Cleanup:</strong> After the operation finishes, update the stored value with a final status/body and set a TTL. This ensures that the cached result doesn’t live forever and will be removed eventually.</p><p><strong>Do not delete idempotency records immediately.</strong> Keep them for a reasonable window so late retries still get the same response.</p><p>Typical ranges:</p><ul><li>short-lived ops (UI actions): <strong>24 hours</strong></li><li>financial transactions/payments: <strong>7–30 days</strong> (depends on refunds/chargeback windows)</li><li>Also, ensure to use <strong>TTL</strong> (Redis EXPIRE) instead of manual deletion where possible.</li></ul><pre>cache.setex(request_id, 600, &quot;Payment succeeded&quot;)</pre><p>After 10 minutes, Redis automatically removes the cached result with that id. Repeated requests with the same request_id within that window will get the same response.</p><p>Here’s a full breakdown of this process in python:</p><pre>import redis<br>import uuid<br>import time<br><br># initialize a Redis connection<br>cache = redis.StrictRedis(host=&#39;localhost&#39;, port=6379, db=0)<br><br># this processes the request atomically<br>def process_request(request_id, process_function):<br>    result_key = f&quot;{request_id}:result&quot; # store the actual processed result<br>    lock_key = f&quot;{request_id}:lock&quot; # short lived lock during processing<br><br>    # 1. Check if result already cached; early return if result is cached<br>    cached_result = cache.get(result_key)<br>    if cached_result:<br>        return cached_result.decode(&#39;utf-8&#39;)<br><br>    # attempt to set the request ID in Redis with a value to ensure atomicity<br>    # if request_id does not exist, it will be set and the request will proceed<br>    if cache.set(lock_key, &#39;locked&#39;, nx=True, ex=30):  # SETNX: Set if Not Exists (atomic)<br>        try:<br>            # process the request since the request_id wasn&#39;t in the cache<br>            result = process_function(request_id)<br><br>            # store the result in the cache after processing<br>            cache.setex(result_key, 600, result)  # cache with a TTL of 10 minutes<br>            return result<br>        finally:<br>            # cleanup step: Remove the temporary processing state<br>            # always runs to release lock; pass/fail of process_function<br>            cache.delete(lock_key)<br>    else:<br>        # if the request_id already exists, that means another process is handling it<br>        # ask client to retry(Retry-After Header) / enter retry + backoff logic or external queueing mechanism<br>        return &quot;Request already in progress, please wait.&quot;<br><br># example function to simulate processing (e.g., payment processing)<br>def fake_payment_processing(request_id):<br>    time.sleep(2)  # simulates some processing delay<br>    return f&quot;Payment processed successfully with {request_id}&quot;<br><br># example usage:<br>request_id = str(uuid.uuid4())  # create a unique request ID / client sends this<br>response = process_request(request_id, fake_payment_processing)<br>print(response)<br><br># second request with the same ID (idempotency in action)<br>response2 = process_request(request_id, fake_payment_processing)<br>print(response2)</pre><p>Now, we’ve talked about race conditions and how to combat them using atomicity and locks, which you can see in the example above.</p><p>Think of this:</p><p>→ Suppose two workers call cache.get(result_key) at the <em>exact</em> same time and both see it missing.</p><p>→ Both then race to SET lock_key ... nx=True. Only one succeeds.</p><p>→ The loser returns “Request already in progress,” which is fine — but if the winner crashes <em>before</em> setting the final result, we’ll <strong>lose the result entirely when the lock expires.</strong></p><p>→ The next caller will retry and potentially re-process.</p><p>→ For many systems this is acceptable, but for critical operations (like payments) we are going to want a stronger guarantee.</p><p>Cue <strong>background reprocessor + a “Pending” marker with a longer TTL.</strong></p><p>Think of the <strong>lock</strong> as a very short-lived, <em>mutual-exclusion</em> tool: it only exists so two workers don’t run process_function at the same time.</p><p>The pending marker survives much longer than the lock. Typical TTL is within <strong>10–30 mins.</strong></p><p>The pending marker (request_id:pending) says <em>“this request is being handled and should eventually have a result, even if the current worker dies.”</em></p><p>Your background reprocessor is a separate job (cron, Celery beat task, Kubernetes CronJob, etc.) that periodically scans for keys marked <strong>pending</strong> but still missing a <strong>result</strong> after some safety window. This means <strong>we recover if anything crashes and can restart the work.</strong></p><p>A pseudo loop could look like this:</p><pre>def reprocess_stale_requests():<br>    for key in cache.scan_iter(&#39;*:pending&#39;):<br>        req_id = key.split(&#39;:&#39;)[0]<br>        if not cache.exists(f&quot;{req_id}:result&quot;): # f&quot;{req_id}:result&quot; =&gt; cached result key<br>            # maybe check an external DB or queue to avoid duplicates<br>            requeue_for_processing(req_id)</pre><p>Now, this job might run every few minutes.<br>If it finds a request that is <em>still</em> pending but has no result after, say, 5–10 minutes, it re-queues or retries the processing.</p><p>The current timeline <strong>without</strong> a pending marker is</p><pre>Worker acquires lock -&gt; does work -&gt; [crash occurs before writing result] -&gt; Lock TTL expires -&gt; system forgets this request ever happened</pre><p>After the lock TTL expires, another caller may never know that the work was <em>half done</em> and might never retry.</p><p>With a <strong>pending</strong> marker:</p><pre>Worker sets pending marker (long TTL, e.g., 30 min) -&gt; Worker acquires short lock -&gt; does work -&gt; crash before result -&gt; Lock TTL expires<br>Pending marker still exists<br>Background reprocessor sees: pending exists &amp; result missing -&gt; re-queues for processing</pre><p>This system notices “something was started but never finished” and can then recover automatically — covering the <em>result-missing</em> edge cases.</p><p>A quick update:</p><pre>def process_request(request_id, process_function):<br>    result_key  = f&quot;{request_id}:result&quot;<br>    lock_key    = f&quot;{request_id}:lock&quot;<br>    pending_key = f&quot;{request_id}:pending&quot;<br><br>    if cache.get(result_key):<br>        return cache.get(result_key).decode()<br><br>    # mark as pending for a long time<br>    cache.set(pending_key, &#39;1&#39;, ex=1800, nx=True)<br><br>    if cache.set(lock_key, &#39;locked&#39;, nx=True, ex=30):<br>        try:<br>            result = process_function(request_id)<br>            cache.setex(result_key, 600, result)<br>            return result<br>        finally:<br>            cache.delete(lock_key)<br>    else:<br>        return &quot;Processing in progress.&quot;</pre><p><strong>Why use a lock instead of plain</strong> SETNX<strong>?</strong></p><p>SETNX key value is the primitive. It is a single atomic Redis command. Redis will <em>never</em> interleave another client’s request between the check and the set (Covers <strong>only</strong> the <em>no-two-winners</em> race)</p><p>So if two clients both run SETNX request_id value at the same instant, <strong>only one wins</strong> and gets a truthy reply. This is enough to guarantee that <em>only one</em> of them gets past the “gate.”</p><p>This is great for if you only need to <strong>deduplicate</strong> (<strong>remove duplicates</strong>) starts of work and you don’t mind the key sticking around forever (or you manage cleanup yourself).</p><pre># this is true atomicity for that single operation.<br>if cache.setnx(f&quot;req:{rid}&quot;, &quot;processing&quot;):<br>    do_work()<br>else:<br>    # someone else got it</pre><p>A <strong>lock</strong> is basically the same SETNX idea <strong>plus an expiry (</strong>EX) and (optionally) a value that lets you verify ownership when releasing. It is built upon the primitive.</p><p>You add this TTL period so you’re covered if your worker <strong>crashes</strong> after SETNX succeeds but <strong>before</strong> calling do_work() or before deleting the key?</p><p>With a bare SETNX, that key never disappears. Everyone else will think “someone’s processing this” forever.</p><pre>cache.set(&quot;lock:req-12345&quot;, &quot;token&quot;, nx=True, ex=60)</pre><p>Now if your process dies, the next attempt after 60s can safely retry — covers the <em>process crash</em> edge case</p><blockquote>“Use a lock instead of atomicity with SETNX”<em> — a </em>safer<em> use of the same mechanism, because the TTL prevents permanent deadlocks.</em></blockquote><h3>Database-backed approach (Postgres unique constraint)</h3><p>So far, the Redis-style approach prioritizes <em>speed</em> and <em>low latency</em>. It works best for short-lived operations — like processing a payment, confirming a form, or sending a one-off email — where a few seconds of cached state are enough to prevent duplicates.</p><p>But sometimes, you want something stronger — <strong>durability</strong>.<br>You want idempotency records that survive restarts, redeployments, cache flushes, or even region failovers. This is where a <strong>database-backed</strong> approach comes in.</p><p>The typical process is:</p><ul><li><strong>Table setup</strong>: Create table idempotency_keys(key TEXT PRIMARY KEY, user_id UUID, status INT, response JSONB, created_at TIMESTAMP).</li></ul><pre>CREATE TABLE idempotency_keys (<br>    key TEXT PRIMARY KEY,<br>    user_id UUID,<br>    status INT,<br>    response JSONB,<br>    created_at TIMESTAMP DEFAULT now()<br>);</pre><p>Each record represents a unique request (key) and optionally stores:</p><ul><li>who made it (user_id),</li><li>the operation state (status),</li><li>the final result (response),</li><li>and when it happened (created_at).</li></ul><p>The <strong>unique constraint</strong> on key is what enforces idempotency — it guarantees that two concurrent requests using the same key can’t both “win.”. Remember race conditions.</p><ul><li><strong>Insert logic</strong>:<br>When a new request arrives:<br>- INSERT INTO idempotency_keys (key, user_id) VALUES ($1,$2) ON CONFLICT DO NOTHING RETURNING response;<br>- If insert returned a row with a response, return it.<br>- If insert succeeded (i.e. you “won” the key), run the operation inside the same transaction or update the row after success.</li></ul><pre>INSERT INTO idempotency_keys (key, user_id)<br>VALUES ($1, $2)<br>ON CONFLICT DO NOTHING<br>RETURNING response;</pre><p>To break this down,</p><p><strong>Case 1: First request</strong></p><p>The insert succeeds because the key doesn’t exist yet i.e. You <strong>own</strong> the key and can safely run the operation.</p><p><strong>Case 2: Duplicate request</strong></p><p>The insert hits a unique constraint violation (key already exists). The ON CONFLICT DO NOTHING prevents an error, and the RETURNING response lets you fetch the stored result if it’s available.</p><p>So, if RETURNING response gives you a non-null value, you can immediately return it to the client — that means this exact request has already been processed before.</p><p>If the row was inserted successfully and you “won the key,” you can:</p><ul><li>either run your business logic <strong>inside the same transaction</strong>, or</li><li>run it normally and then <strong>update</strong> the row once the operation finishes successfully:</li></ul><pre>UPDATE idempotency_keys<br>SET status = 1, response = $3<br>WHERE key = $1;</pre><p>This ensures that subsequent duplicate requests will read the same saved response instead of executing again.</p><p>This approach works because;</p><ol><li>The <strong>unique constraint</strong> (PRIMARY KEY) ensures only one concurrent insert for a key succeeds.</li><li>The <strong>database transaction</strong> guarantees atomicity — no half-completed states.</li><li>The <strong>stored response</strong> provides durability — results live as long as your database retention policy.</li></ol><p>This is ideal for cases where idempotency must survive cache flushes, server restarts, or long-running processes — e.g., financial systems, long-lived background jobs, or systems with strict audit requirements — in cases where you want durability in the DB rather than an ephemeral store.</p><h3>Fast caching (Redis) vs Database (Postgres)</h3><p><strong>Speed</strong>: Fast cache is <strong>Ultra-fast</strong> (in-memory) while Database is <strong>Slower</strong> (disk I/O)</p><p><strong>Persistence: Fast cache is Ephemeral (TTL-based)</strong> i.e. it lasts for a short time, while Database is <strong>Durable</strong> (stored forever or how long your retention period is)</p><p><strong>Failure recovery</strong>. Fast cache requires a <strong>TTL + a background reprocessor</strong> while Database already has <strong>built-in consistency and a durable</strong> state</p><p>Fast cache is ideal for <strong>transient and high-throughput APIs</strong> while Database is more suitable for <strong>critical, auditable workflows</strong></p><p>Common use cases for fast cache includes Payment APIs, webhook deduplication, and rate-limiting. Common use cases for Database include Transactional systems, order processing, and long-running jobs.</p><p>In short, <strong>Redis</strong> gives you speed and flexibility for short-term guarantees while <strong>Postgres</strong> gives you durability and auditability for long-term guarantees .It’s important to note though, that for most real systems, you’ll often see both used together — Redis for <em>fast transient locks</em>, and Postgres for <em>final durable record-keeping</em>.</p><h3>Common pitfalls</h3><p>Even experienced teams make subtle mistakes when implementing idempotency. Some common gotchas include:</p><ul><li><strong>Session-scoped keys for side effects/actions:<br></strong>If the key is session-scoped, <em>different logical actions collide</em> e.g. create-order A vs create-order B. The server may treat different actions as the same and drop or return the wrong result.<br>The right approach is to generate one idempotency key per <em>logical operation</em> (per click that should be a single effect) and reuse that same key on retries of <em>that same action.<br></em>Exceptions where session-level scoped keys might be okay would include very specific “single instance per session” actions (e.g. “initialize demo account once per session”) — but this is niche and should be explicit in the API contract.</li><li><strong>Immediate deletion of key after processing<br></strong>If you delete the key immediately on completion<strong>, </strong>you open a<strong> race/window</strong> where a retry arriving slightly later could be re-processed. Ensure to expire keys with a short TTL instead of deleting immediately.</li><li><strong>Separating idempotency stores in distributed systems</strong>: In multi-server deployments, ensure the idempotency store is <strong>shared</strong> (e.g., Redis or central DB) so that requests hitting different servers see the same key.</li><li><strong>Storing huge responses</strong> in cache store, causing memory issues. Only store lightweight metadata and a pointer to persisted data.</li><li><strong>Accepting predictable keys</strong> or not tying keys to user can cause replay risk.<br>If keys are guessable or not tied to the user, they can be replayed. Ensure to tie keys to user IDs or accounts, and make them unpredictable (UUIDv4).</li><li><strong>Payload Mismatch Handling / Not comparing payloads</strong>:<br>A common pitfall in idempotent systems is when the client reuses the same idempotency key but sends a different payload (e.g., changed payment amount, altered user details, etc.). This can lead to silent failures or incorrect results, as the server might mistakenly process a new payload as part of the same operation.<br>To prevent this pitfall, the server should compare the payloads for requests with the same idempotency key. If the payloads differ, return a 409 Conflict status code, indicating a mismatch.<br>In the Database-backed approach, we compute a canonical payload_hash (SHA256 of the canonicalized JSON) for the payload on the client and server. On first insert, we store payload_hash. On subsequent requests with same key, however, we compare incoming payload_hash with the one stored. If there’s a mismatch, we return a 409 Conflict and describe the problem. A match, however, means it is safe to return stored response or wait for completion.<br>For the fast caching technique using Redis, we <strong>store</strong> the payload hash <strong>in the value</strong> (i.e., the Redis value), along with any metadata like status, response, user ID, etc. Then, <strong>when the same key is used again</strong>, you look it up, and <strong>compare the stored hash with the new request’s hash.<br>On First Request</strong></li><li>The <strong>Client</strong> sends the Idempotency-Key: 1234-abcd and payload: { &quot;amount&quot;: 100, &quot;currency&quot;: &quot;USD&quot; }</li></ul><pre>POST /payments<br>Idempotency-Key: 1234-abcd<br>Payload: { &quot;amount&quot;: 100, &quot;currency&quot;: &quot;USD&quot; }</pre><ul><li>The <strong>Server</strong> computes payload_hash = SHA256(canonicalized_payload) and stores in Redis under key: idempotency:1234-abcd</li></ul><pre>idempotency:1234-abcd =&gt; {<br>  &quot;payload_hash&quot;: &quot;abc123...&quot;,<br>  &quot;response&quot;: { ... },       // optional if not complete yet<br>  &quot;status&quot;: &quot;processing&quot;,    // or &quot;completed&quot;<br>  &quot;user_id&quot;: &quot;user-xyz&quot;,<br>  &quot;created_at&quot;: &quot;...&quot;,<br>  &quot;expires_in&quot;: 3600<br>}</pre><p><strong>On Retry (Same Key)</strong></p><ul><li>The <strong>Client</strong> sends Idempotency-Key: 1234-abcd and payload: { &quot;amount&quot;: 100, &quot;currency&quot;: &quot;USD&quot; }</li><li>The server:<br>- Computes payload_hash_new = SHA256(canonicalized_payload)<br>- Looks up idempotency:1234-abcd in Redis<br>- Then, compares payload_hash_new with stored payload_hash. If there’s a match, it’s safe to return stored response or resume processing. If there’s a <strong>mismatch</strong>, however, return 409 Conflict indicating payload changed</li></ul><blockquote><strong>The same idempotency key with different payloads must either reject the request or behave deterministically</strong> — meaning it should clearly define how to handle such cases (e.g., reject, override, or return an error message</blockquote><h3>Where idempotency matters the most (real examples)</h3><ul><li>Payments &amp; charge creation — prevent double charges</li><li>Order creation in e-commerce — avoid duplicate orders</li><li>Sending transactional emails/SMS — avoid duplicate sends</li><li>Reservation / booking systems (seats) — prevent double booking</li><li>Any action that triggers an external third-party change (billing provider, shipping label) — avoid triggering irreversible third-party actions.</li></ul><h3>Client flow summary (Example: Payments)</h3><ol><li><strong>Page loads:</strong></li></ol><ul><li>Generate an idempotency key.</li><li>Store it in localStorage.</li></ul><p>2. <strong>User fills the payment/signup form.</strong></p><p>3.<strong> User clicks “Pay”:</strong></p><ul><li>Send request with the stored key (PUT request).</li></ul><p>4. <strong>If user reloads or doesn’t get confirmation:</strong></p><ul><li>Use the <strong>same key again</strong> to check if the payment went through.</li><li>If payment <strong>did go through</strong>, clear the key and proceed.</li><li>If payment <strong>did NOT go through or isn’t in a retryable state</strong> like processing, Retry-After, create a new key and try again.</li></ul><p>Here’s a checklist for when you should/should not generate a new key using the payments example above</p><p><strong>Situation -&gt; Action -&gt; Reason</strong></p><ul><li><strong>User first loads payment page -&gt; </strong>Generate and store a new idempotency key -&gt; To uniquely identify this payment operation</li><li><strong>User submits the payment request -&gt; </strong>Reuse the stored key -&gt; Prevent duplicate processing if they click “Pay” multiple times or retry due to network issues</li><li><strong>User reloads page and payment status unknown -&gt; </strong>Reuse the same key to check payment status -&gt; To check if the previous payment went through</li><li><strong>Payment confirmed successful with current key -&gt; </strong>Clear the key and proceed to next step -&gt; That operation is complete; key no longer needed</li><li><strong>Payment failed or no response, user tries again -&gt; </strong>Generate a <strong>new idempotency key -&gt; </strong>This is a new attempt, so must be uniquely identified to avoid confusion with previous attempt</li></ul><h3>Conclusion</h3><p>Idempotency keys are one of those “small” engineering tools that prevent catastrophic duplicated side-effects at scale (double-charges, duplicate orders, or sending the same email twice).</p><p>Ultimately, idempotency isn’t about databases or caches; it’s about <strong>trust</strong> — ensuring that every request produces exactly one effect, no matter how many times it’s retried.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91505ccff0e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Requests at Scale: Everything You’re Doing Wrong with Requests]]></title>
            <link>https://medium.com/@titoadeoye/requests-at-scale-everything-youre-doing-wrong-with-requests-0421e3798e2b?source=rss-9b9003e23766------2</link>
            <guid isPermaLink="false">https://medium.com/p/0421e3798e2b</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <dc:creator><![CDATA[Tito Adeoye]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 18:00:13 GMT</pubDate>
            <atom:updated>2025-09-14T18:00:13.506Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLi5btN8Z0N2pHqTfc1zTg.png" /></figure><p>Most developers think sending a request is simple — fetch(&#39;/api&#39;) and done. We can treat requests as fire-and-forget, and just move on. But at scale, naive requests kill performance and reliability. Requests aren’t cheap — they’re one of the most expensive and failure-prone parts of your system.</p><p>This article kicks off a new series I’m calling <strong>Requests at Scale, </strong>where I’ll break down the patterns and pitfalls of making reliable, efficient, and safe requests. Today I’ll cover the high level problems — and over the next week or two (if all goes to plan🤞), we’ll be looking into each one deeply, starting with <strong>Idempotency Keys</strong>.</p><p>This series would be split into 3 focus groups: Efficiency, Resilience, and Safety.</p><h3>Resilience: Surviving Failure</h3><p>Common mistakes in this group include:</p><ul><li><strong>Not handling retries correctly:</strong> A lot of clients retry failed requests without thinking. Something times out? Retry immediately. Server says “busy”? Retry again. The result is often worse than the original failure: duplicate writes, request storms (thundering herds), and a backend that’s barely holding on.<br>We fix this by ensuring that retries are <strong>controlled and intelligent</strong>.</li><li>Apply <strong>Exponential backoff with jitter</strong> to avoid thundering herd (Lockstep Retry) so requests don’t all hit the server at once.</li><li><strong>Use Idempotency keys </strong>to prevent duplicate side effects, allowing retries without duplicates.</li><li><strong>Timeouts too short/long</strong>: Some requests drop too quickly, while others hang forever, tying up resources. Both extremes can kill resilience.<br>The fix here is to utilize <strong>Timeouts &amp; circuit breakers</strong>. Always set a reasonable <strong>retry limit. </strong>Endless retries just waste cycles and make the failure louder. Instead, fail fast, don’t drag the system down.</li><li><strong>Improper prioritization</strong>: background requests overwhelm critical flows. Not every request is equally important. Payment processing, auth, and user-critical flows should always take <strong>priority</strong> over analytics, background syncs, or cosmetic API calls. <strong>Throttling</strong> prevents less important requests from overwhelming servers.<br>An example is your system delegating resources to background syncs in load spikes where there are multiple users trying to sign up.<br>Without prioritization, your system can get bogged down by “noise” traffic, starving critical paths. Instead, prioritize &amp; rate-limit.</li><li><strong>Tight Coupling</strong>: This is when secondary requests (logging, tracking, recommendations) failing block primary user actions (checkout, saving work, logging in).<br>An example is analytics breaking checkout.<br>You must isolate secondary features, via <strong>Graceful degradation &amp; fallbacks</strong>, preventing “one bad dependency” from taking down your entire user flow.</li></ul><h3>Efficiency: Doing More with Less</h3><p>Common efficiency mistakes include:</p><ul><li><strong>Chatty clients</strong>: Some apps make multiple redundant calls instead of batching or caching them , overwhelming both the server and the client.<br>An example is a profile screen that makes <strong>three separate requests</strong> — /user, /user/address, /user/settings.<br>To fix this, use batching and request collapsing to combine multiple lookups into fewer round trips. In this case, this will be fetching all details in /user.</li><li><strong>N+1 requests</strong>: Fetching resources one by one in a loop can quickly spiral into dozens or hundreds of call, instead of <strong>bulk-loading or joins</strong>.<br>An example is fetching 100 posts, then running GET /comments?postId=… <strong>inside a loop</strong> → 101 requests. <br>The fix is to use <strong>bulk-loading</strong> (GET /posts?include=comments) or a join at the backend.</li><li><strong>Not using caching/ETags:</strong> This is where every call re-downloads the same data, wasting bandwidth and compute.<br>An example is a client requesting /products every minute and re-downloads the same JSON, even if nothing changed.<br>Instead, add an <strong>ETag</strong> header. server responds with 304 Not Modified when data is unchanged.</li><li><strong>Ignoring pagination</strong>: fetching entire datasets when you don’t need to. A completely baffling example, that I have personally seen, is the client requesting for data on a GET request, and gets back <strong>50,000 rows</strong> in one response, even if the UI only shows 20.<br>Use <strong>pagination (cursor-based over offset)</strong> e.g. /orders?limit=20&amp;cursor=xyz or /orders?page=1 , to scale large datasets. Also, <a href="https://medium.com/@titoadeoye/virtualized-lists-745cf97ebf8b">virtualized lists</a> are your friend.</li><li><strong>Bloated payloads</strong>: This involves sending full objects instead of only fields needed by the UI. The result is larger responses, slower rendering, and higher costs. Examples:</li><li>API returns entire user objects with <strong>50 fields</strong> when the UI only needs name and avatarUrl.</li><li>API returns embedded customer objects for every order object, when the UI only needs order ID and location.</li></ul><p>To fix this, <strong>trim payloads </strong>to the necessary fields (via GraphQL projections, sparse fieldsets, or selective DTOs)<strong> and enable compression </strong>to cut response size and speed things up.</p><p>I once debugged an app that would <strong>crash the browser tab entirely</strong> — on some devices, even the whole window. The culprit? A mix of <strong>bloated payloads and lack of pagination</strong>. The fix was to implement infinite scroll (pagination) and update the backend to send only required fields, until the client specifically requested more data. The crashes stopped.</p><p><strong>Quick note:</strong> Never send fields that aren’t immediately needed or displayed in the UI.</p><ul><li><strong>Stale requests that waste resources</strong>: Old or outdated fetches still run in the background, consuming bandwidth and CPU even when the user has moved on.<br>An example is a user quickly navigating between search pages — if your app doesn’t cancel the old queries, you’ll waste work fetching results that won’t even be shown.<br>Fix it by using <strong>request cancellation (AbortController, cancellation tokens)</strong> so outdated work doesn’t slow down current actions.</li></ul><h3>Safety: Protecting Clients &amp; Servers</h3><p>A few mistakes security-wise include:</p><ul><li><strong>Exposing sensitive data in query params</strong>: Tokens and secrets in URLs leak into server logs, browser history, and analytics tools.<br>An example: GET /reset-password?token=abcd1234 shows up in access logs and referrers.<br>Instead, always send secrets in <strong>headers</strong> or <strong>request bodies</strong> (HTTPS-secured). For instance, an authentication token can be sent as a secure HttpOnly cookie instead of as a query param.</li><li><strong>Not scoping request keys/tokens</strong>: Using the same key across users/sessions. This makes it easier to hijack.<br><strong>Example:</strong> A shared API key lets anyone act on behalf of any user.<br>Fix this by scoping tokens to a <strong>user/session</strong> and apply <strong>least privilege</strong> (a user is granted the least amount of access required for them to do their work). Remember to <strong>rotate and expire them regularly.</strong></li><li><strong>Skipping request validation</strong>: Trusting the client to always send well-formed input is dangerous. Attackers can craft malformed or oversized payloads, and even well-meaning users can send sloppy input.<br>For instance, an<strong> </strong>API crashes because someone POSTs a 10MB string into a username field or a bulk CSV import contains corrupted rows.<br>Ensure you validate <strong>types, formats, and sizes</strong> of incoming requests before processing. Validation is your first line of defense — utilize the <strong>bouncer pattern</strong>, screening and rejecting malformed or oversized payloads before they ever hit your business logic. For instance, you can return early with a descriptive 400 error response or if iterating (say from a CSV file), skip and perform a partial save of valid entities.</li><li><strong>Inconsistent authorization checks</strong>: Some apps only check auth at the controller/endpoint level, but skip checks deeper in the stack.<br><strong>Example:</strong> A “delete user” action is protected, but a background job triggered by /sync-users still runs destructive actions without verifying permissions.<br>A fix is to apply <strong>authorization consistently at every layer</strong> — not just the entry point.</li></ul><h3>Conclusion</h3><p>Requests aren’t fire-and-forget — they’re costly resources, and every mistake compounds at scale. By handling safety, resilience, and efficiency properly, you protect both clients and servers while keeping user-critical paths reliable.</p><p>This article introduced the patterns. In the <em>Requests at Scale</em> series, I’ll dive deeper into each — starting with idempotency keys.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0421e3798e2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Putting Django into Practice: A Step‑by‑Step Backend Project]]></title>
            <link>https://medium.com/@titoadeoye/putting-django-into-practice-a-step-by-step-backend-project-1fe07185d68d?source=rss-9b9003e23766------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fe07185d68d</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[cms]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Tito Adeoye]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 21:29:55 GMT</pubDate>
            <atom:updated>2025-07-27T21:29:55.957Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5bz2oRXaNfv5_Hagu2sI0g.png" /></figure><p>Hello again👋</p><p>So… this article should have been released about a month ago — but the past few weeks have basically been:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*QpqOxADb51f-kqqqwgTiWw.gif" /></figure><p>Anyway, we’re back!<br>In the last few articles, we explored the <strong>foundations of building a Django backend</strong>: models, serializers, views, and how they fit together. But it’s one thing to know the pieces — it’s another to see them come alive in a real project.</p><p>Instead of building yet another generic blog or page-based CMS, let’s do something a little different: we’ll build a <strong>domain‑specific CMS for tailors</strong>.</p><p>Think of it as the <em>Tailor’s Toolkit</em>: an API that lets tailors:</p><ul><li>Save customer details and measurements</li><li>Upload and track inventory data e.g. fabrics and how many yards they have</li><li>Record orders, prices, and currencies</li><li>Upload catalogue images of finished styles</li><li>And view useful metrics: total orders, total revenue, fabric usage over time</li></ul><p>At first glance, this might feel niche — but under the hood, it’s a classic content management system:</p><p>And this project doesn’t stop here. Over time, we’ll use it to explore deeper backend engineering topics:</p><ul><li>🐳 <strong>Docker</strong>: containerize the app and run supporting services like Redis locally</li><li>🏃‍♂️ <strong>Celery</strong>: send emails and run tasks in the background</li><li>⏰ <strong>Scheduled jobs</strong>: e.g., notify tailors when they hit sales milestones</li><li>🗄 <strong>Redis caching</strong>: speed up expensive endpoints like metrics</li><li>🔌<strong>Websockets (Django Channels)</strong>: e.g. facilitate messaging between Tailor and Customer</li><li>☁️ <strong>Production deployment</strong>: from local dev to a real host</li></ul><p>Step by step, you’ll see how a real backend project <strong>starts simple, then evolves</strong> as needs grow — just like in real life.</p><p>In this first part, though, we will keep it focused. We’ll design the models, build the API, and add simple metrics.</p><h3>Plan &amp; design your backend</h3><p>Before jumping into code, it’s important always to figure out exactly what your backend needs to do. <strong>Good architecture</strong> starts with a few simple questions:</p><ul><li>What features do we want?</li><li>What data (models &amp; fields) do we need to store?</li><li>What actions should users be able to perform?</li><li>Who is allowed to do what?</li></ul><p>Let’s answer them.</p><p><strong>What are the necessities?</strong></p><p>Our CMS should let tailors:</p><ul><li>Save information about their customers: names, contact details, measurements</li><li>Keep track of fabric inventory: how many yards they have left, plus a photo</li><li>Record orders: how much the customer paid, in which currency, and when</li><li>Upload photos of finished styles into a catalogue</li><li>See quick business metrics: total revenue this month, number of orders, yards used, etc.</li></ul><p>To keep our codebase tidy, we’ll split these into Django apps:</p><ul><li>customers for customer profiles &amp; measurements</li><li>inventory for fabrics</li><li>orders for order records</li><li>catalogue for style photos</li><li>(and possibly) core for shared utilities, metrics, and future features like notifications</li></ul><h3>What models and fields do we need?</h3><p>We’ll mainly have:</p><p><strong>User (Tailor):</strong><br>Each tailor logs in to manage <em>only their own data</em>.<br>We can use Django’s built-in User model or extend it, but the key idea:<br>every customer, fabric, order, and catalogue item belongs to a single tailor.</p><p><strong>Customer:</strong><br>Stores name, phone number, email, address, measurement unit, and a flexible JSON field for measurements (e.g., chest, waist, sleeve).<br>Each customer is linked to the tailor who created them.</p><p><strong>Inventory:</strong><br>Represents a piece of fabric (could expand on this later on to include others) the tailor owns, with its name, how many yards are left, and a photo.<br>Also linked to the tailor (and optionally to a specific customer, if needed).</p><p><strong>Order:</strong><br>Records when a customer paid for work: amount, down payment, currency, date, optional notes.<br>Linked to both the customer and the tailor.</p><p><strong>CatalogueItem:</strong><br>Stores a photo of a finished style the tailor wants to showcase, with a title and optional description.<br>Also belongs to the tailor.</p><p><strong>Metrics:</strong><br>Not a model, but an endpoint that aggregates data from orders and fabrics.</p><h3>What actions do we want to support?</h3><p>For each model:</p><ul><li>Create a new record</li><li>Retrieve a single record</li><li>Update it</li><li>Delete it</li><li>List all records (filtered by the current logged-in tailor)</li></ul><p>For metrics:</p><ul><li>A read-only endpoint that shows data like total revenue, total number of orders, total yards of fabric remaining.</li></ul><p>Later on, we can add more advanced actions, like:</p><ul><li>Bulk uploads (multiple catalogue items at once)</li><li>Search and filtering</li><li>Nested routes (e.g., list all orders for a single customer)</li></ul><h3>Who can access what?</h3><p>From the very start, we’ll make it <strong>multi-tenant</strong>:</p><ul><li>Each tailor must be logged in</li><li>Each tailor can <em>only</em> see, create, update, or delete their own customers, fabrics, orders, and catalogue items</li><li>Tailor A shouldn’t even know Tailor B’s data exists</li></ul><p>Later, we could:</p><ul><li>Add roles (admin vs. staff)</li><li>Make some data public (e.g., read-only public catalogue)</li></ul><h3>Build the app</h3><p>Alrighty. Now we know what we are building, as well as how we want it to work — time to actually build the thing.</p><p>We’ll start by creating a new Django project and the separate apps that will handle each part of our CMS.</p><p>If you’ve followed my earlier foundational series, you probably remember how to do this. But here’s a quick refresher just in case.</p><p><strong>1. Create and activate a virtual environment</strong></p><pre>python -m venv venv<br>source venv/Scripts/activate</pre><p><strong>2. Install Django and Django REST Framework</strong></p><pre>pip install django djangorestframework</pre><p><strong>3. Start a new Django project</strong></p><p>Replace tailors_toolkit with whatever project name you like:</p><pre>django-admin startproject tailors_toolkit . # . keeps it in the current folder instead of making a subfolder.</pre><p><strong>4. Create the apps</strong></p><p>We decided to split the project into four domain apps right from the start:</p><pre>python manage.py startapp customers<br>python manage.py startapp inventory<br>python manage.py startapp orders<br>python manage.py startapp catalogue<br>python manage.py startapp users</pre><p>You might also create a core app later for metrics or shared utilities.</p><p><strong>5. Register the apps</strong></p><p>Open tailors_toolkit/settings.py and add them to INSTALLED_APPS:</p><pre>INSTALLED_APPS = [<br>    ...<br>    &#39;rest_framework&#39;,<br>    &#39;customers&#39;,<br>    &#39;inventory&#39;,<br>    &#39;orders&#39;,<br>    &#39;catalogue&#39;,<br>    &#39;users&#39;,<br>]</pre><h3>Defining our models</h3><p>Now that we’ve set up our Django project and created our apps, let’s define the actual <strong>models</strong> that will power our tailor’s CMS.</p><p>This is where the database structure comes to life: we’ll write Python classes that describe the <em>things</em> our backend manages, and Django will turn them into database tables.</p><p>Remember, each model:</p><ul><li>Belongs to the currently logged‑in user (tailor)</li><li>Has fields that store the data we planned earlier</li><li>Can later be extended with methods, validations, or special behaviors</li></ul><p>Now, let’s go through each model step by step.</p><p><strong>1. User</strong></p><p>In users/models.py:</p><pre>from django.db import models<br>from django.contrib.auth.models import AbstractUser<br><br># Create your models here.<br>class User(AbstractUser):<br>    role_choices = (<br>        (&#39;tailor&#39;, &#39;Tailor&#39;), # the tailor / service worker who owns catalogue, customers, etc.<br>        (&#39;viewer&#39;, &#39;viewer&#39;), # regular public user who can sign up to browse catalogues or posts<br>        (&#39;admin&#39;, &#39;Admin&#39;), # platform admin with full power<br>        (&#39;Support&#39;, &#39;support&#39;), # can moderate flagged posts, etc.<br>    )<br><br>    username = models.CharField(<br>        max_length=150,<br>        unique=True,<br>        null=True,     # &lt;- allow null in DB<br>        blank=True     # &lt;- allow empty in forms<br>    )<br>    email = models.EmailField(unique=True, null=False, blank=False)<br>    first_name = models.CharField(max_length=60)<br>    last_name = models.CharField(max_length=60, blank=True)<br>    role = models.CharField(max_length=20, choices=role_choices, default=&#39;tailor&#39;, help_text=&#39;Role of the user in the system&#39;)<br>    date_created = models.DateTimeField(auto_now_add=True)<br>    date_updated = models.DateTimeField(auto_now=True)<br> <br>    def __str__(self):<br>        return f&quot;{self.first_name} {self.last_name} ({self.role})&quot;</pre><p>The other roles will become important in later iterations of this product.<br>Ensure to tell Django to use this user model. In your settings.py:</p><pre>AUTH_USER_MODEL = &#39;users.User&#39;</pre><p><strong>2. Customer</strong></p><p>The customer model holds the tailor’s client information and their measurements.</p><pre>from django.db import models<br>from django.db import models<br>from django.conf import settings<br>from phonenumber_field.modelfields import PhoneNumberField<br><br><br>class Customer(models.Model):<br>    MEASUREMENT_UNIT_CHOICES = [<br>        (&quot;metric&quot;, &quot;Metric (cm)&quot;),<br>        (&quot;imperial&quot;, &quot;Imperial (inches)&quot;),<br>    ]<br><br>    GENDER_CHOICES = [(&quot;male&quot;, &quot;Male&quot;), (&quot;female&quot;, &quot;Female&quot;)]<br><br>    user = models.ForeignKey(<br>        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name=&quot;customers&quot;<br>    )<br>    first_name = models.CharField(max_length=60)<br>    last_name = models.CharField(max_length=60, blank=True)<br>    gender = models.CharField(max_length=6, choices=GENDER_CHOICES, blank=True)<br>    email = models.EmailField(blank=True)<br>    address = models.CharField(max_length=255, blank=True)<br>    note = models.TextField(blank=True)<br>    phone_number = PhoneNumberField(blank=True)<br>    measurements = models.JSONField(default=dict, blank=True)<br>    measurement_unit = models.CharField(<br>        max_length=10, choices=MEASUREMENT_UNIT_CHOICES, default=&quot;metric&quot;<br>    )<br>    date_created = models.DateTimeField(auto_now_add=True)<br>    date_updated = models.DateTimeField(auto_now=True)<br><br>    def __str__(self):<br>        return f&quot;{self.first_name} {self.last_name}&quot;</pre><p>For the customer’s phone number, we won’t just use a simple CharField.<br>Instead, we’ll use PhoneNumberField from the django-phonenumber-field package.</p><p>This helps us validate that the number is real, keep it in a consistent format (like +234...), and makes it easier to display or filter later.</p><p>To install, run:</p><pre>pip install &quot;django-phonenumber-field[phonenumberslite]&quot;</pre><p><strong>3. Inventory</strong></p><p>Each tailor can track fabrics they own, including photos.</p><pre>from django.db import models<br>from django.conf import settings<br>from media_file.models import MediaFile<br><br><br># Create your models here.<br>class Inventory(models.Model):<br>    user = models.ForeignKey(<br>        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name=&quot;inventory&quot;<br>    )<br>    name = models.CharField(max_length=255)<br>    description = models.TextField(blank=True)<br>    yards = models.FloatField()<br>    date_created = models.DateTimeField(auto_now_add=True)<br>    date_updated = models.DateTimeField(auto_now=True)<br><br>    def __str__(self):<br>        return self.name</pre><blockquote><em>yards is a float to allow partial yards (e.g., 2.5)</em></blockquote><p><strong>3. Catalogue</strong></p><pre>from django.db import models<br>from django.conf import settings<br>from media_file.models import MediaFile<br><br><br># Create your models here.<br>class CatalogueItem(models.Model):<br>    user = models.ForeignKey(<br>        settings.AUTH_USER_MODEL,<br>        on_delete=models.CASCADE,<br>        related_name=&quot;catalogue_items&quot;,<br>    )<br>    title = models.CharField(max_length=255)<br>    description = models.TextField(blank=True)<br>    date_created = models.DateTimeField(auto_now_add=True)<br>    date_updated = models.DateTimeField(auto_now=True)<br><br>    def __str__(self):<br>        return self.title</pre><p><strong>4. Order</strong></p><pre>from django.db import models<br>from django.conf import settings<br>from customers.models import Customer<br><br><br># Create your models here.<br>class Order(models.Model):<br>    currency_choices = ((&quot;NGN&quot;, &quot;NGN&quot;), (&quot;USD&quot;, &quot;USD&quot;))<br>    status = (<br>        (&quot;in_progress&quot;, &quot;In progress&quot;),<br>        (&quot;completed&quot;, &quot;Completed&quot;),<br>        (&quot;not_started&quot;, &quot;Not started&quot;),<br>    )<br><br>    user = models.ForeignKey(<br>        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name=&quot;orders&quot;<br>    )<br>    customer = models.ForeignKey(<br>        Customer, on_delete=models.CASCADE, related_name=&quot;orders&quot;<br>    )<br>    amount = models.DecimalField(max_digits=10, decimal_places=2)<br>    downpayment = models.DecimalField(<br>        max_digits=10,<br>        decimal_places=2,<br>        default=0,<br>        help_text=&quot;Amount paid as downpayment&quot;,<br>    )<br>    currency = models.CharField(max_length=10, default=&quot;NGN&quot;)<br>    due_date = models.DateField(help_text=&quot;When the order is meant to be delivered&quot;)<br>    notes = models.TextField(blank=True)<br>    is_fully_paid = models.BooleanField(<br>        default=False, help_text=&quot;Has the full payment been completed?&quot;<br>    )<br><br>    date_downpayment_paid = models.DateField(<br>        null=True, blank=True, help_text=&quot;Date the downpayment was actually paid&quot;<br>    )<br>    date_created = models.DateTimeField(auto_now_add=True)<br>    date_updated = models.DateTimeField(auto_now=True)<br><br>    def __str__(self):<br>        return f&quot;Order for  {self.customer.name} on {self.date_created}&quot;</pre><p>To better help tailors manage orders, we added:</p><ul><li>downpayment: how much the client paid upfront.</li><li>date_downpayment_paid: when they actually paid.</li><li>due_date: when the outfit should be ready.</li><li>is_fully_paid: shows whether the full amount has been received.</li></ul><p>This keeps payment tracking simple, yet flexible.</p><p><strong>5. MediaFile</strong></p><p>Instead of saving image URLs directly on every model (like User, CatalogueItem, Fabric), we’ll introduce a dedicated <strong>MediaFile</strong> model.</p><p>This is a common real‑world pattern:</p><ul><li>Keeps media storage <strong>centralized</strong></li><li>Lets us <strong>track metadata</strong> (like upload date, uploader, file type)</li><li>Makes it easy to <strong>reuse</strong> the same media file across different parts of the app</li><li>Keeps your database design <strong>clean and scalable</strong></li></ul><p>To do this:</p><p><strong>Create a new app</strong></p><pre>python manage.py startapp media_file</pre><p>In media_file/models.py:</p><pre>from django.db import models<br>from django.conf import settings<br><br><br># Create your models here.<br>class MediaFile(models.Model):<br>    url = models.URLField()<br>    uploaded_by = models.ForeignKey(<br>        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True<br>    )<br>    file_type = models.CharField(max_length=50, blank=True)<br>    date_created = models.DateTimeField(auto_now_add=True)<br>    date_updated = models.DateTimeField(auto_now=True)<br><br>    def __str__(self):<br>        return self.url</pre><p><strong>Example: linking a user’s profile picture to a MediaFile</strong></p><p>In your users/models.py:</p><pre>from media.models import MediaFile<br><br>class User(AbstractUser):<br><br>    role = models.CharField(max_length=20, choices=ROLE_CHOICES, default=ARTISAN)<br><br>    profile_picture = models.ForeignKey(<br>        MediaFile,<br>        on_delete=models.SET_NULL,<br>        null=True,<br>        blank=True,<br>        related_name=&#39;profile_users&#39;<br>    )<br><br>    # ... rest of the User class</pre><p><strong>Now replicate the same idea</strong> <strong>in:</strong></p><ul><li>CatalogueItem → add a field like picture = models.ForeignKey(MediaFile, ...)</li><li>Inventory → add picture = models.ForeignKey(MediaFile, ...)</li></ul><p>This keeps <em>all</em> images stored consistently — and your backend stays DRY, maintainable, and professional.</p><blockquote><em>Tip: Remember to add “media_file” to INSTALLED_APPS</em></blockquote><p><strong>Apply your new models to the database</strong></p><p>Now that we’ve defined all our models (User, Customer, Order, Inventory, CatalogueItem, and MediaFile), we need to <strong>create the migrations</strong> and <strong>apply them</strong> so Django updates the actual database.</p><p>Run:</p><pre>python manage.py makemigrations<br>python manage.py migrate</pre><p>This tells Django to build the database tables that match the models we just wrote.</p><blockquote><em>Tip: if you add new fields or models later, repeat the same commands to keep your database schema up to date.</em></blockquote><h3>Connect DB</h3><p>Now, we need to connect our Postgres DB (using pgAdmin) to Django. Rather than hardcoding database credentials, we keep them in a .env file (which we <strong>never</strong> commit to git; update .gitignore file).</p><p>We load them in settings.py using python-decouple, so we can safely change DB config for local, staging, or production.</p><p><strong>Step 1: create an</strong> .env <strong>file</strong></p><p>In your project root (same folder as manage.py), create a file called, .env</p><p>Inside, add your database config:</p><pre>DB_NAME=mytailor_db<br>DB_USER=postgres<br>DB_PASSWORD=supersecretpassword<br>DB_HOST=localhost<br>DB_PORT=5432</pre><p><em>(change values to match what you actually created in pgAdmin)</em></p><p><strong>Step 2: load env vars in Django settings</strong></p><p>Install <a href="https://pypi.org/project/python-decouple/">python-decouple</a> (simple &amp; popular):</p><pre>pip install python-decouple</pre><p>In your settings.py:</p><pre>from decouple import config<br>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: &#39;django.db.backends.postgresql&#39;,<br>        &#39;NAME&#39;: config(&#39;DB_NAME&#39;),<br>        &#39;USER&#39;: config(&#39;DB_USER&#39;),<br>        &#39;PASSWORD&#39;: config(&#39;DB_PASSWORD&#39;),<br>        &#39;HOST&#39;: config(&#39;DB_HOST&#39;),<br>        &#39;PORT&#39;: config(&#39;DB_PORT&#39;),<br>    }<br>}</pre><p>This reads your real credentials from .env.</p><p><strong>Step 3: tell Django to use PostgreSQL</strong></p><p>Make sure you have <a href="https://pypi.org/project/psycopg2/">psycopg2</a> installed:</p><pre>pip install psycopg2</pre><p>(or psycopg2-binary for local/dev: pip install psycopg2-binary)</p><p><strong>Now</strong> your project is connected to your PostgreSQL DB (the one you can manage in pgAdmin)🙌<br>After this step, you can safely run:</p><pre>python manage.py migrate</pre><p>Now, if you get this error (cause I did): <em>FATAL: database “tailor_toolkit” does not exist,</em> you know you need to create a database on the pgAdmin GUI called tailors_toolkit (under a server).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KW3tryYwW_05jgVO.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6zzR7MOy3bTLLhj7.png" /></figure><p>And in your DB,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zu1zUHVnZvFNJS2C.png" /></figure><p>Alrighty. We’re halfway there.</p><h3>Next: wiring up URLs and views</h3><p>Now that our models are in place and migrated, it’s time to <strong>expose them through an API.</strong><br>This is what lets the frontend (or tools like Postman) talk to our backend: create users, update inventory, upload catalogue items, and so on.</p><p>In Django REST Framework (DRF), we usually do this in two steps:</p><ol><li><strong>Views</strong> — where we define what actions can happen (list, create, update, delete)</li><li><strong>URLs</strong> — which connect HTTP endpoints (like /api/users/ or /api/orders/) to those views</li></ol><p>A great tip for structure is that for each app (like users, inventory, catalogue):</p><ul><li>add a views.py for your DRF views or viewsets</li><li>add a urls.py to register the routes</li></ul><p>Then in your project’s main urls.py, include those app URLs under something like /api/.</p><p><strong>users/urls.py</strong></p><pre>from rest_framework.routers import DefaultRouter<br>from users.views import UserViewSet<br><br>router = DefaultRouter()<br>router.register(r&#39;users&#39;, UserViewSet, basename=&#39;user&#39;)<br><br>urlpatterns = router.urls</pre><p>Do the same as above for catalogue, customers, inventory, orders, and media_file, making sure to update the route, viewset and base names.</p><p><strong>main project urls.py (e.g.,</strong> myproject/urls.py<strong>)</strong></p><pre>from django.contrib import admin<br>from django.urls import path, include<br><br>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;api/&#39;, include(&#39;users.urls&#39;)),<br>    path(&#39;api/&#39;, include(&#39;catalogue.urls&#39;)),<br>    path(&#39;api/&#39;, include(&#39;customers.urls&#39;)),<br>    path(&#39;api/&#39;, include(&#39;inventory.urls&#39;)),<br>    path(&#39;api/&#39;, include(&#39;orders.urls&#39;)),<br>    path(&#39;api/&#39;, include(&#39;media_file.urls&#39;)),<br>]</pre><p>All our app routes are now grouped under /api/.<br>For example: /api/users/, /api/catalogue/, /api/fabrics/ etc.</p><h3>Now, draft your views</h3><p>In each app’s views.py, start simple with DRF ModelViewSet.</p><p>Using ModelViewSet from DRF automatically gives you <strong>all CRUD operations</strong> out of the box:</p><p>✅ List (GET /api/things/)<br>✅ Retrieve (GET /api/things/{id}/)<br>✅ Create (POST)<br>✅ Update / partial update (PUT/PATCH)<br>✅ Delete (DELETE)</p><p><strong>users/views.py</strong></p><pre>from rest_framework import viewsets<br>from users.models import User<br>from users.serializers import UserSerializer<br><br>class UserViewSet(viewsets.ModelViewSet):<br>    queryset = User.objects.all()<br>    serializer_class = UserSerializer</pre><p>Do the same as above for catalogue, customers, inventory, orders, and media_file, making sure to update the route, viewset and base names.</p><h3>Draft your serializers</h3><p>Now, here are the <strong>serializers</strong> for all the models we defined — clean, starter code so your API works right away.</p><p><strong>users/serializers.py</strong></p><pre>from rest_framework import serializers<br>from users.models import User<br>from media.serializers import MediaFileSerializer<br><br>class UserSerializer(serializers.ModelSerializer):<br>    profile_picture = MediaFileSerializer(read_only=True)<br><br>    class Meta:<br>        model = User<br>        fields = [<br>            &#39;id&#39;, &#39;first_name&#39;, &#39;last_name&#39;, &#39;email&#39;, &#39;role&#39;,<br>            &#39;date_created&#39;, &#39;date_updated&#39;,<br>            &#39;profile_picture&#39;,<br>        ]</pre><p><em>Using nested</em> MediaFileSerializer <em>as read-only, so it shows the S3 URL &amp; metadata.</em></p><p><strong>orders/serializers.py</strong></p><pre>from rest_framework import serializers<br>from orders.models import Order<br><br><br>class OrderSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Order<br>        fields = &quot;__all__&quot;</pre><p>Do the same as above for catalogue, customers, inventory, and media_file, making sure to update the class and model and names, as well as the fields to be returned.</p><h3>Authentication &amp; Permissions</h3><p>This answers part of the “Who is allowed to do what?” question when we were designing our backend system.</p><p>We need:</p><ul><li>Auth endpoints: register (signup) &amp; login</li><li>To add IsAuthenticated permission globally so only logged‑in users can access the APIs</li></ul><p>Let’s do it!</p><p>Since it’s an API, DRF’s <strong>TokenAuthentication</strong> is simple &amp; perfect for now.<br>Later on, in another article, we will replace with JWT or OAuth or Cookies.</p><p><strong>Step 1: install &amp; setup tokens</strong></p><p>Install DRF’s token auth (usually already installed with DRF):</p><p>Add to INSTALLED_APPS in <a href="http://settings.py/">settings.py</a>:</p><pre>INSTALLED_APPS = [<br># ...,<br>&#39;rest_framework&#39;,<br>&#39;rest_framework.authtoken&#39;,<br>]</pre><p>Then run migrations to create the token table:</p><pre>python manage.py migrate</pre><p><strong>Spot authtoken_token✅</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/0*dN3zW_tDHeruV_9X.png" /></figure><p><strong>Step 2: create auth endpoints</strong></p><p>Create a new app:</p><pre>python manage.py startapp authentication</pre><p>authentication/views.py</p><pre>from django.shortcuts import render<br><br># Create your views here.<br>from rest_framework.authtoken.models import Token<br>from rest_framework.decorators import api_view, permission_classes<br>from rest_framework.permissions import AllowAny<br>from rest_framework.response import Response<br>from django.contrib.auth import authenticate<br>from users.models import User<br>from django.utils.crypto import get_random_string<br><br><br>@api_view([&quot;POST&quot;])<br>@permission_classes([AllowAny])<br>def register(request):<br>    VALID_ROLES = [choice[0] for choice in User.role_choices]<br><br>    first_name = request.data.get(&quot;first_name&quot;)<br>    last_name = request.data.get(&quot;last_name&quot;)<br>    password = request.data.get(&quot;password&quot;)<br>    email = request.data.get(&quot;email&quot;)<br>    role = request.data.get(&quot;role&quot;, &quot;tailor&quot;)<br>    username = request.data.get(&quot;username&quot;)  # optional<br><br>    if not first_name or not password or not email:<br>        return Response(<br>            {&quot;error&quot;: &quot;First name, password and email are required.&quot;}, status=400<br>        )<br><br>    if role not in VALID_ROLES:<br>        return Response(<br>            {&quot;error&quot;: f&quot;Invalid role. Must be one of: {VALID_ROLES}&quot;}, status=400<br>        )<br><br>    # if username not provided, generate one<br>    if not username:<br>        while True:<br>            username = get_random_string(10)<br>            if not User.objects.filter(username=username).exists():<br>                break<br><br>    user = User.objects.create_user(<br>        username=username,<br>        first_name=first_name,<br>        last_name=last_name,<br>        password=password,<br>        email=email,<br>        role=role,<br>    )<br>    token, created = Token.objects.get_or_create(user=user)<br>    return Response(<br>        {<br>            &quot;token&quot;: token.key,<br>            &quot;user&quot;: {<br>                &quot;id&quot;: user.id,<br>                &quot;username&quot;: user.username,<br>                &quot;email&quot;: user.email,<br>                &quot;role&quot;: user.role,<br>                &quot;first_name&quot;: user.first_name,<br>                &quot;last_name&quot;: user.last_name,<br>            },<br>        }<br>    )<br><br><br>@api_view([&quot;POST&quot;])<br>@permission_classes([AllowAny])<br>def login(request):<br>    email = request.data.get(&quot;meail&quot;)<br>    password = request.data.get(&quot;password&quot;)<br><br>    user = authenticate(email=email, password=password)<br>    if user:<br>        token, created = Token.objects.get_or_create(user=user)<br>        return Response(<br>            {<br>                &quot;token&quot;: token.key,<br>                &quot;user&quot;: {<br>                    &quot;id&quot;: user.id,<br>                    &quot;username&quot;: user.username,<br>                    &quot;email&quot;: user.email,<br>                    &quot;role&quot;: user.role,<br>                    &quot;first_name&quot;: user.first_name,<br>                    &quot;last_name&quot;: user.last_name,<br>                },<br>            }<br>        )<br>    else:<br>        return Response({&quot;error&quot;: &quot;Invalid credentials&quot;}, status=400)</pre><p><strong>authentication/urls.py</strong></p><pre>from django.urls import path<br>from authentication.views import register, login<br><br>urlpatterns = [<br>    path(&#39;register/&#39;, register, name=&#39;register&#39;),<br>    path(&#39;login/&#39;, login, name=&#39;login&#39;),<br>]</pre><p><strong>Step 3: protect all APIs with</strong> IsAuthenticated</p><p>In settings.py:</p><pre>REST_FRAMEWORK = {<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: [<br>        &#39;rest_framework.authentication.TokenAuthentication&#39;,<br>    ],<br>    &#39;DEFAULT_PERMISSION_CLASSES&#39;: [<br>        &#39;rest_framework.permissions.IsAuthenticated&#39;,<br>    ],<br>}</pre><p>Now, all our viewsets (users, catalogue, inventory, orders, media) automatically require the user to be logged in and send their token in the header:</p><pre>Authorization: Token &lt;token_value&gt;</pre><p><strong>Step 4: include auth URLs in main urls.py</strong></p><p>In the main urls.py:</p><p>Then run migrations to create the token table:</p><pre>urlpatterns = [<br>    # ... other paths<br>    path(&#39;api/auth/&#39;, include(&#39;authentication.urls&#39;)),<br>]</pre><p>Now we have:</p><ul><li>/api/auth/register/ → create user &amp; get token</li><li>/api/auth/login/ → login &amp; get token</li><li>All other APIs protected by IsAuthenticated</li></ul><h3>Testing the API</h3><p>Now that our models, views, serializers, and auth endpoints are wired up, it’s time to <strong>test everything end‑to‑end</strong>.</p><p>You can use:<br>✅ Postman<br>✅ Django GUI<br>✅ Or even curl if you like the terminal</p><p>I’m using the GUI. Why? I closed my eyes and pointed.</p><h3>1. Start your server</h3><pre>python manage.py runserver</pre><p>You should see:</p><pre>Starting development server at http://127.0.0.1:8000/</pre><h3>2. Register a user</h3><ul><li><strong>Method:</strong> POST</li><li><strong>URL:</strong> <a href="http://127.0.0.1:8000/api/auth/register/">http://127.0.0.1:8000/api/auth/register/</a></li><li><strong>Body (JSON):</strong></li></ul><pre>{<br>  &quot;first_name&quot;: &quot;john&quot;,<br>  &quot;last_name&quot;: &quot;doe&quot;,<br>  &quot;password&quot;: &quot;supersecret&quot;,<br>  &quot;email&quot;: &quot;johndoe@example.com&quot;,<br>  &quot;role&quot;: &quot;tailor&quot; // optional. tailor is default<br>}</pre><p>You should get back:</p><pre>{<br>  &quot;token&quot;: &quot;abcdef123456...&quot;,<br>  &quot;user&quot;: {<br>     &quot;user_id&quot;: 1,<br>     &quot;username&quot;: &quot;xxxxx&quot;,<br>     &quot;role&quot;: &quot;artisan&quot;, <br>     &quot;first_name&quot;: &quot;john&quot;,<br>     &quot;last_name&quot;: &quot;doe&quot;,<br>     &quot;date_created&quot;: &quot;2025-07-27T18:46:27.328025Z&quot;,<br>     &quot;date_updated&quot;: &quot;2025-07-27T18:46:27.328025Z&quot;,<br>}</pre><h3>3. Log in</h3><ul><li><strong>POST</strong> to <a href="http://127.0.0.1:8000/api/auth/login/">http://127.0.0.1:8000/api/auth/login/</a></li><li>Body:</li></ul><pre>{<br>  &quot;email&quot;: &quot;johndoe@example.com&quot;,<br>  &quot;password&quot;: &quot;supersecret&quot;<br>}</pre><p>You’ll get the same kind of token back.</p><h3>4. Access your protected APIs</h3><p>For Postman or — curl, add the Token you get after login to your headers.</p><pre>Authorization: Token your_token_here</pre><blockquote><em>Without this, you’ll get: </em><em>{&quot;detail&quot;:&quot;Authentication credentials were not provided.&quot;}</em></blockquote><p>If you’re on the GUI, like me, add &#39;rest_framework.authentication.SessionAuthentication&#39; to your DEFAULT_AUTHENTICATION_CLASSES:</p><pre>REST_FRAMEWORK = {<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: [<br>        &#39;rest_framework.authentication.TokenAuthentication&#39;,<br>        &#39;rest_framework.authentication.SessionAuthentication&#39;,<br>    ],<br>    &#39;DEFAULT_PERMISSION_CLASSES&#39;: [<br>        &#39;rest_framework.permissions.IsAuthenticated&#39;,<br>    ],<br>}</pre><p>And in your view</p><pre>from django.contrib.auth import get_user_model, login as django_login<br><br>def login(request):<br>    email = request.data.get(&quot;email&quot;)<br>    password = request.data.get(&quot;password&quot;)<br><br>    try:<br>        user = User.objects.get(email=email)<br>    except User.DoesNotExist:<br>        return Response({&quot;error&quot;: &quot;Invalid credentials&quot;}, status=400)<br><br>    if user.check_password(password):<br>        # ✅ Create session<br>        django_login(request, user)<br><br>        # ✅ Create/get token<br>        token, created = Token.objects.get_or_create(user=user)<br><br>        # ...</pre><p>Then when you login via Django admin → your browser has a session cookie → browsable API shows you as authenticated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wFh9vSj72G-8LoHg.png" /></figure><p>We’re calling django_login(request, user) so Django creates a <strong>session cookie</strong>.</p><p>That way, when we use the <strong>DRF browsable API</strong> in the browser, it <em>sees us as logged in</em> at the top‑right corner — without needing to open Postman or manually add token headers.</p><p>This is perfectly fine for <strong>development</strong> because it makes testing easier and keeps us lazy &amp; happy.<br>In production, your frontend should instead always send the Authorization: Token &lt;token&gt; header.</p><h3>5. Try CRUD</h3><p>Try:</p><ul><li>POST to /api/catalogue/ → create a catalogue item</li><li>GET to /api/catalogue/ → list your items</li><li>PATCH to /api/catalogue/{id}/ → update</li><li>DELETE → delete</li></ul><p>Same for inventory, orders, etc.</p><p><strong>Example</strong>: Create a customer</p><pre>{<br>    &quot;first_name&quot;: &quot;velma&quot;,<br>    &quot;last_name&quot;: &quot;thorfinn&quot;,<br>    &quot;gender&quot;: &quot;female&quot;,<br>    &quot;email&quot;: &quot;velmathorfinn@yahoo.com&quot;,<br>    &quot;address&quot;: &quot;&quot;,<br>    &quot;note&quot;: &quot;a note on velma&quot;,<br>    &quot;phone_number&quot;: &quot;+2349090909090&quot;,<br>    &quot;measurements&quot;: {<br>        &quot;waist&quot;: 100<br>    },<br>    &quot;user&quot;: 1<br>}</pre><h3>6. Check your DB</h3><p>Open pgAdmin → see tables:</p><ul><li>users_user</li><li>catalogue_catalogueitem</li><li>inventory_inventory</li><li>orders_order</li><li>media_file_mediafile</li><li>authtoken_token</li></ul><p>You should see real data inside.</p><p>From my example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BaV_Maspb3z8mGhG.png" /></figure><h3>Add dashboard metrics</h3><p>For now, we’ll keep it simple and add this metrics view inside the users app (or the core app like I’d originally planned. Oops!).<br>Later, if our analytics get bigger (e.g., weekly reports, charts, time‑based metrics), we could split them into a dedicated metrics or analytics app.</p><p>In users/views.py (or core/views.py):</p><pre># ...other imports<br>from rest_framework.decorators import api_view, permission_classes<br>from rest_framework.permissions import IsAuthenticated<br>from rest_framework.response import Response<br>from orders.models import Order<br>from inventory.models import Inventory<br>from catalogue.models import Catalogue<br>from customers.models import Customer<br><br># class<br><br>@api_view([&quot;GET&quot;])<br>@permission_classes([IsAuthenticated])<br>def user_metrics(request):<br>    user = request.user<br><br>    total_orders = Order.objects.filter(user=user).count()<br>    total_revenue = (<br>        Order.objects.filter(user=user, is_fully_paid=True).aggregate(<br>            total=models.Sum(&quot;amount&quot;)<br>        )[&quot;total&quot;]<br>        or 0<br>    )<br>    total_inventory_yards = (<br>        Inventory.objects.filter(user=user).aggregate(total=models.Sum(&quot;yards&quot;))[<br>            &quot;total&quot;<br>        ]<br>        or 0<br>    )<br>    catalogue_items = Catalogue.objects.filter(user=user).count()<br>    total_customers = Customer.objects.filter(user=user).count()<br><br>    return Response(<br>        {<br>            &quot;total_orders&quot;: total_orders,<br>            &quot;total_revenue&quot;: total_revenue,<br>            &quot;total_inventory_yards&quot;: total_inventory_yards,<br>            &quot;catalogue_items&quot;: catalogue_items,<br>            &quot;total_customers&quot;: total_customers,<br>        }<br>    )</pre><p>In users/urls.py:</p><pre>from rest_framework.routers import DefaultRouter<br>from users.views import UserViewSet, user_metrics<br>from django.urls import path<br><br><br>router = DefaultRouter()<br>router.register(r&quot;users&quot;, UserViewSet, basename=&quot;user&quot;)<br><br>urlpatterns = [<br>    *router.urls,<br>    path(&quot;dashboard/&quot;, user_metrics, name=&quot;dashboard&quot;),<br>]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nc6dCoJnMPBpezny.png" /></figure><h3>That’s it!</h3><p>From defining our models, to wiring up serializers, views, auth, and even setting up media uploads, we now have a solid, working Django REST Framework backend for our tailor toolkit.</p><p>Of course, there’s always room for improvement — and that’s the fun part. For instance:</p><ul><li>When creating a customer, the backend should automatically set the user field from the logged‑in user (request.user) instead of relying on the client to send it.</li><li>We could generate usernames in a cleaner, more meaningful way.</li><li>Our permissions could be refined so only owners can modify their own resources.</li></ul><p>This project is a solid foundation you can build on — and that’s exactly what we’ll do.<br>Later, we can explore adding:</p><ul><li>Celery for background jobs (like sending email notifications)</li><li>Redis for caching</li><li>Docker to containerize everything</li><li>Even exposing parts of the app publicly so real customers can view catalogs</li><li>And yes — you probably noticed: while we prepared the MediaFile model for S3 storage, we didn’t actually wire it up to S3 yet. That’s definitely something to explore next.</li></ul><p><strong>Remember:</strong> building a backend is an iterative process. Start simple, get it working, then make it better.</p><p>Thanks for following along — and happy building! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fe07185d68d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Backend Foundations: Extending with Django REST Framework]]></title>
            <link>https://medium.com/@titoadeoye/django-backend-foundations-extending-with-django-rest-framework-b28aad6eef53?source=rss-9b9003e23766------2</link>
            <guid isPermaLink="false">https://medium.com/p/b28aad6eef53</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[serializers]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Tito Adeoye]]></dc:creator>
            <pubDate>Sat, 14 Jun 2025 09:40:06 GMT</pubDate>
            <atom:updated>2025-06-14T09:40:06.121Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bpejsUOB4pOKG6o34BToeA.png" /></figure><p>You’ve set up your project, defined your models, and taken full advantage of Django’s powerful built-in features. Now it’s time to take things one step further — into the world of APIs.</p><p><strong>Django REST Framework (DRF)</strong> is the toolkit that turns Django into an API powerhouse. While Django itself is more geared toward rendering HTML via templates, DRF extends that foundation to serve structured data — typically JSON — to frontend apps, mobile clients, or other services.</p><p>In other words:<br><strong>Django is great at building websites. DRF makes it great at building APIs.</strong></p><h3>Add DRF to the mix:</h3><pre>pip install djangorestframework</pre><p>And add it to INSTALLED_APPS in settings.py:</p><pre>INSTALLED_APPS = [<br>  ...,<br>  &#39;rest_framework&#39;,<br>]</pre><p>Now, DRF doesn’t replace Django. It <strong>extends</strong> it — adding tools that make it easy to <strong>build and manage APIs</strong>. Without it, you’d be hand-coding JSON responses and parsing incoming payloads. DRF gives you structure, validation, and control.</p><ul><li>While Django by default is more HTML/template-oriented, DRF gives you:</li><li>API views</li><li>Serializers (for transforming models/data to JSON)</li><li>Browsable API interface (a huge dev UX win)</li><li>Authentication, permissions, throttling</li><li>Pagination, filtering, etc.</li></ul><p>DRF turns Django into a <strong>powerful backend for modern web or mobile apps</strong> that consume JSON over HTTP.</p><p>It provides:</p><h3>Serializers:</h3><p>which are the heart of DRF. They do two major things:</p><ul><li><strong>Serialization (Outgoing Data):</strong> convert complex data (like model instances e.g. the Profile model) into native Python datatypes (like dictionaries, lists, strings) that can then be easily rendered into data formats such as JSON or XML, suitable for API responses (outgoing data).</li><li><strong>Deserialization &amp; Validation (Incoming Data):</strong> take incoming data from the client (e.g., JSON received in an HTTP POST request), parse it into native Python data types, thoroughly validating it against a defined schema, and then converting it into complex Python data types (like Django model instances) for database operations.</li></ul><p><strong>A Basic Example</strong></p><p>Let’s work with a basic example. Do the following:</p><ol><li>create a library app</li><li>register it in settings.py</li></ol><p>Then in library/models.py:</p><pre># library/models.py<br>from django.db import models<br><br># Create your models here.<br>class Book(models.Model):<br>    title = models.CharField(max_length=100)<br>    author = models.CharField(max_length=100)<br>    published = models.DateField()</pre><p>Finally, create a serializers.py file</p><h3>Model to JSON: ModelSerializer</h3><p>DRF provides a ModelSerializer that auto-generates serializer fields based on the model.</p><pre>from rest_framework import serializers<br>from .models import Book<br><br>class BookSerializer(serializers.ModelSerializer):<br>    # to configure behavior<br>    class Meta:<br>        model = Book<br>        fields = [&#39;id&#39;, &#39;title&#39;, &#39;author&#39;, &#39;published&#39;]<br>        # read_only_fields = [&#39;id&#39;] # optionally make fields read-only; will not be accepted during create(), update()<br>        # extra_kwargs = {&#39;bio&#39;: {&#39;min_length&#39;: 5}} # add extra validation/options<br>        # exclude = [&#39;bio&#39;] # fields from the model to be excluded</pre><p>So <strong>you don’t need to define</strong> each field manually like this:</p><pre>title = serializers.CharField(max_length=100)<br>author = serializers.CharField(max_length=100)<br>published = serializers.DateField()</pre><p>That’s what ModelSerializer saves you from doing. It is the most commonly used serializer. It provides a convenient shortcut for creating serializers that directly map to Django models.</p><p><strong>Practice in the shell:</strong></p><pre>python manage.py shell</pre><pre>from library.models import Book<br>from library.serializers import BookSerializer<br><br>book = Book.objects.create(title=&quot;Animal Farm&quot;, author=&quot;George Orwell&quot;, published=&quot;1945-08-17&quot;)<br>serializer = BookSerializer(book)<br>print(serializer.data)</pre><p>Without the serializer, you get a complex “unreadable” model instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/0*xWr0VUBmZp5wSh_1.png" /></figure><p>With the serializer, you get your data in a readable, python datatype; a dictionary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t6Gj5ntE6I3JKFIx.png" /></figure><p>This is ready to become JSON in your API response.</p><h3>From JSON to Model: Deserialization &amp; Validation</h3><p>You can also take incoming JSON, validate it, and turn it into a model instance.</p><p><strong>Practice in the shell:</strong></p><pre>data = {&#39;title&#39;: &#39;Brave New World&#39;, &#39;author&#39;: &#39;Aldous Huxley&#39;, &#39;published&#39;: &#39;1932-01-01&#39;}<br>serializer = BookSerializer(data=data)<br><br>if serializer.is_valid():<br>    book = serializer.save()<br>    print(book)<br>else:<br>    print(serializer.errors)</pre><p>And that’s it! You get your model instance back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eNoXWC5uASsYgF3Q.png" /></figure><p>Use Shift+Enter to move on to the next line in your terminal without running the command. Remember your indentation blocks, as well.</p><p>DRF:</p><ul><li>Validates the data based on your model field types</li><li>Saves it if valid (Peep the QuerySet at the bottom with 2 items)</li><li>Returns errors if something is wrong (e.g., missing fields or bad formats)</li></ul><p>What if you wanted to have your own <strong>custom validation?</strong> Here’s how:</p><pre>class BookSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Book<br>        fields = [&#39;id&#39;, &#39;title&#39;, &#39;author&#39;, &#39;published&#39;]<br><br>    # validation function<br>    def validate_title(self, value):<br>        if &quot;bad&quot; in value.lower():<br>            raise serializers.ValidationError(&quot;This book title is not allowed.&quot;)<br>        return value</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*__C0BwOHpcd77tKT.png" /></figure><p>If you get True when checking if the instance is valid, restart your shell.</p><p>You may be wondering where I came up with the validate_title function. I didn’t. It’s a convention. To add validation for a field, you initialize the validate function using this format: validate_[fieldname] and when you run is_valid(), DRF <strong>automatically detects and calls it</strong> during validation of that specific field. That means you can also run validate_author() and validate_published().</p><p>For cross-field validation or when your validation depends on multiple values:</p><pre>def validate(self, attrs):<br>    if attrs[&#39;author&#39;] == attrs[&#39;title&#39;]:<br>        raise serializers.ValidationError(&quot;Author and title can&#39;t be the same.&quot;)<br>    return attrs</pre><p>If you try to save without validating:</p><pre>data = {&quot;title&quot;: &quot;bad&quot;, &quot;author&quot;: &quot;Aldous Huxley&quot;, &quot;published&quot;: &quot;1932-01-01&quot;}<br>serializer = BookSerializer(data=data)<br>serializer.save()    <br>Traceback (most recent call last):<br>  File &quot;&lt;console&gt;&quot;, line 1, in &lt;module&gt;<br>  File &quot;C:\Python312\Lib\site-packages\rest_framework\serializers.py&quot;, line 178, in save<br>    assert hasattr(self, &#39;_errors&#39;), (<br>           ^^^^^^^^^^^^^^^^^^^^^^^^<br>AssertionError: You must call `.is_valid()` before calling `.save()`.</pre><p>So, when you call is_valid(), DRF runs:</p><ul><li><strong>Built-in field validation</strong> (e.g., required=True, max_length)</li><li>Your custom validate_&lt;fieldname&gt; methods</li><li>Any validators passed directly to the field</li><li>And finally, the validate(self, attrs) method (for cross-field validation)</li></ul><p>Note that you can also attach one or more custom validator functions like this:</p><pre>def no_numbers(value):<br>    if any(char.isdigit() for char in value):<br>        raise serializers.ValidationError(&quot;Numbers are not allowed.&quot;)<br><br>author = serializers.CharField(validators=[no_numbers])</pre><p>Or create reusable validator classes like this:</p><pre>from rest_framework import serializers<br><br>class MustStartWithCapital:<br>    def __call__(self, value):<br>        if not value[0].isupper():<br>            raise serializers.ValidationError(&quot;Must start with a capital letter.&quot;)<br><br>title = serializers.CharField(validators=[MustStartWithCapital()])</pre><p>serializers.ModelSerializer is a convenient shortcut <strong>when your data maps to a Django model</strong>, but there are many cases where you’re not working with models at all. That&#39;s where the <strong>base class</strong> serializers.Serializer comes in.</p><h3>serializers.Serializer — The Base Class</h3><p>You use this when:</p><ul><li>You’re not working with a Django model.</li><li>You want <strong>manual control</strong> over fields and validation.</li><li>You’re accepting or sending arbitrary JSON data — like for third-party APIs, config files, or simple data transforms.</li></ul><p><strong>A basic example:</strong></p><p>Let’s build a serializer to accept a basic contact form:</p><pre>from rest_framework import serializers<br><br>class ContactSerializer(serializers.Serializer):<br>    name = serializers.CharField(max_length=100)<br>    email = serializers.EmailField()<br>    message = serializers.CharField()<br><br>    def validate_name(self, value):<br>        if not value[0].isupper():<br>            raise serializers.ValidationError(&quot;Name must start with a capital letter.&quot;)<br>        return value<br><br>    def validate(self, data):<br>        message = data.get(&quot;message&quot;, None)<br>        if message is not None and &quot;help&quot; not in message.lower():<br>            raise serializers.ValidationError(&quot;Message must include the word &#39;help&#39;.&quot;)<br>        return data</pre><p>This:</p><ul><li><strong>Defines fields manually (See list of field types in</strong> <a href="https://medium.com/@titoadeoye/django-backend-foundations-building-blocks-apps-models-and-views-b6543b586eb4"><strong>Part 2</strong></a><strong>)</strong></li><li>Supports <strong>custom per-field validation</strong></li><li>Allows <strong>cross-field validation</strong> with validate(self, data)</li></ul><p><strong>How we use this</strong></p><pre># library/views.py<br>def contact_form:<br>    data = {<br>        &quot;name&quot;: &quot;Alice&quot;,<br>        &quot;email&quot;: &quot;alice@example.com&quot;,<br>        &quot;message&quot;: &quot;I need help with your service&quot;<br>    }<br>    <br>    serializer = ContactSerializer(data=data)<br>    <br>    if serializer.is_valid():<br>        print(serializer.validated_data)<br>    else:<br>        print(serializer.errors)</pre><p>Notice:</p><ul><li>There’s <strong>no</strong> .save() unless <strong>you implement it yourself.</strong></li><li>You’re in full control over what “saving” means — could be sending an email, writing to a log, or making an API call.</li></ul><p>If you want to mimic ModelSerializer behavior, you can define your own methods:</p><pre># serializers.py<br>def create(self, validated_data):<br>    # e.g create a user object and immediately link it to a profile<br>    user = User.objects.create(**validated_data)<br>    Profile.objects.create(user=user)<br>    return user<br><br>def update(self, instance, validated_data):<br>    if &#39;status&#39; in validated_data and validated_data[&#39;status&#39;] == &#39;archived&#39;:<br>        instance.archived_at = timezone.now()<br>        # other business logic like logging<br><br>    for attr, value in validated_data.items():<br>        setattr(instance, attr, value)<br><br>    instance.save()<br>    return instance</pre><p>But DRF won’t call them unless you invoke .save() — just like with ModelSerializer(which has it’s create() and update() methods generated automatically)</p><p>Now if we want to save:</p><pre># library/serializers.py<br>class ContactSerializer(serializers.Serializer):<br>    # ...<br>    # commented out the second validate function btw; add help to your message if you don&#39;t want to<br><br>    def create(self, validated_data):<br>        # In a real app, you might send this data to email or save in a model<br>        print(&quot;Contact submission received!&quot;)<br>        print(f&quot;From: {validated_data[&#39;name&#39;]} &lt;{validated_data[&#39;email&#39;]}&gt;&quot;)<br>        print(f&quot;Message: {validated_data[&#39;message&#39;]}&quot;)<br>        return validated_data  # no DB, so we just return the data</pre><pre># in shell<br> data = {<br>    &quot;name&quot;: &quot;tito&quot;, # will trigger an error; write it better for smooth sailing<br>    &quot;email&quot;: &quot;tito@example.com&quot;,<br>    &quot;message&quot;: &quot;Hey, can we chat?&quot;<br>}<br><br>serializer = ContactSerializer(data=data)<br><br>if serializer.is_valid():<br>    serializer.save()<br>else:<br>    print(serializer.errors)</pre><p>You should get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d03g53QMTM2kXL0S.png" /></figure><p><strong>Create multiple objects:</strong></p><pre>data = [<br>    {&quot;id&quot;: 1, &quot;title&quot;: &quot;Updated Book 1&quot;, &quot;author&quot;: &quot;New Author 1&quot;, &quot;published&quot;: &quot;2000-01-01&quot;},<br>    {&quot;id&quot;: 2, &quot;title&quot;: &quot;Updated Book 2&quot;, &quot;author&quot;: &quot;New Author 2&quot;, &quot;published&quot;: &quot;2010-02-02&quot;},<br>]<br>serializer = BookSerializer(data=data, many=True)<br>serializer.is_valid()<br>serializer.save()</pre><p><strong>How</strong> .save() <strong>decides between</strong> create() <strong>and</strong> update()</p><p>DRF checks <strong>whether the serializer was initialized with an instance or not</strong>:</p><pre># create a new object<br>serializer = BookSerializer(data=data)  # no instance passed<br>serializer.is_valid()<br>serializer.save()  # calls create()<br><br># update an existing object (partial=True; to pass only some of the model&#39;s fields)<br>serializer = BookSerializer(instance=book, data=data, partial=True) # an instance is an already existing object<br>serializer.is_valid()<br>serializer.save()  # calls update()</pre><p>To update:</p><pre># can&#39;t actually persist for non-model serializers<br>def update(self, instance, validated_data):<br>        for attr, value in validated_data.items():<br>            setattr(instance, attr, value)<br>        return instance</pre><h3>Nested Serializers</h3><p>Let’s say a Profile belongs to a User.</p><pre># models.py<br>from django.contrib.auth.models import User<br><br>class Profile(models.Model):<br>    user = models.OneToOneField(User, on_delete=models.CASCADE)<br>    bio = models.TextField(blank=True)</pre><p>Now, to include the full user data in the profile API, not just the ID:</p><pre># serializers.py<br>from django.contrib.auth.models import User<br><br>class UserSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = User<br>        fields = [&#39;id&#39;, &#39;username&#39;, &#39;email&#39;]<br><br>class ProfileSerializer(serializers.ModelSerializer):<br>    user = UserSerializer(read_only=True)<br><br>    class Meta:<br>        model = Profile<br>        fields = [&#39;id&#39;, &#39;user&#39;, &#39;bio&#39;]</pre><p>In views, this would return:</p><pre>{<br>  &quot;id&quot;: 1,<br>  &quot;user&quot;: {<br>    &quot;id&quot;: 5,<br>    &quot;username&quot;: &quot;tito&quot;,<br>    &quot;email&quot;: &quot;tito@example.com&quot;<br>  },<br>  &quot;bio&quot;: &quot;Backend developer&quot;<br>}</pre><p>If you want to <strong>create or update the related user from this serializer</strong>, you’ll need to override create() or update().</p><p>Example:</p><pre>class ProfileSerializer(serializers.ModelSerializer):<br>    user = UserSerializer()<br><br>    class Meta:<br>        model = Profile<br>        fields = [&#39;id&#39;, &#39;user&#39;, &#39;bio&#39;]<br><br>    def create(self, validated_data):<br>        user_data = validated_data.pop(&#39;user&#39;)<br>        user = User.objects.create(**user_data)<br>        profile = Profile.objects.create(user=user, **validated_data)<br>        return profile</pre><p>Practice:</p><pre># in shell<br>data = {<br>  &quot;user&quot;: {&quot;username&quot;: &quot;jane&quot;, &quot;email&quot;: &quot;jane@example.com&quot;},<br>  &quot;bio&quot;: &quot;Fullstack dev&quot;<br>}<br><br>serializer = ProfileSerializer(data=data)<br>if serializer.is_valid():<br>    profile = serializer.save()<br>    print(profile)</pre><h3>Browsable API interface:</h3><p>The <strong>Browsable API</strong> is a web-based interface that DRF provides when you hit your API endpoints via a browser (instead of something like Postman or curl). It’s automatically generated and interactive.</p><h3>Example:</h3><p>When you visit http://localhost:8000/api/books/, you might see a clean form to:</p><ul><li>Submit POST data via a web form</li><li>Browse paginated GET results</li><li>See validation errors in real time</li><li>Test your endpoints without writing frontends</li></ul><p>The Browsable API is rendered using:</p><ul><li>DRF’s BrowsableAPIRenderer</li><li>Which is enabled by default in your DEFAULT_RENDERER_CLASSES setting</li></ul><pre># settings.py<br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_RENDERER_CLASSES&#39;: [<br>        &#39;rest_framework.renderers.JSONRenderer&#39;,<br>        &#39;rest_framework.renderers.BrowsableAPIRenderer&#39;,<br>    ]<br>}</pre><p>If you <strong>only want JSON responses</strong> (e.g., in production), you can remove &#39;BrowsableAPIRenderer&#39; — but it’s very helpful in dev.</p><p>Let’s try it out</p><ol><li>Create a basic view:</li></ol><pre>from rest_framework import generics<br>from .models import Book<br>from .serializers import BookSerializer<br><br>class BookListCreateView(generics.ListCreateAPIView):<br>    queryset = Book.objects.all()<br>    serializer_class = BookSerializer</pre><p>2. Add to urls.py<a href="http://localhost:8000/api/books/">:</a></p><pre># library/urls.py<br>from django.urls import path<br>from .views import BookListCreateView<br><br>urlpatterns = [<br>    path(&#39;books/&#39;, BookListCreateView.as_view()),<br>]<br><br># root urls.py, add this<br>path(&#39;library/&#39;, include(&#39;library.urls&#39;)),</pre><p>3. Visit http://localhost:8000/library/books/ in your browser and there it is, a list of our books 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*komUDd8ZPqw9xylb.png" /></figure><p>At the bottom, you can make POST requests either via the form or using a JSON object:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6AZT4eds6DHfVCmZ.png" /></figure><p>Response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ScMnGvxWCgJQLhxb.png" /></figure><h3>DRF Views</h3><p>Now that you’ve seen serializers in action and DRF’s browsable UI, it’s time to move onto the part of the stack that actually <strong>handles HTTP requests</strong> — views.</p><p>In Django, views are the bridge between the request and the response. They define <strong>how data is processed</strong>, <strong>what gets returned</strong>, and <strong>who is allowed to access it</strong>.</p><p>Django REST Framework (DRF) builds on this idea and provides powerful, flexible ways to write views for APIs.</p><p>Let’s walk through the main types of views DRF provides — and when to use each.</p><h3>1. Function-Based Views (FBVs)</h3><p>DRF gives you decorators like @api_view to convert plain Django functions into API views.</p><pre>from rest_framework.decorators import api_view<br>from rest_framework.response import Response<br><br>@api_view([&#39;GET&#39;])<br>def hello_world(request):<br>    return Response({&quot;message&quot;: &quot;Hello, world!&quot;})</pre><p><strong>Try it out:</strong> GET /hello/<br>Response: {&quot;message&quot;: &quot;Hello, world!&quot;}</p><p>This is <strong>great for</strong> simple, one-off endpoints, quick prototypes, or when you’re just starting out.</p><h3>2. Class-Based Views (CBVs)</h3><p>These are based on Django’s own class-based views but add extra methods for handling APIs.</p><h4>a. APIView (The Base Class)</h4><p>Think of APIView as the lowest-level building block for API endpoints. It is great for full control over request handling and custom behavior, especially when you need logic that doesn’t map neatly to CRUD.</p><pre>from rest_framework.views import APIView<br>from rest_framework.response import Response<br>from rest_framework import status<br><br>class HelloWorldView(APIView):<br>    def get(self, request):<br>        return Response({&quot;message&quot;: &quot;Hello, world!&quot;})<br><br>    def post(self, request):<br>        return Response({&quot;you_sent&quot;: request.data}, status=status.HTTP_201_CREATED)</pre><p>b. ViewSet <strong>(base class — no built-in methods)</strong></p><p>This is barebones. You must explicitly define list(), retrieve(), etc. You should this when you want <strong>complete control</strong>.</p><pre>from rest_framework.viewsets import ViewSet<br>from rest_framework.response import Response<br>from .models import Book<br>from .serializers import BookSerializer<br><br>class BookViewSet(ViewSet):<br>    def list(self, request):<br>        books = Book.objects.all()<br>        serializer = BookSerializer(books, many=True)<br>        return Response(serializer.data)<br><br>    def retrieve(self, request, pk=None):<br>        book = Book.objects.get(pk=pk)<br>        serializer = BookSerializer(book)<br>        return Response(serializer.data)</pre><h3>3. Generic Views</h3><p>If you’re working with models and serializers, this is where DRF really shines.</p><p>Generic views abstract away most of the boilerplate, so you don’t need to keep writing .get(), .post(), .put(), etc.</p><p>Here’s a classic example:</p><pre>from rest_framework.generics import ListCreateAPIView<br>from .models import Book<br>from .serializers import BookSerializer<br><br>class BookListCreateView(ListCreateAPIView):<br>    queryset = Book.objects.all()<br>    serializer_class = BookSerializer</pre><p>That’s it — this one class now:</p><ul><li>Lists all books when you GET</li><li>Allows creation of a new book on POST</li></ul><p>You can also do RetrieveAPIView, UpdateAPIView, DestroyAPIView, or combine them like RetrieveUpdateDestroyAPIView.</p><p>Still using our Book model:</p><pre># library/views.py<br>from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView<br>from .models import Book<br>from .serializers import BookSerializer<br><br># GET + POST requests (List + Create)<br>class BookListCreateView(ListCreateAPIView):<br>    queryset = Book.objects.all()<br>    serializer_class = BookSerializer<br><br># PATCH + DELETE <br>class BookDetailView(RetrieveUpdateDestroyAPIView):<br>    queryset = Book.objects.all()<br>    serializer_class = BookSerializer</pre><pre># library/urls.py<br>from django.urls import path<br>from .views import BookListCreateView, BookDetailView<br><br>urlpatterns = [<br>    path(&#39;books/&#39;, BookListCreateView.as_view()),<br>    path(&#39;books/&lt;int:pk&gt;/&#39;, BookDetailView.as_view()),<br>]</pre><p><strong>Try it out:</strong></p><ul><li>GET /books/</li><li>POST /books/ → create a book</li><li>GET /books/1/ → retrieve book with ID 1</li><li>PATCH /books/1/ → partial update</li><li>DELETE /books/1/ → delete (Click on red DELETE button at the top-right corner)</li></ul><p>You can also add <strong>mixins</strong> to your <strong>GenericViewSet</strong>. Use this if you want to <strong>build a custom combination</strong> of CRUD operations.</p><pre>from rest_framework.viewsets import GenericViewSet<br>from rest_framework.mixins import ListModelMixin, RetrieveModelMixin<br>from .models import Book<br>from .serializers import BookSerializer<br><br>class BookViewSet(ListModelMixin, RetrieveModelMixin, GenericViewSet):<br>    queryset = Book.objects.all()<br>    serializer_class = BookSerializer</pre><p>Use this when you only want specific operations (e.g., list + retrieve, but not create/update/delete).</p><h3>4. ViewSets (For Even More Abstraction)</h3><p><strong>ViewSets</strong> are the highest-level abstraction DRF offers. Instead of writing separate views for list, create, update, retrieve, and delete — you define a single class, and DRF wires up the logic automatically.</p><pre># library/views.py<br>from rest_framework import viewsets<br><br>class BookViewSet(viewsets.ModelViewSet):<br>    queryset = Book.objects.all()<br>    serializer_class = BookSerializer</pre><p>By default, ModelViewSet gives you:</p><ul><li>GET /books/ (list)</li><li>GET /books/1/ (retrieve)</li><li>POST /books/ (create)</li><li>PUT /books/1/ (update)</li><li>PATCH /books/1/ (partial update)</li><li>DELETE /books/1/ (delete)</li></ul><p>This is great for fully RESTful resources with minimal boilerplate.</p><p>You then use DRF’s routers to wire it up:</p><pre># urls.py<br>from rest_framework.routers import DefaultRouter<br>from .views import BookViewSet<br><br>router = DefaultRouter()<br>router.register(r&#39;books&#39;, BookViewSet)<br><br>urlpatterns = router.urls</pre><p>When using ViewSets, <strong>you don’t define your own</strong> urlpatterns manually. Instead, DRF provides a router that auto-generates all the routes.</p><h3>When to Use What?</h3><p><strong>Use Case </strong>→ <strong>Recommended View Type</strong></p><ul><li>One-off endpoint simple logic → Function-Based View</li><li>Full control over logic → APIView</li><li>CRUD with models/serializers → Generic Views</li><li>Full REST resource with routing → ViewSets + Routers</li></ul><h3>Custom actions</h3><p>You may also add custom methods with the @action decorator.</p><pre>from rest_framework.decorators import action<br>from rest_framework.response import Response<br><br>class BookViewSet(ModelViewSet):<br>    queryset = Book.objects.all()<br>    serializer_class = BookSerializer<br><br>    @action(detail=True, methods=[&#39;post&#39;])<br>    def publish(self, request, pk=None):<br>        book = self.get_object()<br>        book.published = True<br>        book.save()<br>        return Response({&#39;status&#39;: &#39;book published&#39;})</pre><p>This creates /books/{pk}/publish/ (POST).</p><h3>Permissions</h3><p><strong>Permissions in DRF</strong> control <strong>who</strong> is allowed to perform actions (like GET, POST, PUT, DELETE) on a view or resource. They run <strong>after authentication</strong>, but <strong>before any view logic</strong>.</p><p>You can define permissions:</p><ul><li><strong>Globally</strong> (in settings.py)</li><li><strong>Per View / ViewSet</strong>. This is recommended when you want different rules for different endpoints)</li></ul><p><strong>Global permissions:</strong> In settings.py:</p><pre>REST_FRAMEWORK = {<br>    &#39;DEFAULT_PERMISSION_CLASSES&#39;: [<br>        &#39;rest_framework.permissions.IsAuthenticated&#39;,<br>    ]<br>}</pre><p>Common Built-in Permissions include:</p><p>1. AllowAny: Anyone can access. No authentication needed.</p><pre>from rest_framework.permissions import AllowAny<br><br>class MyView(APIView):<br>    permission_classes = [AllowAny]</pre><p>Useful for public endpoints like signup, homepage, etc.</p><p>2. IsAuthenticated: Only logged-in users are allowed.</p><pre>from rest_framework.permissions import IsAuthenticated<br><br>class MyView(APIView):<br>    permission_classes = [IsAuthenticated]</pre><p>Useful for most protected APIs.</p><p>3. IsAdminUser: Only users with is_staff=True can access.</p><pre>from rest_framework.permissions import IsAdminUser<br><br>class AdminOnlyView(APIView):<br>    permission_classes = [IsAdminUser]</pre><p>4. IsAuthenticatedOrReadOnly</p><ul><li>GET (read-only) allowed for everyone</li><li>POST, PUT, DELETE require login</li></ul><pre>from rest_framework.permissions import IsAuthenticatedOrReadOnly<br><br>class BookViewSet(ModelViewSet):<br>    queryset = Book.objects.all()<br>    serializer_class = BookSerializer<br>    permission_classes = [IsAuthenticatedOrReadOnly]</pre><p>Useful for public blogs or articles where anyone can read, but only logged-in users can write.</p><p>You can create your own permission class, as well (<strong>Custom Permissions</strong>)</p><pre>from rest_framework.permissions import BasePermission<br><br>class IsOwnerOrReadOnly(BasePermission):<br>    def has_object_permission(self, request, view, obj):<br>        # SAFE_METHODS: GET, HEAD, OPTIONS<br>        if request.method in [&#39;GET&#39;, &#39;HEAD&#39;, &#39;OPTIONS&#39;]:<br>            return True<br>        return obj.owner == request.user</pre><p>Use it like this:</p><pre>class BookViewSet(ModelViewSet):<br>    permission_classes = [IsOwnerOrReadOnly]</pre><p>This means:</p><ul><li>Anyone can <strong>read</strong> any book</li><li>But only the <strong>owner</strong> can edit/delete it</li></ul><h3>Filtering</h3><p>Filtering allows clients to narrow down results — for example, get all books by a specific author.</p><p>Here’s how to do basic filtering with filters_backend.</p><p>First, install Django Filter:</p><pre>pip install django-filter</pre><p>Add to your settings.py:</p><pre>INSTALLED_APPS = [<br>    ...,<br>    &#39;django_filters&#39;,<br>]<br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_FILTER_BACKENDS&#39;: [&#39;django_filters.rest_framework.DjangoFilterBackend&#39;]<br>}</pre><p>Let’s try to filter our books by author and published:</p><p>In your views.py:</p><pre>from django_filters.rest_framework import DjangoFilterBackend<br>from .models import Book<br>from .serializers import BookSerializer<br>from rest_framework import viewsets<br><br>class BookListView(viewsets.ModelViewSet):<br>    queryset = Book.objects.all()<br>    serializer_class = BookSerializer<br>    filter_backends = [DjangoFilterBackend]<br>    filterset_fields = [&#39;author&#39;, &#39;published&#39;]</pre><p>Now you can filter like:</p><pre>GET /api/books/?author=George%20Orwell<br>GET /api/books/?published=1945-08-17</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iAMJk06KNBzen1NW.png" /></figure><h3>Pagination</h3><p>Let’s limit how many records are returned in one response. This is helpful in situations where you have thousands of entries. This way your API doesn’t overload clients with 10,000 entries, instead they get the limit you set in groups (pages).</p><p>Enable Pagination in settings.py:</p><pre>REST_FRAMEWORK = {<br>    # ...,<br>    &#39;DEFAULT_PAGINATION_CLASS&#39;: &#39;rest_framework.pagination.PageNumberPagination&#39;,<br>    &#39;PAGE_SIZE&#39;: 3,<br>}</pre><p>Now API responses look like this:</p><pre>{<br>  &quot;count&quot;: 57,<br>  &quot;next&quot;: &quot;http://api.example.org/books/?page=2&quot;,<br>  &quot;previous&quot;: null,<br>  &quot;results&quot;: [<br>    {<br>      &quot;title&quot;: &quot;Book 1&quot;,<br>      &quot;author&quot;: &quot;Author 1&quot;<br>    },<br>    ...<br>  ]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e8DAO6QC3hvioxRP.png" /></figure><p>To get the next page: http://localhost:8000/library/books/?page=2</p><h3>Throttling</h3><p>Throttling protects your API from being overwhelmed by too many requests from the same user or IP.</p><p>In settings.py:</p><pre>REST_FRAMEWORK = {<br>    &#39;DEFAULT_THROTTLE_CLASSES&#39;: [<br>        &#39;rest_framework.throttling.UserRateThrottle&#39;,<br>        &#39;rest_framework.throttling.AnonRateThrottle&#39;,<br>    ],<br>    &#39;DEFAULT_THROTTLE_RATES&#39;: {<br>        &#39;user&#39;: &#39;100/day&#39;,<br>        &#39;anon&#39;: &#39;10/hour&#39;,<br>    }<br>}</pre><p>This means:</p><ul><li><strong>Authenticated users</strong> can make 100 requests per day</li><li><strong>Anonymous users</strong> can make 10 per hour</li></ul><p>If the limit is hit, DRF returns:</p><pre>{<br>  &quot;detail&quot;: &quot;Request was throttled. Expected available in 3600 seconds.&quot;<br>}</pre><h3>Conclusion</h3><p>Over the past four parts of this series, we’ve taken a deep, foundational look at Django and Django REST Framework — from project setup and app structure to models, serializers, views, permissions, and beyond. Instead of rushing to build a project, this series focused on understanding <em>how</em> Django works under the hood, and <em>why</em> it’s designed the way it is.</p><p>You’ve seen:</p><ul><li>How Django gives you a complete toolkit out of the box: routing, templating, ORM, admin, and authentication</li><li>How DRF extends that foundation to build flexible, production-ready APIs</li><li>How to use serializers for validation and transformation</li><li>How to handle views — from function-based to class-based and viewsets</li><li>And how to add powerful features like permissions, authentication, filtering, pagination, and throttling</li></ul><p>If you’ve followed this far, you’re not just “aware” of Django — you now have mental models and working knowledge to build real-world APIs confidently.</p><h3>What’s Next?</h3><p>You may have noticed we didn’t wrap all this up into a complete project — and that’s by design. This series was meant to lay a strong foundation. But in the next article, we’ll build a real API-driven application from scratch using everything we’ve learned here.</p><p>Thanks for sticking with it. This is dense material, but getting comfortable with Django and DRF is a serious level-up for any backend (or fullstack) developer.</p><p>Until the next one<strong>👋</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b28aad6eef53" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>