<?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 Alex Murimi on Medium]]></title>
        <description><![CDATA[Stories by Alex Murimi on Medium]]></description>
        <link>https://medium.com/@Alex_Murimi?source=rss-6ff31833c88e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Alex Murimi on Medium</title>
            <link>https://medium.com/@Alex_Murimi?source=rss-6ff31833c88e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:43:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Alex_Murimi/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[The 12 System Design Principles Every Backend Engineer Should Understand]]></title>
            <link>https://medium.com/@Alex_Murimi/the-12-system-design-principles-every-backend-engineer-should-understand-c29caa608e8d?source=rss-6ff31833c88e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c29caa608e8d</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Alex Murimi]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 19:19:31 GMT</pubDate>
            <atom:updated>2026-06-22T19:19:31.694Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yiymDZM6cIy1sWKmQLpprQ.png" /></figure><p>When I first started learning system design, I thought it was about databases, load balancers, and microservices.</p><p>I spent hours watching videos about distributed systems, drawing architecture diagrams, and memorizing terms like sharding, replication, and event-driven architecture.</p><p>For a while, I believed becoming a better engineer meant learning more technologies.</p><p>Over time, I realized something important.</p><p>The real challenge was never understanding the technologies.</p><p>The real challenge was understanding the forces that shape every system.</p><p>Whether you are building Gmail, Spotify, Stripe, Netflix, or a small internal business application, the same questions keep appearing:</p><ul><li>What happens when a server fails?</li><li>What happens when traffic doubles?</li><li>What happens when a request is retried?</li><li>What happens when a database becomes slow?</li><li>What happens when two systems disagree on data?</li></ul><p>The tools may change.</p><p>The questions do not.</p><p>After spending more time building and maintaining production systems, I realized there are a handful of principles that appear almost everywhere.</p><p>These are the principles I wish I had learned earlier.</p><h3>1. APIs: Every System Is a Conversation</h3><p>Modern software is rarely a single application.</p><p>It is usually a collection of services talking to one another.</p><p>The language they use is the API.</p><p>When your mobile application requests a user’s profile, it doesn’t care whether the backend uses PostgreSQL, Redis, MongoDB, or a stack of spreadsheets hidden in a server room.</p><p>It only cares about the contract.</p><p>That contract defines:</p><ul><li>What can be requested</li><li>What responses look like</li><li>What errors mean</li><li>What behavior clients can rely on</li></ul><p>This is why API design matters so much.</p><p>A poorly designed API creates confusion.</p><p>A well-designed API allows the implementation behind it to evolve while consumers remain unaffected.</p><p>One lesson that every engineer eventually learns:</p><p>Changing code is easy.</p><p>Changing contracts is expensive.</p><h3>2. Statelessness: Assume Servers Will Die</h3><p>One of the biggest mindset shifts in distributed systems is accepting that servers are temporary.</p><p>Machines crash.</p><p>Containers restart.</p><p>Networks fail.</p><p>Cloud providers experience outages.</p><p>The goal is not to prevent failure.</p><p>The goal is to survive it.</p><p>This is where statelessness becomes important.</p><p>A stateless service stores no user-specific information locally.</p><p>Any request can be handled by any server.</p><p>If one server disappears, another immediately takes over.</p><p>A question I now ask whenever reviewing a system is:</p><p>“What happens if I delete this server right now?”</p><p>If the answer is “users lose data,” then the architecture still has work to do.</p><p>Great systems treat servers as replaceable.</p><h3>3. Databases: The Source of Truth</h3><p>Applications come and go.</p><p>Data remains.</p><p>That is why databases are often the most important component in a system.</p><p>A database is more than a storage engine.</p><p>It is the place where business truth lives.</p><blockquote>Customer accounts.</blockquote><blockquote>Payments.</blockquote><blockquote>Orders.</blockquote><blockquote>Invoices.</blockquote><blockquote>Medical records.</blockquote><blockquote>Inventory.</blockquote><p>These are not just rows in a table.</p><p>They are the assets the business depends on.</p><p>One mistake many engineers make is choosing databases based on popularity.</p><p>The better approach is choosing based on requirements.</p><p>Ask yourself:</p><ul><li>How critical is consistency?</li><li>How frequently is data read?</li><li>How frequently is data written?</li><li>What happens if data is lost?</li></ul><p>The database is not just another service.</p><p>It is usually the foundation everything else depends on.</p><h3>4. Indexing: The Most Underrated Scaling Tool</h3><p>Whenever people discuss scalability, they often jump directly to caching, microservices, or distributed databases.</p><p>In reality, many systems become dramatically faster because of a single index.</p><p>Imagine a library with one million books.</p><p>Without organization, finding a book means checking every shelf.</p><p>An index is the librarian that immediately points you to the correct location.</p><p>The same principle applies to databases.</p><p>Before introducing new infrastructure, ask:</p><ul><li>Is the query efficient?</li><li>Is there an index?</li><li>Is the database scanning unnecessary rows?</li></ul><p>Many performance problems are not scaling problems.</p><p>They are search problems.</p><p>I’ve seen situations where a single index reduced query execution time from seconds to milliseconds.</p><p>No new servers.</p><p>No new architecture.</p><p>Just helping the database do less work.</p><h3>5. Caching: Stop Doing Expensive Work Repeatedly</h3><p>Many engineers describe caching as a way to make applications faster.</p><p>I prefer a different definition.</p><p>Caching is a way to avoid repeating expensive work.</p><p>Imagine asking the database the same question one thousand times per second.</p><p>The database can answer.</p><p>But should it?</p><p>A cache allows us to temporarily store answers closer to the application.</p><p>Instead of performing expensive work repeatedly, we reuse previous results.</p><p>The challenge is that caching introduces a tradeoff.</p><p>Speed increases.</p><p>Freshness decreases.</p><p>Every cache eventually becomes stale.</p><p>The engineering challenge is determining how stale is acceptable.</p><p>The best cache strategy is rarely the most complicated.</p><p>It is the simplest one that solves the business problem.</p><h3>6. Message Queues: Breaking Dependency Chains</h3><p>One of the most fragile architectures is a chain of synchronous dependencies.</p><p>Imagine this flow:</p><p>Order Service → Payment Service → Inventory Service → Notification Service</p><p>If one service becomes unavailable, the entire workflow may fail.</p><p>Message queues solve this problem by introducing separation.</p><p>Instead of demanding immediate responses, systems communicate through events.</p><p>An order is created.</p><p>An event is published.</p><p>Interested services react independently.</p><p>Inventory updates.</p><p>Emails are sent.</p><p>Analytics are updated.</p><p>The services no longer depend on each other’s availability.</p><p>This shift from direct communication to event-driven communication is one of the most powerful techniques in modern architecture.</p><h3>7. Consistency Models: How Correct Must Data Be?</h3><p>Not all data has the same requirements.</p><p>A banking transaction requires precision.</p><p>A social media like count does not.</p><p>This is where consistency models become important.</p><p>Strong consistency ensures everyone sees the latest data immediately.</p><p>Eventual consistency allows temporary differences while replicas synchronize.</p><p>The question is not:</p><p>“Which model is better?”</p><p>The question is:</p><p>“What level of correctness does the business require?”</p><p>The most effective systems apply strict consistency where mistakes are costly and relaxed consistency where scalability matters more.</p><p>Engineering is often about choosing the right tradeoff.</p><p>Consistency is one of the clearest examples.</p><h3>8. Idempotency: The Art of Safe Retries</h3><p>Distributed systems retry.</p><p>Requests timeout.</p><p>Networks drop packets.</p><p>Consumers process duplicate messages.</p><p>The same operation may arrive more than once.</p><p>This raises a dangerous question:</p><p>“What happens if this executes twice?”</p><p>Imagine charging a customer twice because a network timeout triggered a retry.</p><p>Or sending the same email three times.</p><p>Or creating duplicate invoices.</p><p>Idempotency solves this problem.</p><p>An idempotent operation can be executed multiple times while producing the same final outcome.</p><p>The more systems I work on, the more I realize reliability often depends less on preventing duplication and more on handling duplication safely.</p><h3>9. Data Ownership: Clear Boundaries Create Healthy Systems</h3><p>As systems grow, complexity often appears at service boundaries.</p><p>One common mistake is allowing multiple services to directly modify the same data.</p><p>Ownership becomes unclear.</p><p>Responsibilities overlap.</p><p>Debugging becomes difficult.</p><p>A healthier model is simple:</p><p>Each service owns its own data.</p><p>Order data belongs to the Order Service.</p><p>Payment data belongs to the Payment Service.</p><p>Inventory data belongs to the Inventory Service.</p><p>Communication happens through APIs and events.</p><p>Ownership creates boundaries.</p><p>Boundaries reduce chaos.</p><p>Without ownership, microservices often become a distributed monolith.</p><h3>10. Observability: If You Cannot See It, You Cannot Operate It</h3><p>Every production system eventually fails.</p><p>When that happens, engineers need answers.</p><p>What happened?</p><p>Why did it happen?</p><p>Where did it happen?</p><p>When did it happen?</p><p>Observability provides those answers.</p><p>Logs tell the story.</p><p>Metrics measure behavior.</p><p>Traces reveal request journeys.</p><p>Without observability, troubleshooting becomes guesswork.</p><p>With observability, failures become understandable.</p><p>One lesson I learned the hard way:</p><blockquote><strong>A feature is not finished when it works.</strong></blockquote><p>A feature is finished when it can be monitored.</p><h3>11. Backpressure: Protecting Systems from Success</h3><p>Engineers often design systems for normal traffic.</p><p>Real systems must survive abnormal traffic.</p><p>What happens when demand suddenly becomes ten times larger?</p><p>Can the queue absorb it?</p><p>Can workers keep up?</p><p>Can the database handle it?</p><p>Can external providers keep responding?</p><p>Backpressure is the collection of mechanisms that protect systems under stress.</p><p>Rate limiting.</p><p>Request throttling.</p><p>Queue limits.</p><p>Circuit breakers.</p><p>Load shedding.</p><p>Healthy systems understand their limits.</p><p>The goal is not to process infinite work.</p><p>The goal is to remain operational during overload.</p><h3>12. Failure Recovery: Reliability Is Recovery</h3><p>One of the biggest misconceptions in software engineering is believing reliability means avoiding failure.</p><p>No system avoids failure forever.</p><p>Reliable systems recover quickly.</p><p>Backups exist because databases fail.</p><p>Dead-letter queues exist because messages fail.</p><p>Multi-region deployments exist because regions fail.</p><p>Disaster recovery plans exist because disasters happen.</p><p>The question is never:</p><p>“Will this fail?”</p><p>The question is:</p><p>“How quickly can we recover?”</p><p>Mature engineering teams spend as much time planning recovery as they spend building features.</p><h3>Final Thoughts</h3><p>When I first started learning system design, I thought architecture was about technologies.</p><p>Today, I see it differently.</p><p>System design is really the study of tradeoffs.</p><p>Every architecture decision is an answer to a question:</p><ul><li>Consistency or availability?</li><li>Simplicity or flexibility?</li><li>Speed or freshness?</li><li>Cost or resilience?</li></ul><p>The technologies will continue changing.</p><p>The principles will remain.</p><p>If you can understand APIs, statelessness, databases, indexing, caching, queues, consistency, idempotency, data ownership, observability, backpressure, and failure recovery, you will have a framework for reasoning about almost every system you encounter.</p><p>And in my experience, that framework is far more valuable than memorizing any particular technology stack.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c29caa608e8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Instagram Does Not Care About Billions of Rows]]></title>
            <link>https://medium.com/@Alex_Murimi/why-instagram-does-not-care-about-billions-of-rows-0e1ad92e6164?source=rss-6ff31833c88e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e1ad92e6164</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Alex Murimi]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 20:35:29 GMT</pubDate>
            <atom:updated>2026-06-15T20:35:29.831Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDHUQgi4vs2B8VuC3f0XGA.png" /></figure><p>Instagram has billions of photos.</p><p>YouTube has billions of videos.</p><p>Amazon has millions of products.</p><p>Banks store years of transactions.</p><p>Yet when you open an app, you still expect the result to appear almost immediately.</p><p>That expectation hides one of the most important lessons in backend engineering:</p><p>Big systems are not fast because they have less data.</p><p>They are fast because they avoid looking at most of it.</p><p>A database does not become slow simply because it stores billions of rows.</p><p>It becomes slow when every request is forced to think about too many rows.</p><p>That is the difference between a system that merely works and a system that scales.</p><h3>Performance Is Not Scalability</h3><p>Most developers measure performance like this:</p><p>This query takes 40 milliseconds.</p><p>That sounds useful.</p><p>But it is only one data point.</p><p>A better question is:</p><pre>What happens when the data grows 10x?<br>What happens when 1,000 users run it at the same time?<br>What happens when production has network latency, firewalls, background jobs, and real traffic?</pre><p>Performance tells you how fast something is today.</p><p>Scalability tells you whether it will still be fast tomorrow.</p><p>A query that takes 40 milliseconds on 10,000 rows may take 4 seconds on 10 million rows.</p><p>The SQL did not change.</p><p>The code did not change.</p><p>The table simply grew.</p><p>That is where weak database design gets exposed.</p><h3>A Simple Instagram Example</h3><p>Imagine Instagram has a table like this:</p><pre>CREATE TABLE photos (<br>    id BIGINT PRIMARY KEY,<br>    user_id BIGINT,<br>    created_at TIMESTAMP,<br>    caption TEXT,<br>    image_url TEXT<br>);</pre><p>When you open a profile, Instagram might need to show the latest photos for one user:</p><pre>SELECT *<br>FROM photos<br>WHERE user_id = 123<br>ORDER BY created_at DESC<br>LIMIT 20;</pre><p>This query should not care whether Instagram has:</p><pre>10,000 photos<br>10 million photos<br>10 billion photos</pre><p>Why?</p><p>Because the query only needs photos for one user.</p><p>The database should not search the entire photos table.</p><p>It should jump directly to the rows for:</p><pre>user_id = 123</pre><p>Then return the newest 20.</p><p>That is what a good index allows.</p><pre>CREATE INDEX idx_photos_user_created<br>ON photos (user_id, created_at DESC);</pre><p>Now the database can think like this:</p><pre>Go to this user&#39;s photos.<br>Start from the newest.<br>Return 20 rows.<br>Stop.</pre><p>That last word matters:</p><pre>Stop.</pre><p>Fast systems are good at stopping early.</p><p>Slow systems keep scanning.</p><h3>What a Good Index Allows</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDHUQgi4vs2B8VuC3f0XGA.png" /></figure><h3>The Dangerous Version</h3><p>Now imagine the database has no useful index.</p><p>The query is still the same:</p><pre>SELECT *<br>FROM photos<br>WHERE user_id = 123<br>ORDER BY created_at DESC<br>LIMIT 20;</pre><p>But without the right index, the database may have to scan a huge number of rows.</p><p>Conceptually, it becomes:</p><pre>Look at photo 1.<br>Is it user 123?</pre><pre>Look at photo 2.<br>Is it user 123?</pre><pre>Look at photo 3.<br>Is it user 123?</pre><pre>Keep going...</pre><p>That is not search.</p><p>That is punishment.</p><p>At small scale, you may not notice.</p><p>At large scale, it becomes a production incident.</p><h3>The Real Problem Is Not Big Data</h3><p>A common mistake is to say:</p><blockquote>The database is slow because the table is large.</blockquote><p>That is not always true.</p><p>Large tables can be fast.</p><p>Small tables can be slow.</p><p>The real question is:</p><blockquote>How much data does the database need to read to answer the question?</blockquote><p>Instagram does not ask:</p><blockquote>Find photos from billions of rows.</blockquote><p>It asks:</p><blockquote>Find the latest 20 photos for this one user.</blockquote><p>That is a much smaller problem.</p><p>The job of indexes is to turn big problems into small problems.</p><h3>The Index That Looks Right But Is Wrong</h3><p>This is where many developers get trapped.</p><p>They create an index.</p><p>The database uses the index.</p><p>The query becomes faster.</p><p>So they think the problem is solved.</p><p>But not every index is equally useful.</p><p>Consider this query:</p><pre>SELECT count(*)<br>FROM scale_data<br>WHERE section = ?<br>AND id2 = ?;</pre><p>Now compare these two indexes:</p><pre>CREATE INDEX scale_slow<br>ON scale_data (section, id1, id2);</pre><pre>CREATE INDEX scale_fast<br>ON scale_data (section, id2, id1);</pre><p>Both indexes contain the same columns.</p><p>But they do not behave the same.</p><p>The first one is weaker for this query.</p><p>The second one is better.</p><p>Why?</p><p>Column order.</p><h3>Composite Indexes Are Ordered</h3><p>A composite index is not just a bag of columns.</p><p>This index:</p><pre>(section, id1, id2)</pre><p>is not the same as:</p><pre>(section, id2, id1)</pre><p>The order matters.</p><p>Think of a phone book sorted like this:</p><pre>Last Name<br>First Name<br>City</pre><p>If you search by:</p><pre>Last Name = Kariuki<br>First Name = Alem</pre><p>that is efficient.</p><p>But if you search by:</p><pre>Last Name = Kariuki<br>City = Nairobi</pre><p>the phone book helps you find all people named Kariuki.</p><p>But inside that group, the book is sorted by first name, not city.</p><p>So you still have to scan through many Kariukis to find those in Nairobi.</p><p>That is exactly what happens with a badly ordered composite index.</p><h3>Access Predicate vs Filter Predicate</h3><p>This is one of the most important ideas in query tuning.</p><p>An access predicate helps the database find the rows directly.</p><p>A filter predicate is checked after the database has already read extra rows.</p><p>That difference is massive.</p><p>For the slow index:</p><pre>(section, id1, id2)</pre><p>and the query:</p><pre>WHERE section = ?<br>AND id2 = ?</pre><p>the database can use:</p><pre>section = ?</pre><p>to access the index.</p><p>But id2 is not next in the index.</p><p>id1 is in the middle.</p><p>So the database may do this:</p><pre>Access: section = ?<br>Filter: id2 = ?</pre><p>That means:</p><pre>Find the section.<br>Read many rows in that section.<br>Throw away rows where id2 does not match.</pre><p>The index is being used.</p><p>But not well enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GQCl38EBdF5cYVhKD1lzEQ.png" /></figure><h3>The Better Index</h3><p>The better index is:</p><pre>CREATE INDEX scale_fast<br>ON scale_data (section, id2, id1);</pre><p>Now the query matches the beginning of the index:</p><pre>WHERE section = ?<br>AND id2 = ?</pre><p>The database can use both conditions to narrow the search.</p><p>Conceptually:</p><pre>Access: section = ? AND id2 = ?</pre><p>This is much better.</p><p>The database jumps closer to exactly what it needs.</p><p>It reads less.</p><p>It filters less.</p><p>It wastes less.</p><p>And because it wastes less work, it scales better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rGy_jvYuz7gtNcJWHI-Mtw.png" /></figure><h3>“It Uses an Index” Is Not Enough</h3><p>This is the mistake that separates junior debugging from senior debugging.</p><p>A junior engineer asks:</p><blockquote>Is the query using an index?</blockquote><p>A senior engineer asks:</p><blockquote>Is the query using the right index in the right way?</blockquote><p>Those are very different questions.</p><p>An execution plan may say:</p><pre>INDEX RANGE SCAN</pre><p>That sounds good.</p><p>But if the important condition is only applied as a filter, the query may still scan too much data.</p><p>That is how you get the painful situation:</p><blockquote>The query uses an index but is still slow.</blockquote><p>The index is not broken.</p><p>The access pattern is wrong.</p><h3>Why This Looks Fine in Development</h3><p>In development, your table may have:</p><pre>10,000 rows</pre><p>In production, it may have:</p><pre>100 million rows</pre><p>A bad query can hide in development because there is not enough data to expose it.</p><p>Scanning 500 extra rows is harmless.</p><p>Scanning 5 million extra rows is not.</p><p>This is why production often reveals problems that staging missed.</p><p>Staging tests correctness.</p><p>Production tests scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ReW-4LoGVXTwZqdW8c99w.png" /></figure><h3>The YouTube Version</h3><p>Imagine YouTube wants to fetch a video by creator and video ID:</p><pre>SELECT *<br>FROM videos<br>WHERE creator_id = 900<br>AND video_id = 777;</pre><p>A good index may look like:</p><pre>CREATE INDEX idx_videos_creator_video<br>ON videos (creator_id, video_id);</pre><p>This allows the database to go directly to:</p><pre>creator_id = 900<br>video_id = 777</pre><p>But a weaker index might be:</p><pre>CREATE INDEX idx_videos_creator_category_video<br>ON videos (creator_id, category_id, video_id);</pre><p>Now the database can find the creator.</p><p>But because category_id sits between creator_id and video_id, the database cannot use video_id as efficiently unless the query also filters by category_id.</p><p>The database may need to scan many videos from that creator and then check the video ID.</p><p>Again:</p><pre>The index exists.<br>The query uses it.<br>The design is still not ideal.</pre><h3>System Load Makes Waste Expensive</h3><p>Data volume is one dimension of scalability.</p><p>System load is another.</p><p>A query that wastes a little work may be acceptable when one person runs it.</p><p>But what happens when 1,000 people run it at once?</p><p>Suppose one query scans:</p><p>10,000 unnecessary rows</p><p>That may not destroy the system.</p><p>But if 1,000 users trigger that query at the same time:</p><p>10,000 × 1,000 = 10,000,000 unnecessary row checks</p><p>The waste multiplies.</p><p>That is why production systems fail under load.</p><p>The bad query did not suddenly become bad.</p><p>The traffic revealed the truth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MNPu4jBI1IV2pdp6wC6K_g.png" /></figure><h3>This Is Why Fast Is Not the Same as Efficient</h3><p>A query can be fast and still be dangerous.</p><p>That sounds strange, but it is true.</p><p>Fast means:</p><blockquote>It returned quickly in this test.</blockquote><p>Efficient means:</p><blockquote>It did the minimum reasonable work.</blockquote><p>You want efficient queries.</p><p>Because efficient queries survive growth.</p><p>A query that takes 30ms while scanning unnecessary rows is not a victory.</p><p>It is a warning.</p><p>Today the waste is small.</p><p>Tomorrow it may be huge.</p><h3>Why Bigger Hardware Does Not Fix Everything</h3><p>When queries become slow, teams often say:</p><pre>Let us upgrade the server.</pre><p>Sometimes that helps.</p><p>But it does not fix the root problem.</p><p>Bigger hardware usually improves throughput.</p><p>It does not always improve response time.</p><p>A wider highway allows more cars to travel at the same time.</p><p>It does not make one car move faster.</p><p>The same applies to databases.</p><p>More CPU cores can help run more work concurrently.</p><p>But if one query reads far too much data, it is still doing too much work.</p><p>The better fix is usually:</p><pre>Read fewer rows.<br>Use better indexes.<br>Improve the query shape.<br>Reduce unnecessary scans.</pre><p>Hardware can hide inefficiency for a while.</p><p>It rarely removes it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yj18Rpp3ze6X7L0f_nmXnA.png" /></figure><h3>Caching Helps, But It Is Not Magic</h3><p>Modern databases cache frequently accessed data in memory.</p><p>That helps a lot.</p><p>If an index page is already in memory, the database does not need to read it from disk.</p><p>SSDs also reduce disk seek time compared to traditional hard drives.</p><p>But neither caching nor SSDs changes the fundamental rule:</p><blockquote>Reading less data is better than reading more data quickly.</blockquote><p>A bad query can still hurt a system even when the database has good caching.</p><p>Why?</p><p>Because wasteful queries compete for shared resources:</p><blockquote>CPU<br>memory<br>buffer cache<br>disk I/O<br>connections<br>locks</blockquote><p>Caching makes good access patterns faster.</p><p>It does not make bad access patterns good.</p><h3>The Backend Engineer’s Mental Model</h3><p>When you design or review a query, think like this:</p><blockquote>What exact question is the application asking?</blockquote><p>Not:</p><blockquote>What columns exist?</blockquote><p>Not:</p><blockquote>What index can I randomly add?</blockquote><p>Start from the access pattern.</p><p>For Instagram:</p><blockquote>Give me the latest photos for this user.</blockquote><p>For YouTube:</p><blockquote>Give me this video for this creator.</blockquote><p>For an e-commerce app:</p><blockquote>Give me available products in this category ordered by popularity.</blockquote><p>For a banking app:</p><blockquote>Give me the latest transactions for this account.</blockquote><p>Then design the index around that question.</p><h3>Practical Examples</h3><h3>Instagram Profile Feed</h3><p>Query:</p><pre>SELECT *<br>FROM photos<br>WHERE user_id = 123<br>ORDER BY created_at DESC<br>LIMIT 20;</pre><p>Good index:</p><pre>CREATE INDEX idx_photos_user_created<br>ON photos (user_id, created_at DESC);</pre><p>Why it works:</p><pre>Find one user&#39;s photos.<br>Read newest first.<br>Stop after 20.</pre><h3>YouTube Creator Video Lookup</h3><p>Query:</p><pre>SELECT *<br>FROM videos<br>WHERE creator_id = 900<br>AND video_id = 777;</pre><p>Good index:</p><pre>CREATE INDEX idx_videos_creator_video<br>ON videos (creator_id, video_id);</pre><p>Why it works:</p><blockquote>Use creator_id and video_id together to narrow the search.</blockquote><h3>Banking Transaction History</h3><p>Query:</p><pre>SELECT *<br>FROM transactions<br>WHERE account_id = 555<br>ORDER BY created_at DESC<br>LIMIT 50;</pre><p>Good index:</p><pre>CREATE INDEX idx_transactions_account_created<br>ON transactions (account_id, created_at DESC);</pre><p>Why it works:</p><pre>Find one account.<br>Read latest transactions first.<br>Stop after 50.</pre><h3>E-commerce Category Search</h3><p>Query:</p><pre>SELECT *<br>FROM products<br>WHERE category_id = 10<br>AND status = &#39;ACTIVE&#39;<br>ORDER BY popularity_score DESC<br>LIMIT 30;</pre><p>Possible index:</p><pre>CREATE INDEX idx_products_category_status_popularity<br>ON products (category_id, status, popularity_score DESC);</pre><p>Why it works:</p><pre>Find active products in one category.<br>Read most popular first.<br>Stop after 30.</pre><h3>The Senior Engineer Checklist</h3><p>Before shipping a query on an important endpoint, ask:</p><pre>1. What is the access pattern?<br>2. Does the index match the WHERE clause?<br>3. Does the index support the ORDER BY?<br>4. Can the database stop early because of LIMIT?<br>5. Are important predicates used to access rows or only filter them?<br>6. How many rows does the database read before returning the result?<br>7. What happens when the table grows 10x?<br>8. What happens when 1,000 users run this at once?<br>9. Am I solving the real problem or just adding hardware?<br>10. Would this still be acceptable with production-size data?</pre><p>This is how senior engineers think.</p><p>They do not only ask whether the query works.</p><p>They ask whether the query survives growth.</p><h3>Final Thought</h3><p>Instagram does not care about billions of rows because one request should not search billions of rows.</p><p>YouTube does not scan every video when you open one video.</p><p>A bank does not scan every transaction when you open one account.</p><p>Large systems stay fast because they turn huge datasets into tiny, targeted lookups.</p><p>That is the real job of indexing.</p><p>Not to make databases magically fast.</p><p>But to help the database avoid unnecessary work.</p><p>Because at scale, the best query is not the one that runs fast today.</p><p>It is the one that still runs fast when the system grows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e1ad92e6164" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why a Single WHERE Clause Can Make a Query 1000x Slower]]></title>
            <link>https://medium.com/@Alex_Murimi/why-a-single-where-clause-can-make-a-query-1000x-slower-f4b1eaf22bcf?source=rss-6ff31833c88e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4b1eaf22bcf</guid>
            <category><![CDATA[perfomance]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Alex Murimi]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 20:41:34 GMT</pubDate>
            <atom:updated>2026-06-09T20:41:34.456Z</atom:updated>
            <content:encoded><![CDATA[<p>Everything in this article was tested on PostgreSQL using a table containing one million employee records.</p><p>Rather than relying on theory, we’ll observe the query optimizer ourselves and see exactly why some queries run in milliseconds while others take seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sXnHLqj5DWmHY_dVkliq8w.png" /></figure><h3>Where Database Performance Is Won or Lost</h3><p>Imagine a feature works perfectly in development.</p><p>The API responds instantly.</p><p>Users are happy.</p><p>Then the application goes live.</p><p>A few months later, the table grows to millions of rows and the same endpoint suddenly takes 12 seconds.</p><p>What changed?</p><p>Most of the time, the answer can be traced back to a single place:</p><h4>The WHERE clause.</h4><p>We learn SQL by writing queries like this:</p><pre>SELECT first_name, last_name<br>FROM employees<br>WHERE employee_id = 123;</pre><p>The query looks simple.</p><p>In fact, SQL was designed to be simple. You describe <em>what</em> data you want, and the database figures out <em>how</em> to retrieve it.</p><p>The problem is that while SQL hides the implementation details, it doesn’t eliminate them.</p><p>Many performance issues originate from a single place:</p><h4>The WHERE clause.</h4><p>A poorly written WHERE clause can turn a millisecond query into a multi-second database scan, even when indexes exist.</p><p>Understanding how databases use indexes inside the WHERE clause is one of the highest-leverage skills a software engineer can learn.</p><h3>The Real Purpose of an Index</h3><p>Think of a database table as a library containing millions of books.</p><p>Without an index, finding a single book requires checking every shelf until you find the correct one.</p><p>This is known as a <strong>Full Table Scan</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QpVfCZ1E_pWC1bRhcey5g.png" /></figure><p>As the table grows, the search time grows proportionally.</p><p>Indexes solve this problem.</p><p>Instead of scanning everything, the database uses a structure similar to a book’s table of contents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cc8DYZpKKEZnbKXVYas7Xw.png" /></figure><p>Instead of asking “Does this row match?” a million times, the database can jump almost directly to the answer.</p><p>This is why indexed lookups often remain fast even when a table grows from thousands to millions of rows.</p><h3>The Fastest Query: Primary Key Lookups</h3><p>Let’s start with the query every database is optimized for.</p><p>Consider the following table:</p><pre>CREATE TABLE employees (<br>    employee_id BIGINT PRIMARY KEY,<br>    first_name VARCHAR(100),<br>    last_name VARCHAR(100)<br>);</pre><p>Now suppose we need information about a single employee:</p><pre>SELECT first_name, last_name<br>FROM employees<br>WHERE employee_id = 123;</pre><p>At first glance, this query doesn’t seem special.</p><p>However, it is one of the fastest queries a relational database can execute.</p><p>The reason is simple.</p><p>The database knows that employee_id is a primary key.</p><p><em>A primary key guarantees uniqueness.</em></p><p>That means there can never be more than one employee with an ID of 123.</p><p>As a result, PostgreSQL doesn’t need to scan thousands or millions of rows.</p><p>Instead, it follows the primary key index directly to the correct location.</p><p>Once the row is found, the search immediately stops.</p><p>The database doesn’t need to keep looking because it already knows there cannot be another match.</p><p>This is one of the reasons primary key lookups remain extremely fast even when a table grows from a few hundred rows to several million rows.</p><p>To verify this, I ran the query against a table containing one million employee records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*egKa4Mh1GzsMraDGGqFfag.png" /></figure><pre>EXPLAIN ANALYZE<br>SELECT *<br>FROM employees<br>WHERE employee_id = 500000;</pre><p>The execution plan shows:</p><pre>Index Scan using employees_pkey on employees</pre><p>This tells us PostgreSQL used the primary key index instead of scanning the table.</p><p>The query completed in a fraction of a millisecond.</p><p>This is the ideal scenario for an index:</p><ul><li>One unique value</li><li>One matching row</li><li>One direct lookup</li></ul><p>In database terms, this is as close to a perfect search as you can get.</p><h3>The Hidden Trap of Composite Indexes</h3><p>As applications grow, a single-column index is often not enough.</p><p>Imagine an employee table belonging to a company with many subsidiaries.</p><p>A developer notices that many queries filter using both employee_id and subsidiary_id, so they create the following index:</p><pre>CREATE INDEX employee_pk<br>ON employees(employee_id, subsidiary_id);</pre><p>This is known as a <strong>composite index</strong> (sometimes called a multi-column index).</p><p>At first glance, it seems obvious what this index does.</p><p>It contains both columns.</p><p>So surely PostgreSQL can search either column efficiently.</p><p>Right?</p><p>Unfortunately, this is one of the most common misconceptions in database design.</p><p>Many developers assume:</p><blockquote><em>If an index contains multiple columns, all of those columns are equally searchable.</em></blockquote><p>The database disagrees.</p><p>To understand why, we need to understand how the index is actually organized.</p><p>Consider this index:</p><pre>(employee_id, subsidiary_id)</pre><p>The order is not decorative.</p><p>It is not a suggestion.</p><p>It is the actual sorting order used inside the index.</p><p>PostgreSQL first sorts entries by employee_id.</p><p>Only when two rows have the same employee_id does it look at subsidiary_id.</p><p>Think of a telephone directory.</p><pre>Murimi, Alex<br>Murimi, Brian<br>Murimi, Carol</pre><pre>Otieno, John<br>Otieno, Peter</pre><pre>Wanjiku, Alice<br>Wanjiku, David</pre><p>The directory is sorted by surname first.</p><p>The first name is only used when multiple people share the same surname.</p><p>Finding everyone named “Murimi” is easy.</p><p>Finding “Alex” without knowing the surname is much harder.</p><p>You would have to scan page after page looking for every occurrence.</p><p>A composite index works exactly the same way.</p><p>Because the index is sorted by employee_id first, PostgreSQL can efficiently search:</p><pre>WHERE employee_id = 123</pre><p>and</p><pre>WHERE employee_id = 123<br>AND subsidiary_id = 10</pre><p>However, searching only by:</p><pre>WHERE subsidiary_id = 10</pre><p>is a completely different story.</p><p>The database cannot jump directly to all rows belonging to subsidiary 10 because the index is not organized around that column.</p><p>Instead, subsidiary IDs are scattered throughout the index, mixed among different employee IDs.</p><p>The result is often far more work than developers expect.</p><p>This seemingly small detail leads to one of the most important indexing rules in database design:</p><p>The order of columns in a composite index matters.</p><blockquote><em>“If column order matters so much, how do we decide which column goes first</em>?<em>”</em></blockquote><h3>The Leftmost Prefix Rule</h3><p>Now that we understand that the order of columns in a composite index matters, we can introduce one of the most important concepts in database performance:</p><blockquote><em>The Leftmost Prefix Rule.</em></blockquote><p>Consider the following index:</p><pre>CREATE INDEX idx_employee<br>ON employees(subsidiary_id, employee_id);</pre><p>Remember that PostgreSQL stores this index in sorted order.</p><p>Conceptually, the index looks something like this:</p><pre>subsidiary_id | employee_id</pre><pre>1             | 101<br>1             | 145<br>1             | 201<br>2             | 102<br>2             | 189<br>2             | 250<br>3             | 103<br>3             | 178</pre><p>Notice how all rows belonging to the same subsidiary are grouped together.</p><p>This organization allows PostgreSQL to quickly find records when the query starts with the first column of the index.</p><p>For example:</p><pre>WHERE subsidiary_id = 2</pre><p>PostgreSQL can immediately jump to the section of the index containing subsidiary 2 and ignore everything else.</p><p>Likewise, this query is also efficient:</p><pre>WHERE subsidiary_id = 2<br>AND employee_id = 189</pre><p>The database first finds subsidiary 2 and then searches for employee 189 within that smaller section.</p><p>However, consider this query:</p><pre>WHERE employee_id = 189</pre><p>At first glance, it looks like the index should still help because employee_id exists in the index.</p><p>Unfortunately, that’s not how the index is organized.</p><p>The index is sorted by subsidiary_id first, not by employee_id.</p><p>If PostgreSQL wants to find employee 189, it has no direct way to jump to the correct location.</p><p>That employee could be under subsidiary 1, subsidiary 2, subsidiary 3, or any other subsidiary.</p><p>The database would have to search through many sections of the index to find the answer.</p><p>This is why the index cannot be fully utilized.</p><p>The first column acts like the front door to the index.</p><p>If your query doesn’t use that column, PostgreSQL loses its shortcut.</p><p>This leads us to the Leftmost Prefix Rule:</p><blockquote><em>A composite index is only guaranteed to be efficient when queries use the leftmost column or columns of the index.</em></blockquote><p>For an index defined as:</p><pre>(subsidiary_id, employee_id)</pre><p>these searches work well:</p><pre>WHERE subsidiary_id = 2</pre><pre>WHERE subsidiary_id = 2<br>AND employee_id = 189</pre><p>But this search cannot fully benefit from the index:</p><pre>WHERE employee_id = 189</pre><p>because the leftmost column is missing.</p><p>Understanding this rule is critical because many slow queries are caused by an index that exists but is organized in the wrong order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGc_xZg7_j8afnAJwM6sEA.png" /></figure><h3>Why Column Order Matters</h3><p>Now we arrive at one of the most important questions in database indexing:</p><blockquote><em>If a query uses multiple columns, how do we decide which column should come first in the index?</em></blockquote><p>Consider the following query:</p><pre>SELECT *<br>FROM employees<br>WHERE subsidiary_id = 27<br>AND date_of_birth BETWEEN<br>      &#39;1971-01-01&#39;<br>  AND &#39;1971-01-09&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Azm7f5ZBXm8DI98cM22IJA.png" /></figure><p>At first glance, both columns seem equally important.</p><p>The query filters by:</p><ul><li>subsidiary_id</li><li>date_of_birth</li></ul><p>A developer might create either of these indexes:</p><p><strong>Option A</strong></p><pre>(subsidiary_id, date_of_birth)</pre><p><strong>Option B</strong></p><pre>(date_of_birth, subsidiary_id)</pre><p>Both indexes contain the same columns.</p><p>So does the order really matter?</p><p>Absolutely.</p><p>The difference can be the difference between scanning a few rows and scanning thousands.</p><p>To understand why, we need to think about how PostgreSQL navigates an index.</p><p>Imagine our company has 50 subsidiaries and one million employees.</p><p>Suppose subsidiary 27 contains 20,000 employees.</p><p>Now let’s look at Option A:</p><pre>(subsidiary_id, date_of_birth)</pre><p>The index is organized primarily by subsidiary.</p><p>Conceptually, it looks something like this:</p><pre>Subsidiary 1<br>  ├─ dates...<br>  ├─ dates...<br>  └─ dates...</pre><pre>Subsidiary 2<br>  ├─ dates...<br>  ├─ dates...<br>  └─ dates...</pre><pre>...</pre><pre>Subsidiary 27<br>  ├─ 1970-12-31<br>  ├─ 1971-01-01<br>  ├─ 1971-01-02<br>  ├─ 1971-01-03<br>  └─ ...</pre><p>When PostgreSQL executes the query, it can immediately jump to the section containing subsidiary 27.</p><p>Once it is inside that section, the rows are already sorted by date of birth.</p><p>Finding employees born between January 1st and January 9th becomes a very small scan.</p><p>The database ignores almost the entire index.</p><p>Now let’s reverse the index:</p><pre>(date_of_birth, subsidiary_id)</pre><p>The index now looks more like this:</p><pre>1971-01-01<br>  ├─ Subsidiary 1<br>  ├─ Subsidiary 5<br>  ├─ Subsidiary 12<br>  ├─ Subsidiary 27<br>  └─ Subsidiary 40</pre><pre>1971-01-02<br>  ├─ Subsidiary 2<br>  ├─ Subsidiary 7<br>  ├─ Subsidiary 27<br>  └─ Subsidiary 45</pre><pre>...</pre><p>PostgreSQL can use the date range efficiently.</p><p>However, it cannot immediately isolate subsidiary 27.</p><p>Instead, it must examine every matching date and then filter out employees belonging to other subsidiaries.</p><p>This requires significantly more work.</p><p>The key insight is that not all conditions are equally useful when navigating an index.</p><p>Look closely at the query:</p><pre>WHERE subsidiary_id = 27<br>AND date_of_birth BETWEEN<br>      &#39;1971-01-01&#39;<br>  AND &#39;1971-01-09&#39;</pre><p>The first condition:</p><pre>subsidiary_id = 27</pre><p>identifies a single value.</p><p>The second condition:</p><pre>date_of_birth BETWEEN ...</pre><p>identifies a range of values.</p><p>Equality conditions are powerful because they allow PostgreSQL to jump directly to a very specific location in the index.</p><p>Range conditions are different.</p><p>Once PostgreSQL starts scanning a range, it must walk through the matching entries one by one.</p><p>This leads to one of the most useful indexing rules you will ever learn:</p><blockquote><em>Equality columns first. Range columns last.</em></blockquote><p>For our query:</p><pre>(subsidiary_id, date_of_birth)</pre><p>is usually the better index because PostgreSQL can first narrow the search to a single subsidiary and only then scan the relevant date range.</p><p>The amount of data that must be examined becomes dramatically smaller.</p><p>And in databases, less work almost always means better performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hG6giuv-9hW567zFlpgWhg.png" /></figure><h3>Equality Before Range</h3><p>If you remember only one indexing rule from this article, remember this one:</p><blockquote><em>Equality columns first. Range columns second.</em></blockquote><p>This simple guideline will help you design effective indexes far more often than memorizing optimizer internals or database-specific tricks.</p><p>Let’s look at an example:</p><pre>WHERE country = &#39;KE&#39;<br>AND created_at BETWEEN<br>    &#39;2025-01-01&#39;<br>AND &#39;2025-12-31&#39;</pre><p>At first glance, both columns appear equally important.</p><p>The query filters by country and by date.</p><p>However, PostgreSQL sees these conditions very differently.</p><p>The first condition:</p><pre>country = &#39;KE&#39;</pre><p>is an <strong>equality condition</strong>.</p><p>It points to a single value.</p><p>The second condition:</p><pre>created_at BETWEEN ...</pre><p>is a <strong>range condition</strong>.</p><p>It points to many possible values.</p><p>This distinction is extremely important.</p><p>An equality condition allows PostgreSQL to jump directly to a precise location in the index.</p><p>A range condition is different.</p><p>Once PostgreSQL reaches the start of the range, it must scan through matching entries until it reaches the end.</p><p>In other words:</p><pre>Equality = Jump directly</pre><pre>Range = Start scanning</pre><p>Because of this, the best index is usually:</p><pre>(country, created_at)</pre><p>With this index, PostgreSQL can:</p><ol><li>Jump directly to all rows belonging to Kenya.</li><li>Scan only the relevant date range within those rows.</li></ol><p>The amount of work is dramatically reduced.</p><p>Now consider the reverse index:</p><pre>(created_at, country)</pre><p>PostgreSQL can locate the beginning of the date range.</p><p>However, within that range it must examine rows from every country and then filter out the ones that are not Kenya.</p><p>The database ends up reading far more data than necessary.</p><p>This is why column order matters so much.</p><p>The goal is not simply to include the right columns in the index.</p><p>The goal is to arrange them so PostgreSQL can eliminate as much data as possible before it starts scanning.</p><p>Whenever you design a composite index, ask yourself:</p><blockquote><em>Which columns use </em><em>= and which columns use ranges such as </em><em>BETWEEN, </em><em>&lt;, </em><em>&gt;, or </em><em>LIKE &#39;prefix%&#39;?</em></blockquote><p>In most cases, the equality columns belong first.</p><p>The range columns belong after them.</p><p>This single rule explains why some indexes feel almost magical while others seem to do very little despite containing exactly the same columns.</p><h3>Why Functions Break Indexes</h3><p>One of the most common indexing mistakes looks completely innocent.</p><p>Consider the following query:</p><pre>SELECT *<br>FROM employees<br>WHERE UPPER(last_name) = &#39;WINAND&#39;;</pre><p>At first glance, this seems perfectly reasonable.</p><p>We want a case-insensitive search, so we convert both values to uppercase.</p><p>Many developers expect PostgreSQL to use the index on last_name.</p><p>After all, the query is still searching by last name.</p><p>Unfortunately, that’s not how the optimizer sees it.</p><p>Suppose we have the following index:</p><pre>CREATE INDEX idx_last_name<br>ON employees(last_name);</pre><p>This index contains values like:</p><pre>Smith<br>Johnson<br>Murimi<br>Otieno<br>Winand</pre><p>However, our query is not searching for last_name.</p><p>It is searching for:</p><pre>UPPER(last_name)</pre><p>From PostgreSQL’s perspective, these are two different things.</p><p>Think about it this way.</p><p>The index contains:</p><pre>last_name</pre><p>But the query asks for:</p><pre>UPPER(last_name)</pre><p>The optimizer cannot assume that one can be substituted for the other.</p><p>In fact, the optimizer generally treats functions as black boxes.</p><p>To PostgreSQL, the query looks more like this:</p><pre>WHERE SOME_FUNCTION(last_name) = &#39;WINAND&#39;</pre><p>The database knows the function exists.</p><p>It knows the function returns a value.</p><p>But it cannot use an index built on last_name to search values generated by that function.</p><p>As a result, PostgreSQL often has no choice but to evaluate the function for every row in the table.</p><p>The execution plan typically changes from:</p><pre>Index Scan</pre><p>to:</p><pre>Seq Scan</pre><p>which means PostgreSQL must inspect rows one by one.</p><p>On a small table, you may never notice the difference.</p><p>On a table containing millions of rows, the performance impact can be dramatic.</p><p>To verify this, I ran the following query against our one-million-row test dataset:</p><pre>EXPLAIN ANALYZE<br>SELECT *<br>FROM employees<br>WHERE UPPER(last_name) = &#39;MURIMI&#39;;</pre><p>The execution plan showed:</p><pre>Seq Scan on employees</pre><p>Even though an index existed on last_name.</p><p>This surprises many developers the first time they encounter it.</p><p>The index exists.</p><p>The column exists.</p><p>Yet PostgreSQL ignores the index completely.</p><p>The reason is simple:</p><blockquote><em>An index on </em><em>last_name can only help PostgreSQL search </em><em>last_name.</em></blockquote><p>It cannot automatically help PostgreSQL search UPPER(last_name).</p><p>And that brings us to the solution.</p><h3>Function-Based Indexes</h3><p>Fortunately, PostgreSQL gives us a way to solve this problem.</p><p>If the query searches using:</p><pre>UPPER(last_name)</pre><p>then we can build an index on exactly that expression.</p><pre>CREATE INDEX idx_upper_last_name<br>ON employees(UPPER(last_name));</pre><p>At first, this might look strange.</p><p>Why create an index on a function?</p><p>The answer becomes obvious when we think about what PostgreSQL stores inside the index.</p><p>A normal index stores values like:</p><pre>Johnson<br>Murimi<br>Otieno<br>Smith<br>Winand</pre><p>But a function-based index stores the result of the expression instead:</p><pre>JOHNSON<br>MURIMI<br>OTIENO<br>SMITH<br>WINAND</pre><p>Now the index contains exactly the values our query is searching for.</p><p>When PostgreSQL executes:</p><pre>SELECT *<br>FROM employees<br>WHERE UPPER(last_name) = &#39;WINAND&#39;;</pre><p>it no longer needs to calculate UPPER(last_name) for every row in the table.</p><p>Instead, it can use the function-based index to jump directly to the matching entries.</p><p>To verify this, I ran the same query again after creating the index:</p><pre>EXPLAIN ANALYZE<br>SELECT *<br>FROM employees<br>WHERE UPPER(last_name) = &#39;MURIMI&#39;;</pre><p>This time the execution plan changed from:</p><pre>Seq Scan on employees</pre><p>to something similar to:</p><pre>Bitmap Index Scan on idx_upper_last_name</pre><p>or</p><pre>Index Scan using idx_upper_last_name</pre><p>The difference was dramatic.</p><p>Instead of inspecting every row in the table, PostgreSQL used the index to locate the matching records directly.</p><p>The query became fast again.</p><h3>A Word of Caution</h3><p>After learning about function-based indexes, it is tempting to index every expression you use.</p><p>Resist that temptation.</p><p>Indexes are not free.</p><p>Every index consumes resources.</p><p>Each additional index increases:</p><ul><li>Storage usage</li><li>Insert cost</li><li>Update cost</li><li>Delete cost</li></ul><p>Why?</p><p>Because every time a row changes, PostgreSQL must also update all affected indexes.</p><p>Imagine a table with five indexes.</p><p>Inserting a single row is no longer just about writing the row itself.</p><p>PostgreSQL must also update five separate index structures.</p><p>The more indexes a table has, the more work PostgreSQL must perform during writes.</p><p>This is why good indexing is not about creating more indexes.</p><p>It is about creating the right indexes.</p><p>A well-designed index can make a query hundreds of times faster.</p><p>A poorly chosen index simply increases maintenance overhead while providing little benefit.</p><p>As with most engineering decisions, indexing is a trade-off between read performance, write performance, and storage cost.Understanding LIKE Performance</p><p>Consider:</p><pre>WHERE last_name LIKE &#39;WINA%&#39;</pre><p>The database can use an index.</p><p>Why?</p><p>Because it knows exactly where names beginning with “WINA” start and stop.</p><p>Now consider:</p><pre>WHERE last_name LIKE &#39;%WINA%&#39;</pre><p>The leading wildcard changes everything.</p><p>The database has no idea where matching values begin.</p><p>The search becomes:</p><pre>Scan everything<br>Check every row</pre><p>Which effectively means a table scan.</p><p>Rule:</p><blockquote><em>Avoid leading wildcards whenever possible.</em></blockquote><h3>The Most Important Indexing Rule</h3><p>After all the examples, execution plans, and indexing techniques, it is tempting to think that database performance is mostly about memorizing rules.</p><p>It isn’t.</p><p>In fact, many indexing myths continue to circulate among developers:</p><ul><li>Put the most selective column first.</li><li>Index every searchable column.</li><li>More indexes are always better.</li><li>If an index exists, PostgreSQL will use it.</li></ul><p>As we’ve seen throughout this article, none of these statements are universally true.</p><p>The reality is much simpler.</p><p>The most important question is:</p><blockquote><em>What does the application actually search for?</em></blockquote><p>Indexes exist to support queries.</p><p>Not tables.</p><p>Not columns.</p><p>Queries.</p><p>An index is only valuable if it helps PostgreSQL answer the questions your application asks most frequently.</p><p>This is why understanding access patterns is so important.</p><p>Before creating an index, ask yourself:</p><ul><li>Which columns appear in the WHERE clause?</li><li>Which columns use equality conditions?</li><li>Which columns use ranges?</li><li>Which searches happen most often?</li><li>Which queries are actually slow?</li></ul><p>The answers to those questions are usually more valuable than any generic indexing rule.</p><p>The best developers are often the best index designers because they understand two worlds at the same time:</p><ol><li>The business workflow.</li><li>The database internals.</li></ol><p>They know how users search for information, and they understand how PostgreSQL retrieves it.</p><p>That combination allows them to build indexes that improve the performance of the entire application instead of optimizing a single query in isolation.</p><p>An index is not something you add because a column exists.</p><p>An index is something you add because a query exists.</p><h3>Final Thoughts</h3><p>Indexes are not magic.</p><p>They are carefully organized data structures whose sole purpose is to reduce the amount of data PostgreSQL must examine.</p><p>The fastest query is usually not the query running on the fastest server.</p><p>It is the query that reads the least amount of data.</p><p>Throughout this article, we saw how seemingly small changes to a WHERE clause can dramatically change the work PostgreSQL performs:</p><ul><li>A primary key lookup can locate a single row almost instantly.</li><li>A poorly ordered composite index can force PostgreSQL to scan far more data than necessary.</li><li>A function such as UPPER() can silently disable an otherwise useful index.</li><li>A leading wildcard can turn an efficient search into a full table scan.</li><li>A well-designed expression index can restore performance with a single change.</li></ul><p>When you encounter a slow query, resist the urge to immediately blame PostgreSQL.</p><p>Instead, start by asking a few simple questions:</p><ul><li>Is the WHERE clause index-friendly?</li><li>Is the column order correct?</li><li>Are equality conditions placed before range conditions?</li><li>Are functions preventing index usage?</li><li>Is a wildcard forcing PostgreSQL to scan more data than necessary?</li></ul><p>In many cases, the answer will be found there.</p><p>And once you learn to think this way, performance tuning becomes far less mysterious.</p><p>Because regardless of whether you’re using PostgreSQL, MySQL, SQL Server, Oracle, Django ORM, Hibernate, Entity Framework, or any other abstraction layer, every application eventually becomes a database application.</p><p>The developers who understand how data is searched, filtered, and retrieved will always have an advantage over those who treat the database as a black box.</p><p>The WHERE clause may look like a small part of a query.</p><p>But in many systems, it is where database performance is won or lost.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4b1eaf22bcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Boost Your Authentication With Django REST OAuth2.]]></title>
            <link>https://medium.com/@Alex_Murimi/how-to-boost-your-authentication-with-django-rest-oauth2-10f3e1706106?source=rss-6ff31833c88e------2</link>
            <guid isPermaLink="false">https://medium.com/p/10f3e1706106</guid>
            <dc:creator><![CDATA[Alex Murimi]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 04:31:03 GMT</pubDate>
            <atom:updated>2026-06-09T04:31:03.483Z</atom:updated>
            <content:encoded><![CDATA[<p>Authentication, it is the process or action of verifying the identity of a user or a process.</p><p>Web application needs a strong Authentication to keep out unwanted visitors.</p><p>You have signed into websites using your Google or Facebook account more than once, ever wonder how its know its really you?This is where OAuth2 comes in. It is like a trusted friend that vouches for you every time, it helps websites and apps verify your identity securely and quickly.</p><p>In this article, we’ll explore why good authentication matters for web applications and how OAuth2 makes the process smooth and safe.</p><h3><strong>Understanding OAuth2</strong></h3><p>OAuth stands for Open Authorization. OAuth is a trusted helper that helps different websites and apps talk to each other securely. Generally it a set of rules that lets you use your Google, Facebook, Github or other accounts to sign into other places on the Internet.</p><p>Before OAuth, if you wanted to use your Facebook account to sign in to a different website, you had to give that website your Facebook password, which is not Safe. OAuth fixed that by letting the website ask for permission to access your account without seeing your password.</p><p>OAuth makes signing in to websites safer and easier. Meaning you can use your favourite accounts to access different services without worrying about sharing your passwords everywhere.</p><h4>Key Concepts:</h4><ol><li><strong>Access Tokens:</strong></li></ol><p>Access tokens are special keys. When you sign in with your Google account, Google gives you a token. This token acts as a proof that you are really you. You can use this token to access your account on other websites without giving them your password.</p><p>2. <strong>Authorization Codes:</strong></p><p>Sometimes, to get an access token, you need an authorization code. You show the code to the website you want to access and it gives you the access token in return.</p><p>3. <strong>Scopes:</strong></p><p>Scopes are like permissions, they tell websites and apps what they are allowed to do with your account. For example, a website might ask for permission to view your email address but not your photos.</p><h3>Setting Up Django REST Framework with OAuth2</h3><p>Now’s lets make our Django backend work smoothly with OAuth2 authentication.</p><h4>Step 1: Installing Necessary Packages:</h4><p>First, we need to install a special toolkit called django-auth-toolkit . It is a set of tools that helps Django work with OAuth2.</p><p>Open your command prompt or terminal and type:</p><pre>pip install django-oath-toolkit</pre><h4>Step 2: Configuring Django Settings</h4><p>Now, we need to tell Django to use OAuth2 for authentication.</p><p>To do this, Open your settings.py file in your Django project and add &#39;oauth2_provider&#39; to the INSTALLED_APPS list.</p><pre>INSTALLED_APPS = [<br>  # Other apps ...<br>  &#39;oauth2_provider&#39;,<br>]</pre><p>Then, we will add &#39;oath2_provider.middleware.OAuth2TokenMiddleware&#39; to the MIDDLEWARE list.</p><pre>MIDDLEWARE = [<br>    # other middleware ...<br>    &#39;oauth2_provider.middleware.OAuth2TokenMiddleware&#39;,<br>]</pre><p>Next, Configure Django REST Framework to accept OAuth2 authentication by adding &#39;rest_framework.authentication.OAuth2Authentication&#39; to the DEFAULT_AUTHENTICATION_CLASSES setting:</p><pre>REST_FRAMEWORK = {<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: (<br>        &#39;rest_framework.authentication.OAuth2Authentication&#39;,<br>        # other authentication classes ....<br>    ),<br>}</pre><h4>Step 3: Creating OAuth2 Provider:</h4><p>Next, we need to create an OAuth2 Provider. This is creating all the necessary tables in your database to manage OAuth2 tokens.</p><p>Run this command in your terminal:</p><pre>python manage.py migrate oauth2_provider</pre><h4>Step 4: Configuring OAuth2 Providers:</h4><p>Let’s configure OAuth2 Providers for GitHub, Google and Facebook. These providers will help us connect to their authentication systems.</p><ol><li>Optain OAuth2 Credentials:</li></ol><p><strong>For Google:</strong></p><ol><li><em>Go to the </em><a href="https://console.cloud.google.com/"><em>Google Cloud Console</em></a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MudTQJzBA6ggGx4WR-Ding.png" /><figcaption>This is the Google Cloud console account</figcaption></figure><p><em>2. Create a new project or select an existing one.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6AH8U67BEKu3-RdkHtM-Xg.png" /><figcaption>creating a new project</figcaption></figure><p><em>3 .Navigate to the “Credentials” page.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiCUd7m9HwDdztqfrEC6dg.png" /><figcaption>Navigating to the credential page</figcaption></figure><p><em>4. Click on “Create Credentials” and select “OAuth client ID”.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MimC25GmY1hQzMQrNsv82w.png" /><figcaption>selecting OAuth Client Id</figcaption></figure><p><em>5. choose “web application” as the application type.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DF_keO8xb0tFGpmq_jG-QA.png" /></figure><p><em>6. Add your websites URL as an authorization redirect URL.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lm_4ugQt0YovWH4yv7ROVA.png" /></figure><p><em>7. After creating the OAuth client, you will get the client ID and client secret.</em></p><p>For Facebook:</p><ol><li>Go to the <a href="https://developers.facebook.com/">Facebook Developers</a> website</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1pVE4_Tw6tXI9ED_Epdc_g.png" /></figure><p>2. Create a new app or select an existing one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5kY96Oo-pdOo0rY9gU5LEA.png" /></figure><p>3. Navigate to the “Settings” page of your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zfIrYCmqT2Udn1KIcRttGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*otmyIWbQ0xheVPxctmpAwA.png" /></figure><p>4. Under “Basic Setting”, you’ll find your App ID and App Secret.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HeQLBz0vLoAfSJ1yiz1LQQ.png" /></figure><blockquote>“i deleted the created projects, so don&#39;t use the details provided, just showing you how to do.”</blockquote><p>In your settings.py file add configuration settings for each provider:</p><pre># Github OAuth2 Provider Configuration<br>OAUTH2_PROVIDER = {<br>    &#39;SCOPES&#39; : {&#39;read&#39;, &#39;write&#39;, &#39;userinfo&#39;},<br>    &#39;CLIENT_ID&#39;: &#39;your-github-client-id&#39;,<br>    &#39;CLIENT_SECRET&#39;: &#39;your-github-client-secret&#39;,<br>    &#39;GITHUB_EXTRA_DATA&#39;: [(&#39;login&#39;, &#39;login&#39;)],<br>}<br><br># Google OAuth2 Provider Configuration<br>OAUTH2_PROVIDER = {<br>    &#39;SCOPES&#39; : {&#39;read&#39;, &#39;write&#39;, &#39;userinfo&#39;},<br>    &#39;CLIENT_ID&#39;: &#39;your-google-client-id&#39;,<br>    &#39;CLIENT_SECRET&#39;: &#39;your-google-client-secret&#39;,<br>    &#39;GOOGLE_EXTRA_DATA&#39;: [(&#39;id&#39;, &#39;id&#39;)],<br>}<br># Facebook OAuth2 Provider Configuration<br>OAUTH2_PROVIDER = {<br>    &#39;SCOPES&#39; : {&#39;read&#39;, &#39;write&#39;, &#39;userinfo&#39;},<br>    &#39;CLIENT_ID&#39;: &#39;your-facebook-app-id&#39;,<br>    &#39;CLIENT_SECRET&#39;: &#39;your-facebook-app-secret&#39;,<br>    &#39;FACEBOOK_EXTRA_DATA&#39;: [(&#39;id&#39;, &#39;id &#39;)],<br>}</pre><p>Replace &#39;your-github-client-id&#39; and your-github-client-secret with your actual GitHub client ID and client secret.</p><p>Replace &#39;your-google-client-id&#39; and &#39;your-google-client-secret&#39; with the client ID and client secret obtained from the Google Cloud Console.</p><p>Replace &#39;your-facebook-app-id&#39; and &#39;your-facebook-app-secret&#39; with the App ID and App Secret obtained from the Facebook Developers website.</p><h4>Step 5: Configuring Authentication Backends:</h4><p>Specify the authentication Backends to be used in the AUNTHENTICATION_BACKENDS setting</p><pre>AUTHENTICATION_BACKENDS = (<br>  &#39;oauth2_provider.backends.OAuth2Backend&#39;,<br>  # other Backends ....<br>)</pre><h4>Step 6: Update Django URLS:</h4><p>In your Django project’s urls.py file, include URL patterns to handle authentication with Google, Facebook or Github OAuth2 providers.</p><pre>from django.urls import path, include<br><br>urlpatterns = [<br>    #other URL patterns ...<br>    path(&#39;auth/&#39;, include(&#39;oauth2.provider.urls&#39;, namespace=&#39;oauth2_provider)),<br>]<br></pre><p>This includes Django OAuth2 Toolkit’s URLs, which provide endpoints for handling OAuth2 authentication flows.</p><h4>Step 7: Configure OAuth2 Redirect URls:</h4><p>Make sure to add the appropriate redirect URls for Google and Facebook OAuth2 providers in their respective developer console settings:</p><p>. For Google, the redirect URl should be something like:</p><p>http://localhost:5000/auth/complete/google-oauth2/ .</p><p>. For Facebook, the redirect URl should be something like:</p><p>http://localhost:5000/auth/complete/Facebook/ .</p><p>These URls are where the OAuth2 providers will redirect users after they’ve authenticated.</p><p>Step 8: Applying Changes:</p><p>Make sure to apply any changes to your Django project’s configuration by running the following command.</p><pre>python manage.py migrate</pre><p>Now, your Django project is configured to handle authentication with Google and Facebook OAuth2 providers.</p><p>When users attempt to sign in using their Google or Facebook accounts, they will be redirected to the appropriate authentication pages, and upon successful authentication, they will be redirected back to your application with the necessary tokens to authenticate their requests.</p><h4>BACKEND APPLICATION (<em>Easy 4 Steps</em>)</h4><p>We are going to create an application that allows users to register and start using tokens.</p><p><strong>Step 1. Create an app</strong></p><p>This is the first step, creating an app for our users.</p><pre>python manage.py startapp users</pre><p>We will need to install the apps in our settings, so that Django can find it.</p><pre>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    ....<br>    <br>    &#39;oauth2_provider&#39;,<br>    &#39;rest_framework&#39;,<br>    <br>    &#39;users&#39;,<br>]</pre><p><strong>Step 2: Create Serializers for User Registration</strong></p><p>We will use the Django’s built-in User Model.</p><p>In Django a model specifies how a table in the SQL database should look, and lets you put and extract data from the database, and, a serializer is a way to create and fetch models in an API format.</p><pre>from rest_framework import serializers<br>from django.contrib.auth.models import User<br><br>class CreateUserSerializer(Serializers.ModelSerializer):<br><br>    def create(self, validated_data):<br>        user = User.objects.create_user(**validated_data)<br>        return user<br>    <br>    class Meta: <br>          model = User<br>          fields = [&#39;id&#39;, &#39;username&#39;, &#39;email&#39;, &#39;password&#39;]<br>          extra_kwargs = { <br>                &#39;password&#39;: {&#39;write_only&#39;: True}<br>          }</pre><p>The <em>create </em>method overrides the default behaviour when saving a user. The details are not too important, but this is important to make sure that the password is hashed correctly.</p><p><strong>Step 3: Create the views</strong></p><p>We will need a couple of views for handling,</p><p>I) Register</p><p>II) Token (Login)</p><p>III) Refresh (Login Next Time)</p><p>IV) Revoke (Log out)</p><p>V) GoogleAuthCompleteView</p><p>VI) FacebookAuthCompleteView</p><pre>from rest_framework import generics, status<br>from rest_framework.response import Response<br>from Django.contrib.auth.models import User<br>from rest_framework.authtoken.views import ObtainedAuthToken<br>from rest_framework.permissions import IsAuthenticated<br>from .serializers import UserSerializer, TokenSerializer<br><br>class UserCreaeAPIView(generics.CreateAPIView):<br>      queryset = User.objects.all()<br>      serializer_class = UserSerializer<br>      def create(self, request, *args, **kwargs):<br>          serializer = self.get_serializer(data=request.data)<br>          serializer.is_valid(raise_exception=True)<br>          self.perform_create(serializer)<br>          token, created = Token.objects.get_or_create(user=serializer.instance)<br>          return Response({&#39;token&#39;: token.key}, status=status.HTTP_201_CREATED)<br><br>       def perform_create(self, serializer):<br>            return serializer.save()<br><br>class CustomObtainAuthToken(ObtainAuthToken):<br><br>    def post(self, request, *args, **kwargs):<br>   <br>        serializer = self.serializer_class(data=request.data, context={&#39;request&#39;: request})<br>        serializer.is_valid(raise_exception=True)<br>        user = serializer.validated_data[&#39;user&#39;]<br>        # Generate or retrieve existing authentication token for the user<br>        token, created = Token.objects.get_or_create(user=user)<br>        # Return the authentication token along with the response<br>        return Response({&#39;token&#39;: token.key}, status=status.HTTP_200_OK)<br><br>class TokenRefreshAPIView(generics.GenericAPIView):<br><br>    permission_classes = [IsAuthenticated]<br><br>    def post(self, request, *args, **kwargs):<br>    <br>        # Generate a new token for the authenticated user<br>        token, created = Token.objects.get_or_create(user=request.user)<br>        # Return the new authentication token along with the response<br>        return Response({&#39;token&#39;: token.key}, status=status.HTTP_200_OK)<br><br>class TokenRevokeAPIView(generics.GenericAPIView):<br> <br>    permission_classes = [IsAuthenticated]<br><br>    def post(self, request, *args, **kwargs):<br>     <br>        # Delete the authentication token associated with the authenticated user<br>        request.user.auth_token.delete()<br>        # Return success response<br>        return Response(status=status.HTTP_200_OK)<br><br>def GoogleAuthCompleteView(request):<br> <br>    # Extract access token from the request<br>    access_token = request.GET.get(&#39;access_token&#39;)<br><br>    # Example logic to authenticate user based on access token<br>    user_data = get_user_data_from_google(access_token)<br>    user = authenticate(request, user_data=user_data)<br><br>    if user is not None:<br>        login(request, user)<br>        return Response({&#39;message&#39;: &#39;Successfully authenticated&#39;}, status=status.HTTP_200_OK)<br>    else:<br>        return Response({&#39;error&#39;: &#39;Authentication failed&#39;}, status=status.HTTP_401_UNAUTHORIZED)<br><br>def FacebookAuthCompleteView(request):<br>  <br>    # Extract access token from the request<br>    access_token = request.GET.get(&#39;access_token&#39;)<br><br>    # Example logic to authenticate user based on access token<br>    user_data = get_user_data_from_facebook(access_token)<br>    user = authenticate(request, user_data=user_data)<br><br>    if user is not None:<br>        login(request, user)<br>        return Response({&#39;message&#39;: &#39;Successfully authenticated&#39;}, status=status.HTTP_200_OK)<br>    else:<br>        return Response({&#39;error&#39;: &#39;Authentication failed&#39;}, status=status.HTTP_401_UNAUTHORIZED)<br></pre><p><strong>Step 4: Bind the urls</strong></p><p>The last step is to create the urls.</p><p>This can be done by creating a new file in the users app called urls.py</p><p>This is my sample urls.</p><pre><br>from django.urls import path<br>from .views import (<br>    UserCreateAPIView,<br>    CustomObtainAuthToken,<br>    TokenRefreshAPIView,<br>    TokenRevokeAPIView,<br>    GoogleAuthCompleteView,<br>    FacebookAuthCompleteView<br>)<br><br>urlpatterns = [<br>    # User registration endpoint<br>    path(&#39;register/&#39;, UserCreateAPIView.as_view(), name=&#39;register&#39;),<br>    # Token generation endpoint (login)<br>    path(&#39;api-token-auth/&#39;, CustomObtainAuthToken.as_view(), name=&#39;api_token_auth&#39;),<br>    # Token refresh endpoint (login next time)<br>    path(&#39;api-token-refresh/&#39;, TokenRefreshAPIView.as_view(), name=&#39;api_token_refresh&#39;),<br>    # Token revocation endpoint (logout)<br>    path(&#39;api-token-revoke/&#39;, TokenRevokeAPIView.as_view(), name=&#39;api_token_revoke&#39;),<br>    # Google OAuth2 completion redirect URL<br>    path(&#39;complete/google-oauth2/&#39;, GoogleAuthCompleteView.as_view(), name=&#39;google_oauth2_complete&#39;),<br>    # Facebook OAuth2 completion redirect URL<br>    path(&#39;complete/facebook/&#39;, FacebookAuthCompleteView.as_view(), name=&#39;facebook_oauth2_complete&#39;),<br>]</pre><p>Then we will need to add to add these route to the main app.</p><pre>from django.urls import path, include<br><br>urlpatterns = [<br>    #other URL patterns ...<br>    path(&#39;auth/&#39;, include(&#39;users.urls&#39;)),<br>]</pre><h3>Summary</h3><p>We have boosted authentication using Django Rest OAuth2. This is a fair guideline and example. Next we will look at implementing the same using react.</p><p>Thank you</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10f3e1706106" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are N-Grams in Python, and how to implement them using Python nltk?]]></title>
            <link>https://medium.com/@Alex_Murimi/what-are-n-grams-in-python-and-how-to-implement-them-using-python-nltk-b42202ddfc38?source=rss-6ff31833c88e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b42202ddfc38</guid>
            <dc:creator><![CDATA[Alex Murimi]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 04:31:02 GMT</pubDate>
            <atom:updated>2026-06-08T04:31:02.403Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will understand n-grams and how to implement them in Python.</p><h3>Definition and understanding of n-grams.</h3><p>Text n-grams refer to a sequence of strings of words that simultaneously appear in the same window, and they can also be sequences of words, tokens, or symbols in a document.</p><p>They are commonly utilized in natural language processing and text mining.</p><h3>Classification of n-grams.</h3><p>The n in n-grams represents the nth value N holding a positive integer, for example, 1,2,3, and so on.</p><p>We have several classifications of n-grams, depending on the number that n represents. For instance:</p><ul><li>An n-gram of size 2, N = 1, is a unigram</li><li>An n-gram of size 2, N = 2, is a bigram.</li><li>An n-gram of size 3, N = 3, is a trigram.</li></ul><p>An n-gram can be of any size, and different types of n-grams are suitable for different applications.</p><p>For instance, for a sentence like “I am an IT enthusiast.”</p><p>If N = 1, then the n-grams are:</p><ul><li>(‘I’)</li><li>(‘am’)</li><li>(‘an’)</li><li>(‘IT’)</li><li>(‘enthusiast’)</li></ul><p>If N = 2, then the n-grams are:</p><ul><li>(‘I’, ‘am’)</li><li>(‘am’, ‘an’)</li><li>(‘an’, ‘IT’)</li><li>(‘IT’, ‘enthusiast’)</li></ul><p>If N = 3, then the n-grams are:</p><ul><li>(‘I’, ‘am’, ‘an’)</li><li>(‘am’, ‘an’, ‘IT’)</li><li>(‘an’, ‘IT’, ‘enthusiast’)</li></ul><h3>Stepwise implementation of n-grams in Python</h3><p>This is where the fun starts. It would be hurtful to learn all about n-grams and not implement them.</p><p>To implement n-gram in Python, we will fire up <a href="https://colab.research.google.com/">Google Colab</a> and proceed to code.</p><p>We will take the following steps:</p><p>· <strong>Explore</strong> the data set.</p><p>· <strong>Feature extraction</strong>.</p><p>· <strong>Split</strong> dataset into train and test sets.</p><p>· Basic <strong>pre-processing</strong>.</p><p>· Generating the n-grams.</p><h3>The data set</h3><p>We will use the <a href="https://www.kaggle.com/datasets/ankurzing/sentiment-analysis-for-financial-news">Sentiment Analysis for Financial News</a> dataset available on <a href="https://www.kaggle.com/">Kaggle</a>. This dataset contains the sentiments for financial news headlines from the perspective of a retail investor.</p><p><strong>Let’s, begin by downloading the required libraries and reading and understanding the data.</strong></p><pre>import pandas as pd<br>df = pd.read_csv(‘FinancialPhraseBank.csv’)<br>df.info</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*HEM4BglIHIq62Gwzc46dow.png" /></figure><p>We observe that the dataset has 4846 rows and two columns:’ Sentiment’ and ‘News Headline.’</p><p>Check if the dataset has null values:</p><pre>df.isna().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*DTI9XrgW7DZsTAtruxBeEQ.png" /></figure><pre> df[&#39;Sentiment&#39;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*aDYFRS_lAxJCbhbzUtM9tA.png" /></figure><p>We can see that there exist 3 types of sentiments.</p><p>· Neutral</p><p>· Positive</p><p>· Negative</p><p>Our objective on this dataset is to predict the sentiments of a given news headline. The ‘News Headline’ column will serve as the <strong>independent variable</strong>, and the ‘Sentiments’ column will be our <strong>target variable</strong>.</p><pre>y=df[&#39;Sentiment&#39;].values<br>y.shape</pre><pre>x=df[&#39;News Headline&#39;].values<br>y.shape</pre><h3>Split the dataset into training and testing sets</h3><p>Splitting the dataset into train and test sets is a crucial step in machine learning, deep learning, or NLP (natural language processing). We will use the method <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html">train_test_split()</a> provided by the <a href="https://scikit-learn.org/">Sklearn</a> library. So, let’s begin by importing it.</p><pre>from sklearn.model_selection import train_test_split</pre><p>We will split the data into 60% for the train and 40% for the test sets. For a start, 20% is best for a test, then keep playing with the test_size parameter. After this, we will discover that the 60–40 ratio of split provides more valuable and meaningful insights from the trigrams generated.</p><pre>(x_train,x_test,y_train,y_test)=train_test_split(x,y,test_size=0.4)<br>x_train.shape<br>y_train.shape<br>x_test.shape<br>y_test.shape</pre><p>After executing the codes above, you will observe that 2907 rows have been considered the train data, and 1937 rows as the test data.</p><p>We will create two data frames but first, convert these NumPy arrays to Pandas data frames which are:</p><ul><li>df_train</li><li>df_test</li></ul><p>We get the first by concatenating x_train and y_train arrays and the latter data by concatenating x_test and y_test arrays. This is crucial to get the number of positive, negative, and neutral sentiments in both train and test datasets.</p><pre>df1=pd.DataFrame(x_train)<br>df1=df1.rename(columns={0:&#39;news&#39;})</pre><pre>df2=pd.DataFrame(y_train)<br>df2=df2.rename(columns={0:&#39;sentiment&#39;})<br>df_train=pd.concat([df1,df2],axis=1)</pre><pre>df_train.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*aBecve3_d-GOSwgyDHdR2Q.png" /></figure><pre>df3=pd.DataFrame(x_test)<br>df3=df3.rename(columns={0:&#39;news&#39;})</pre><pre>df4=df2.rename(columns={0:&#39;sentiment&#39;})<br>df_test=pd.concat([df3,df4],axis=1)</pre><pre>df_test.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*sl2Wh_akGx79wMSxPKnbEg.png" /></figure><h3>Basic pre-processing of train data and test data:</h3><p><strong>In this section, we will remove all punctuations in the train and test data for the ‘news’ column, using the punctuations provided by the string library.</strong></p><pre>#removing punctuations<br>#library that contains punctuation<br>import string<br>string.punctuation</pre><pre>#defining the function to remove punctuation<br>def remove_punctuation(text):<br>  if(type(text)==float):<br>    return text<br>  ans=&quot;&quot;  <br>  for i in text:     <br>    if i not in string.punctuation:<br>      ans+=i    <br>  return ans</pre><pre>#storing the punctuation free text in a new column called clean_msg<br>df_train[&#39;news’] = df_train[&#39;news&#39;].apply(lambda x:remove_punctuation(x))<br>df_test[&#39;news’] = df_test[&#39;news&#39;].apply(lambda x:remove_punctuation(x))</pre><pre>df_train.head()<br>#punctuations are removed from news column in train dataset</pre><p><strong>Comparing the results of df_train, we notice that the punctuations have been removed. That can be seen in the text present in the feature column of the training dataset.</strong></p><p><strong>The same code will also remove all punctuations from the test data frame’s news column.</strong></p><p><strong>To remove all the stopwords from the news column, we will use stopwords provided by the NLTK as follows:</strong></p><pre>import nltk<br>from nltk.corpus import stopwords<br>nltk.download(&#39;stopwords&#39;)</pre><h3>Generating n-grams</h3><p>Let’s now generate some n-grams.</p><pre>#method to generate n-grams:<br>#params:<br>#text-the text for which we have to generate n-grams<br>#ngram-number of grams to be generated from the text(1,2,3,4 etc., default value=1)<br></pre><pre>def generate_N_grams(text,ngram=1):<br>  words=[word for word in text.split(&quot; &quot;) if word not in set(stopwords.words(&#39;english&#39;))]  <br>  print(&quot;Sentence after removing stopwords:&quot;,words)<br>  temp=zip(*[words[i:] for i in range(0,ngram)])<br>  ans=[&#39; &#39;.join(ngram) for ngram in temp]<br>  return ans</pre><p>The above function inputs two parameters, i.e., text(text data we want to generate a specified number of n-grams) and n-grams(number of grams to be generated).</p><p>First, word tokenization is done, where all stopwords are ignored, and the remaining are retained. From the explanation, we could generate n-grams manually. Do you remember? The same logic we have used in the function generate_N_grams()</p><p>Testing the working of the function:</p><pre>#sample!<br>generate_N_grams(&quot;The sun rises in the east&quot;,2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*1HgQ79ueiPB4fdq8oWkFZQ.png" /></figure><p>Cool, it works!</p><h3>Creating Uni-grams</h3><p>We will create unigrams for the news column in the df_train data frame.</p><p>Creating unigrams for each news record belonging to the 3 categories of sentiments (neutral, positive, and negative).</p><p>We will use the following steps:</p><p>· <strong>Store </strong>the word and its count in the corresponding dictionaries.</p><p>· <strong>Convert </strong>the dictionaries into the corresponding data frames.</p><p>· <strong>Fetch </strong>the top 10 frequently used words.</p><p>· <strong>Visualize </strong>the most frequently used word from the 3 categories<strong>.</strong></p><pre>from collections import defaultdict</pre><pre>positiveValues=defaultdict(int)<br>negativeValues=defaultdict(int)<br>neutralValues=defaultdict(int)<br>#get the count of every word in both the columns of df_train and df_test dataframes</pre><pre>#get the count of every word in both the columns of df_train and df_test dataframes where sentiment=&quot;positive&quot;<br>for text in df_train[df_train.sentiment==&quot;positive&quot;].news:<br>  for word in generate_N_grams(text):<br>    positiveValues[word]+=1</pre><pre>#get the count of every word in both the columns of df_train and df_test dataframes where sentiment=&quot;negative&quot;<br>for text in df_train[df_train.sentiment==&quot;negative&quot;].news:<br>  for word in generate_N_grams(text):<br>    negativeValues[word]+=1</pre><pre>#get the count of every word in both the columns of df_train and df_test dataframes where sentiment=&quot;neutral&quot;<br>for text in df_train[df_train.sentiment==&quot;neutral&quot;].news:<br>  for word in generate_N_grams(text):<br>    neutralValues[word]+=1</pre><pre>#focus on more frequently occuring words for every sentiment=&gt;<br>#sort in DO wrt 2nd column in each of positiveValues,negativeValues and neutralValues<br>df_positive=pd.DataFrame(sorted(positiveValues.items(),key=lambda x:x[1],reverse=True))<br>df_negative=pd.DataFrame(sorted(negativeValues.items(),key=lambda x:x[1],reverse=True))<br>df_neutral=pd.DataFrame(sorted(neutralValues.items(),key=lambda x:x[1],reverse=True))</pre><pre>pd1=df_positive[0][:10]</pre><pre>pd2=df_positive[1][:10]</pre><pre>ned1=df_negative[0][:10]<br>ned2=df_negative[1][:10]</pre><pre>nud1=df_neutral[0][:10]<br>nud2=df_neutral[1][:10]</pre><pre>plt.figure(1,figsize=(16,4))<br>plt.bar(pd1,pd2, color =&#39;green&#39;,<br>        width = 0.4)<br>plt.xlabel(&quot;Words in positive dataframe&quot;)<br>plt.ylabel(&quot;Count&quot;)<br>plt.title(&quot;Top 10 words in positive dataframe-UNIGRAM ANALYSIS&quot;)<br>plt.savefig(&quot;positive-unigram.png&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*euvFN6lYz746NXkHKVD9WA.png" /></figure><pre>plt.figure(1,figsize=(16,4))<br>plt.bar(ned1,ned2, color =&#39;red&#39;,<br>        width = 0.4)<br>plt.xlabel(&quot;Words in negative dataframe&quot;)<br>plt.ylabel(&quot;Count&quot;)<br>plt.title(&quot;Top 10 words in negative dataframe-UNIGRAM ANALYSIS&quot;)<br>plt.savefig(&quot;negative-unigram.png&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*bq-9uf7iUAYJLYTjk_kp7g.png" /></figure><pre>plt.figure(1,figsize=(16,4))<br>plt.bar(nud1,nud2, color =&#39;yellow&#39;,<br>        width = 0.4)<br>plt.xlabel(&quot;Words in neutral dataframe&quot;)<br>plt.ylabel(&quot;Count&quot;)<br>plt.title(&quot;Top 10 words in neutral dataframe-UNIGRAM ANALYSIS&quot;)<br>plt.savefig(&quot;neutral-unigram.png&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*AxaJ5UhqiYm2KPen-SDz2w.png" /></figure><h3>Creating Bi-grams</h3><p>This is relatively easier. We only have to follow the same steps we did when creating unigrams. Only this time will we have to pass the parameter 2 while invoking the generate_N_grams().</p><pre>positiveValues2=defaultdict(int)<br>negativeValues2=defaultdict(int)<br>neutralValues2=defaultdict(int)<br>#get the count of every word in both the columns of df_train and df_test dataframes</pre><pre>#get the count of every word in both the columns of df_train and df_test dataframes where sentiment=&quot;positive&quot;<br>for text in df_train[df_train.sentiment==&quot;positive&quot;].news:<br>  for word in generate_N_grams(text,2):<br>    positiveValues2[word]+=1</pre><pre>#get the count of every word in both the columns of df_train and df_test dataframes where sentiment=&quot;neutral&quot;<br>for text in df_train[df_train.sentiment==&quot;neutral&quot;].news:<br>  for word in generate_N_grams(text,2):<br>    neutralValues2[word]+=1</pre><pre>#focus on more frequently occuring words for every sentiment=&gt;<br>#sort in DO wrt 2nd column in each of positiveValues,negativeValues and neutralValues</pre><pre>df_positive2=pd.DataFrame(sorted(positiveValues2.items(),key=lambda x:x[1],reverse=True))<br>df_negative2=pd.DataFrame(sorted(negativeValues2.items(),key=lambda x:x[1],reverse=True))<br>df_neutral2=pd.DataFrame(sorted(neutralValues2.items(),key=lambda x:x[1],reverse=True))</pre><pre>pd1bi=df_positive2[0][:10]<br>pd2bi=df_positive2[1][:10]</pre><pre>ned1bi=df_negative2[0][:10]<br>ned2bi=df_negative2[1][:10]</pre><pre>nud1bi=df_neutral2[0][:10]<br>nud2bi=df_neutral2[1][:10]</pre><pre>plt.figure(1,figsize=(16,4))</pre><pre>plt.bar(pd1bi,pd2bi, color =&#39;green&#39;,width = 0.4)</pre><pre>plt.xlabel(&quot;Words in positive dataframe&quot;)</pre><pre>plt.ylabel(&quot;Count&quot;)</pre><pre>plt.title(&quot;Top 10 words in positive dataframe-BIGRAM ANALYSIS&quot;)</pre><pre>plt.savefig(&quot;positive-bigram.png&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*cFhtFtipMnEHIsoHsiQjeQ.png" /></figure><pre>plt.figure(1,figsize=(16,4))<br>plt.bar(ned1bi,ned2bi, color =&#39;red&#39;,<br>        width = 0.4)<br>plt.xlabel(&quot;Words in negative dataframe&quot;)<br>plt.ylabel(&quot;Count&quot;)<br>plt.title(&quot;Top 10 words in negative dataframe-BIGRAM ANALYSIS&quot;)<br>plt.savefig(&quot;negative-bigram.png&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*oG17lFLtiWAkLlBex5Ptqg.png" /></figure><pre>plt.figure(1,figsize=(16,4))<br>plt.bar(nud1bi,nud2bi, color =&#39;yellow&#39;,<br>        width = 0.4)<br>plt.xlabel(&quot;Words in neutral dataframe&quot;)<br>plt.ylabel(&quot;Count&quot;)<br>plt.title(&quot;Top 10 words in neutral dataframe-BIGRAM ANALYSIS&quot;)<br>plt.savefig(&quot;neutral-bigram.png&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*7aNBqzDK7gf8jomFF40s8w.png" /></figure><h3>Creating Tri-grams</h3><p>This is quite easier, we only have to follow the same steps that we did, when creating unigrams and bigrams. We will have to pass the parameter 3 while invoking the generate_N_grams().</p><pre>positiveValues3=defaultdict(int)<br>negativeValues3=defaultdict(int)<br>neutralValues3=defaultdict(int)<br>#get the count of every word in both the columns of df_train and df_test dataframes</pre><pre>#get the count of every word in both the columns of df_train and df_test dataframes where sentiment=&quot;positive&quot;<br>for text in df_train[df_train.sentiment==&quot;positive&quot;].news:<br>  for word in generate_N_grams(text,3):<br>    positiveValues3[word]+=1</pre><pre>#get the count of every word in both the columns of df_train and df_test dataframes where sentiment=&quot;negative&quot;<br>for text in df_train[df_train.sentiment==&quot;negative&quot;].news:<br>  for word in generate_N_grams(text,3):<br>    negativeValues3[word]+=1</pre><pre>#get the count of every word in both the columns of df_train and df_test dataframes where sentiment=&quot;neutral&quot;<br>for text in df_train[df_train.sentiment==&quot;neutral&quot;].news:<br>  for word in generate_N_grams(text,3):</pre><pre>    neutralValues3[word]+=1#focus on more frequently occuring words for every sentiment=&gt;<br>#sort in DO wrt 2nd column in each of positiveValues,negativeValues and neutralValues<br>df_positive3=pd.DataFrame(sorted(positiveValues3.items(),key=lambda x:x[1],reverse=True))<br>df_negative3=pd.DataFrame(sorted(negativeValues3.items(),key=lambda x:x[1],reverse=True))<br>df_neutral3=pd.DataFrame(sorted(neutralValues3.items(),key=lambda x:x[1],reverse=True))</pre><pre>pd1tri=df_positive3[0][:10]<br>pd2tri=df_positive3[1][:10]</pre><pre>ned1tri=df_negative3[0][:10]<br>ned2tri=df_negative3[1][:10]</pre><pre>nud1tri=df_neutral3[0][:10]<br>nud2tri=df_neutral3[1][:10]</pre><pre>plt.figure(1,figsize=(16,4))<br>plt.bar(pd1tri,pd2tri, color =&#39;green&#39;,<br>        width = 0.4)</pre><pre>plt.xlabel(&quot;Words in positive dataframe&quot;)<br>plt.ylabel(&quot;Count&quot;)<br>plt.title(&quot;Top 10 words in positive dataframe-TRIGRAM ANALYSIS&quot;</pre><pre>plt.savefig(&quot;positive-trigram.png&quot;)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*hd8velS4fW6cryVoZzhYPA.png" /></figure><pre>plt.figure(1,figsize=(16,4))<br>plt.bar(ned1tri,ned2tri, color =&#39;red&#39;,<br>        width = 0.4) <br>plt.xlabel(&quot;Words in negative dataframe&quot;)<br>plt.ylabel(&quot;Count&quot;)<br>plt.title(&quot;Top 10 words in negative dataframe-TRIGRAM ANALYSIS&quot;)<br>plt.savefig(&quot;negative-trigram.png&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*fG6tDfKioP1rofiiZxYL8w.png" /></figure><pre>plt.figure(1,figsize=(16,4))<br>plt.bar(nud1tri,nud2tri, color =&#39;yellow&#39;,<br>        width = 0.4) <br>plt.xlabel(&quot;Words in neutral dataframe&quot;)<br>plt.ylabel(&quot;Count&quot;)<br>plt.title(&quot;Top 10 words in neutral dataframe-TRIGRAM ANALYSIS&quot;)<br>plt.savefig(&quot;neutral-trigram.png&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*YC0xGwWCNnHoxi2feBuI-A.png" /></figure><h3>Results of the model.</h3><p>From the above graphs, trigrams perform the best on our train data. This is because it provides words frequently, such as:</p><ul><li><strong>profit rose EUR.</strong></li><li><strong>year earlier</strong> for the positive data frame,</li><li><strong>corresponding period</strong>, <strong>period 2007.</strong></li><li>names of companies such as <strong>HEL</strong> for the negative data frame and <strong>Finland</strong> company.</li><li>names of companies such as HEL, <strong>OMX Helsinki</strong>, and so on for the neutral data frame.</li></ul><h3>Final thoughts</h3><p>We have learned n-grams and how we can generate any number of n-grams for a given dataset in Python to help us analyze data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b42202ddfc38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[INDEXES: The Most Important Database Concept Every Developer Should Learn.]]></title>
            <link>https://medium.com/@Alex_Murimi/indexes-the-most-important-database-concept-every-developer-should-learn-e656349a9b21?source=rss-6ff31833c88e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e656349a9b21</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[database-design]]></category>
            <dc:creator><![CDATA[Alex Murimi]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 20:12:48 GMT</pubDate>
            <atom:updated>2026-06-06T20:12:48.246Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>SQL tells the database <em>what</em> data is needed. Indexes determine <em>how quickly</em> that data can be found.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Guq5jVdpYjDZ--oRmJdzDw.png" /></figure><h3>The SQL Perfomance Mystery</h3><p>One of the biggest surprises for new developers is discovering that two SQL queries can return the same result while having dramatically different performance.</p><p>Consider:</p><pre>SELECT date_of_birth<br>FROM employees<br>WHERE last_name = &#39;ALEX&#39;;</pre><p>The query looks simple.</p><p>It reads almost like English.</p><p>The beauty of SQL is that we only describe <strong>what </strong>we want.</p><blockquote>Find the date of birth for employees whose last name is ALEX.</blockquote><p>We never tell the database:</p><ul><li>which file to open</li><li>which rows to inspect</li><li>how to search</li><li>where the data lives on disk</li></ul><p>The database decides all of that for us.</p><p>This abstaction is one of the greatest achievements in software engineering.</p><p>But it comes with a hidden cost:</p><blockquote>Developers stop thinking about how data is accessed.</blockquote><p>And that’s where performance problems begin.</p><h3>The Illusion That Databases Are Slow.</h3><p>Many engineers have heard statements like:</p><ul><li>“SQL is slow.”</li><li>“The database is the bottleneck.”</li><li>“We need a bigger server.”</li></ul><p>In reality, databases are astonishingly fast.</p><p>Modern databases can search billions of records in milliseconds.</p><p>The problem is usually not the database.</p><p>The problem is asking the database to do unnecessary work.</p><p>Imagine looking for a name in:</p><ul><li>an unsorted stack of papers</li><li>a telephone directory</li></ul><p>The first requires checking every page.</p><p>The second lets you jump directly to the correct section.</p><p>The telephone directory is essentially what an index provides.</p><h3>What Is a Database Index?</h3><p>A database index is a separate data structure that helps the database locate data quickly.</p><p>Just like the index at the back of a book:</p><ul><li>It occupies additional space.</li><li>It duplicates information.</li><li>It points to the actual content.</li></ul><p>An index is pure redundancy.</p><p>The table already contains the data.</p><p>The index stores additional information so that the database can find that data faster.</p><h3>Why Database Need Indexes</h3><p>Imagine a table containing 10 million employees.</p><p>Without an index:</p><pre>SELECT *<br>FROM employees<br>WHERE last_name = &#39;ALEX&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zp5fBXm8ch2E9_qK-EUUag.png" /></figure><p>The database checks row one by one.</p><p>This is called a <strong>Full Table Scan.</strong></p><p>Time complexity:</p><pre>0(n)</pre><p>The larger the table grows, the slower the query becomes.</p><h3>The Secret Behind Most Database Indexes</h3><h3>B-Trees</h3><p>Most relational database use a structure called a <strong>B-Tree Index.</strong></p><p>Not Binary Tree.</p><p>Not Hash Table.</p><p>A B-Tree.</p><p>The B-Tree combines two idea:</p><ol><li>A search tree</li><li>A doubly linked list</li></ol><p>Together they allow databases to:</p><ul><li>search quickly</li><li>insert quickly</li><li>update quickly</li><li>delete quickly</li></ul><p>without constantly reorganizing the entire structure.</p><h3>The Leaf Nodes</h3><p>At the bottom of a B-Tree are leaf nodes.</p><p>A leaf node contains:</p><pre>Indexed Value<br>+<br>Pointer To Table Row</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EYPYEkgtY6_ObmZMx5Wtzw.png" /></figure><p>The leaf nodes are sorted, and the ordering is what makes searching efficient.</p><h3>The Search Tree</h3><p>Searching millions of rows sequentially would still be slow.</p><p>The database adds another structure, which is a <strong>balanced search tree.</strong></p><p>The B-Tree acts like a navigation system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tWcTOtFJILjs7IxAs-C0XA.png" /></figure><p>To find 57:</p><pre>39<br> ↓<br>83<br> ↓<br>57</pre><p>Instead of examining millions of rows, the database follows a few pointers.</p><p>This operations is incredibly efficient.</p><h4>Why B-Trees Scale So Well.</h4><p>The magic comes from logarithmic growth.</p><p>Instead of:</p><pre>10 rows -&gt; 10 checks<br>100 rows -&gt; 100 checks<br>1000 rows -&gt; 1000 checks</pre><p>A B-Tree grows logarithmically.</p><pre>1,000 rows      -&gt; ~3 levels<br>1,000,000 rows  -&gt; ~4-5 levels<br>100,000,000 rows -&gt; ~5-6 levels</pre><p>This means a database can locate data among millions of records by traversing only a handful of nodes.</p><h3>The Biggest Index Myth</h3><p>Many engineers and developers think:</p><blockquote>If a query uses an index, it must be fast.</blockquote><p>This is false, because an index lookup actually involves three steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uvA60QNq9L7p1gJJcOgptA.png" /></figure><p>Step 1 is cheap, while step 2 and 3 are where things become expensive.</p><h4>Step 1: Traverse the B-Tree</h4><pre>Root<br> ↓<br>Branch<br> ↓<br>Leaf</pre><p>Usually very fast.</p><h4>Step 2: Walk the Leaf Nodes</h4><p>If multiple rows match:</p><pre>WHERE status = &#39;ACTIVE&#39;</pre><p>the database may need to walk many linked leaf nodes.</p><h4>Step 3: Fetch Table Data</h4><p>The index only contains:</p><pre>Indexed Value<br>Pointer</pre><p>The actual row still lives elsewhere.</p><p>The database must visit the table for every matching row.</p><p>This is often the most expensive part.</p><h3>Why Developers Need To Understand Indexes</h3><p>This is the most important lesson.</p><p>Developers know:</p><ul><li>which APIs exist</li><li>which filters users apply</li><li>which reports run daily</li><li>which searches happen most frequently</li></ul><p>DBAs often don’t.</p><p>Indexes should be designed around application access patterns.</p><p>The best index in the world is useless if it doesn’t match the queries being executed.</p><p>A database cannot optimize for usage patterns it doesn’t know.</p><p>Only developers possess that knowledge.</p><h3>Final Thoughts</h3><p>Many engineers spend years learning:</p><ul><li>Django</li><li>Spring Boot</li><li>React</li><li>Kubernetes</li><li>AWS</li></ul><p>yet never learn how databases actually find data.</p><p>Understanding indexes changes how you think about software.</p><p>You begin asking questions like:</p><ul><li>How will this query scale?</li><li>Which columns are filtered most often?</li><li>Is this query selective?</li><li>Will this trigger a full table scan?</li><li>Can this become a covering index?</li></ul><p>And that’s when database performance stops feeling like magic.</p><p>Because ultimately:</p><blockquote>Databases are not slow.</blockquote><blockquote>Searching is slow.</blockquote><blockquote>Indexes are the data structures that make searching fast.</blockquote><h3>Your Responsibility</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IzSqqyAaXwyYTi_6t2Hb4A.png" /></figure><p>Most developers focus on:</p><ul><li>CPUs</li><li>RAM</li><li>SSDs</li></ul><p>The biggest wins usually come from:</p><ul><li>Writing better queries</li><li>Designing better indexes</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e656349a9b21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why AI Might Break Your Database Before It Breaks Your Application.]]></title>
            <link>https://medium.com/@Alex_Murimi/why-ai-might-break-your-database-before-it-breaks-your-application-a6667386cd9a?source=rss-6ff31833c88e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6667386cd9a</guid>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Alex Murimi]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 20:08:45 GMT</pubDate>
            <atom:updated>2026-06-02T20:08:45.537Z</atom:updated>
            <content:encoded><![CDATA[<p>Artificial Intelligence is changing software architecture faster than many engineers expected.</p><p>Most conversations around AI focus on models; GPT, Claude, Gemini, Llama and more models.</p><p>But there is a deeper infrastructure question that matters just as much:</p><blockquote><strong>What happens when AI agents become the main users of our systems?</strong></blockquote><p>Today, most applications are designed for humans. A user logs in, clicks a button, submits a form, views a report and maybe perform a few actions per sessions.</p><p>Humans are slow.</p><p>AI agents are not.</p><p>In a recent conversation at AI+ Expo, Spencer Kimball, CEO of Cockroach Labs, discussed how enterprise systems may soon face a new kind of workload: millions of agents continuously reading, writing, reasoning, and acting on business data.</p><p>That future changes how we should think about databases.</p><h3>1. The Traditional Application Assumption.</h3><p>Most web applications today follow a familliar architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*FjhBT3_7Fr7uYUCOxg3oag.png" /></figure><p>This architecture works well for many systems.</p><p>A human user usually performs actions slowly:</p><p>Login → Search → Create order → View invoice → Download report.</p><p>Even when an application grows, the traffic pattern is usually predictable. You can add caching, read replicas, background jobs, queues and indexing.</p><p>But AI introduces a different traffic pattern.</p><h3>2. AI Agents Change the Shape of Traffic</h3><p>Now imagine one employee does not just use the system directly.</p><p>Instead, that employee has multiple AI agents for them</p><pre>1. Sales Agent <br>2. Support Agent<br>3. Reporting Agent<br>4. Procurement Agent<br>5. Compliance Agent<br>6. Risk Agent</pre><p>The system no longer receives traffic only from humans.</p><p>It receives traffic from humans plus agents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LggNv6j0s8nm7t82alc6FA.png" /></figure><p>This is where the database starts feeling pressure.</p><p>The problem is not only that agents are faster.</p><p>The problem is that agents need constant access to data.</p><p>They need to read context → write decisions → store memory → retrieve history → explain actions.</p><p>Thus the database becomes the memory layer of the AI-powered company.</p><h3>3. why Data Becomes the Real Source of Value</h3><p>AI models are becoming easier to access.</p><p>Many companies can now use similar models through APIs or open-source alternatives.</p><p>But every company has unique data:</p><pre>Customers<br>Transactions<br>Contracts<br>Policies<br>Payments<br>Approval flows<br>Audit logs<br>Support history<br>Procurement records</pre><p>This is the data which makes an AI agent useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g_gG4tGk7LwsosXLsSvrag.png" /></figure><p>Without data, an agent is just a chatbot.</p><p>With the right data, it becomes a business operator.</p><p>This is why databases become critical in the AI era.</p><h3>4. The Problem with Traditional Database Scaling</h3><p>PostreSQL is excellent.</p><p>For many applications, it is still the right choice.</p><p>But traditional database architecture often depends on one primary database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QiB5Bp2mwkrqSG2sQinrRA.png" /></figure><p>This models has limits.</p><p>The primary database can become a bottleneck because most writes must go through it.</p><p>Read replicas help with read traffic, but they do not fully solve:</p><pre>1. Write scaling<br>2. Regional failures<br>3. Failover complexity<br>4. Replication lag<br>5. Multi-region constistency<br>6. High availability during cloud outages<br></pre><p>When ai agents increase both reads and writes, these limits become more serious.</p><h3>5. What Resilient Databases Try to solve:</h3><p>A resilient database is not just a database that has backups.</p><p>A resilient database is designed to keep running even when parts of the system fail.</p><p>For example:</p><pre>1. One node fails<br>2. One region goes offline<br>3. One cloud provider has an outage<br>4. Network communication becomes unstable.</pre><p>Distributed databases try to solve this by spreading data across multiple nodes and regions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UdUqMXJGEmEq0OYf2tUoxg.png" /></figure><p>The goal is simple:</p><p><strong>Failure should be expected, not surprising.</strong></p><p>If one region fails, the system should continue operating.</p><p>That is the kind of thinking behind databases like CockroachBD.</p><h3>6. Agentic Workflows Need Stronger Data Systems</h3><p>Traditional business logic is usually written by developers.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ziXeEZSJ6KdZ4jALQl5Tqw.png" /></figure><p>This is predictable.</p><p>The rules are hardcoded.</p><p>But agentic workflows are different.</p><p>An AI agent may need to reason through the process dynamically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e4X8i2OKdKm50cwU8TSZ5w.png" /></figure><p>This means the database is not just storing final results.</p><p>It is supporting the agent’s reasoning process.</p><p>The system must know:</p><ul><li>What data the agent accessed</li><li>What decision it made</li><li>Why it made that decision</li><li>What action it executed</li><li>Whether the action was allowed</li></ul><p>That leads us to governance.</p><h3>7. Governance Becomes More Important Than Intelligence</h3><p>Enterprises cannot simply give agents full database access.</p><p>That would be dangerous.</p><p>An agent should not be able to read every customer record, modify every payment, or approve every transaction.</p><p>AI systems need controlled access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0LEMJnehElFAOdtvZg4gbQ.png" /></figure><p>For enterprise AI to work safely, databases and platforms need:</p><h4>Auditability</h4><p>Every important action should be traceable.</p><h4>Least-Privilege Access</h4><p>Agents should only access the data they need.</p><h4>Curation</h4><p>Agents should see controlled views of data, not the entire database.</p><h4>Explainability</h4><p>The system should show why an agent made a decision.</p><h4>Cost Control</h4><p>If every agent needs its own isolated compute and database resources, the cost can explode.</p><h3>8. The Million-Database Idea</h3><p>One interesting idea from Cockroach Labs is the possibility of many small databases instead of only a few large ones.</p><p>In the future, an enterprise may want:</p><ul><li>One database per customer</li><li>One database per workspace</li><li>One database per agent</li><li>One database per business process</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NEtBZWqXvBb8cgTClhypIA.png" /></figure><p>At first, this sounds extreme.</p><p>But cloud architecture has moved in this direction before.</p><p>We went from:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZFCrmG8mVtEUUxCKgbcs9Q.png" /></figure><p>The same shift may happen with databases.</p><p>Instead of thinking only about one large shared database, engineers may need to think about elastic, isolated, fractional data systems.</p><h3>9. What This Means for Backend Engineers</h3><p>You do not need to abandon PostgreSQL tomorrow.</p><p>That is not the point.</p><p>The real lesson is that AI will increase the importance of database architecture.</p><p>Backend engineers should start learning:</p><ul><li>Distributed databases</li><li>Replication</li><li>Sharding</li><li>Consensus</li><li>Multi-region architecture</li><li>Event-driven systems</li><li>Audit logs</li><li>Access control</li><li>Observability</li><li>Data governance</li></ul><p>These topics are no longer only for senior infrastructure engineers.</p><p>They are becoming important for everyday backend development.</p><h3>10. A Practical Example: Procurement AI Agents</h3><p>Imagine a procurement platform.</p><p>Today, a user may manually review tenders, suppliers, compliance documents, pricing, and approvals.</p><p>In an AI-native system, multiple agents may help.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNxKI32pH7zf7CSNxiGbjA.png" /></figure><p>Each agent needs data.</p><p>Each agent makes decisions.</p><p>Each decision must be traceable.</p><p>That is why the database becomes the foundation of the system.</p><h3>Final Thoughts</h3><p>The AI era is not only about better models.</p><p>It is also about stronger infrastructure.</p><p>As AI agents become more common, databases will face more pressure from:</p><ul><li>More reads</li><li>More writes</li><li>More automation</li><li>More audit requirements</li><li>More governance rules</li><li>More regional availability expectations</li></ul><p>The companies that succeed will not only have smart AI.</p><p>They will have resilient data systems.</p><p>Because when agents become part of the workforce, databases become the memory, control center, and trust layer of the enterprise.</p><p>And that foundation cannot afford to fail.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6667386cd9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Surviving The Thundering Herd or Cache Stampede]]></title>
            <link>https://medium.com/@Alex_Murimi/surviving-the-thundering-herd-or-cache-stampede-07b394d8aac2?source=rss-6ff31833c88e------2</link>
            <guid isPermaLink="false">https://medium.com/p/07b394d8aac2</guid>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Alex Murimi]]></dc:creator>
            <pubDate>Sat, 30 May 2026 08:04:46 GMT</pubDate>
            <atom:updated>2026-05-30T08:04:46.962Z</atom:updated>
            <content:encoded><![CDATA[<p>For this problem, we are going to do it in imagining for a future disaster.</p><p>It is 11:59:59 PM. Across the globe, millions of screens are locked onto a countdown timer for the most anticipated streaming series finale of the decade.</p><p>At exactly midnight, the UI shifts. The “<strong><em>Coming Soon” </em></strong>button turns into “<strong><em>PLAY”. </em></strong>In a fraction of a millisecond, ten million users click.</p><p>The video doesn’t load. The loading wheel spins endlessely. The origin database melts down. Within seconds, a multi-million dollar infrastructure is entirely offline.</p><p>This is not a scale problem. It is a <strong><em>SYNCHRONIZATION PROBLEM. </em></strong>In distributed systems engineering, it is known as the <strong>Thundering Herd or Cache Stampede.</strong></p><h3>Anotomy of a System Collapse</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7TuFxYN_9S0WfScrLSZ18A.png" /></figure><p>Many engineers confuse high throughput with a Thundering Herd. They are fundamentally different physics.</p><p>High throughput is a busy highway at rush hour; heavy but flowing.</p><p>A thundering herd is every vehicle attempting to occupy the exact same lane at the exact microsecond.</p><blockquote>“System do not typically fail because they lack the raw compute to handle millions of users. They fail because the architecutre inadvertenly weaponizes its own efficiency against itself.”</blockquote><h4>Here is how a synchronized event dismantles a platform.</h4><h4>1. The Cache Cliff (Stampede)</h4><p>To handle massive scale, the platform relies heavily on edge caching.</p><p>The metadata for the finale is cached with a hard expiration exactly at midnight, so the new video URL can populate.</p><p>At 00:00:00 hrs, the cache invalidates, for a split second, it is empty. 10M clients requests hit the edge cache, finds nothing and bypass the cache entirely, slamming directly into the fragile origin database in a single devastiting wave.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y4ud0NIrety1Rwy3HrPgHw.png" /></figure><h4>2. The Self-Inflicted DDOS (Retry Storms)</h4><p>When the database gasps under the sudden load and begins dropping connections, modern clients apps do what they are programmed to do: then try again. Instantly, the initial wave of 10M requests doubles.</p><p>The infrastructure isn’t just failing under organic load, it is actively DDOSing itself through aggressive, synchronized retries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A05eZX77-MbDVrx9Lz_xLQ.png" /></figure><h4>3. The autoscaling Illusion</h4><p>Cloud elasticity is a trailing indicator. Autoscaling groups monitor CPU, memory and queue depth over time (usually minutes).</p><p>A thundering herd is an impluse shock that occurs in milliseconds. By the time the orchestrator realizes it needs to provision more containers, the network pipes are clogged, health checks are failing, and the existing nodes are already dead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*arw663dCHETl5z-fTfA-mQ.png" /></figure><h3>ENGINEERING THE ANTIDOTE</h3><p>You cannot out-scale a Thundering Herd by simply throwing more hardware at it.</p><p>You must architect mechanism that break the synchronization.</p><h4>1. The Single-Flight ( Query Collapsing):</h4><p>When a highly requested cache key expires, do not let thousands of threads rush the database.</p><p>Instead, the application layer traps all incoming requests for that exact resource. It permits exactly one thread to cross the threshold, execute the query, retrieve the data.</p><p>The other 9,999 threads are held in suspension. Once the single worker returns, the payload broadcasts to all waiting requests simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gVsgALzOfC_W-9yn6EkxZg.png" /></figure><h4>2. Temporal Dispersion (Jitter):</h4><p>Never allow timers, token expirations or retry logic to trigger in unison.</p><p>If a system failure disconnects thousands of WebSockets, and they all attempt to reconnect at intervals of 1, 2 and 4 seconds, the system will repeatedly crash.</p><p>You must inject entropy. By adding randomized “Jitter”, eg., reconnecting at 2 seconds + random (-500ms to + 1000ms), you diffuse a connected spike into a manageble rolling wave.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TG9Kq4bIwQEs5w_RTuYLJA.png" /></figure><h4>3. Preemptive Replenishment (XFetch):</h4><p>Relying on a cache miss to trigger a data fetch is dangerous at scale.</p><p>Instead, implement probablistic early expiration. As a cached item nears its time-to-live(TTL) boundary, the system randomly fetch fresh data in the background.</p><p>The cache is repopulated before it ever actually empties, completely eliminiating the cliff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gCATMiawCDAZWrpqcdNdVw.png" /></figure><h4>4. Mutex Guards:</h4><p>For heavy, compute-intensive background jobs (like generating personalized recommendations) use distributed locks such as Redis ```SETNX```</p><p>If the cache drops, the first node to arrive claims the lock and begins the heavy lifting. All the other nodes see the lock is claimed and gracefully fallback to serving slightly stale data until the new computation is ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LfAjUG_tlBF2JlRADLRTmg.png" /></figure><h4><strong>Pattern 5: Ruthless Load Shedding</strong></h4><p>When structural limits are breached, graceful degradation is the only option.</p><p>Instead of letting a core database lock up and take the entire platform down, the edge gateway must immediately start shedding non-critical API calls or routing excess traffic into asynchronous holding queues.</p><p>It is infinitely better to tell 15% of your users “please wait a moment” than to let 100% of the platform go dark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aitGkVSNoTMV8BSXw2oD9w.png" /></figure><h3>The Architectural Takeaway</h3><blockquote>In physics, when soldiers march in perfect unison across a bridge, the synchronized frequency can cause the structure to tear itself apart. The command to prevent this is simple: <em>Break step.</em></blockquote><p>The same applies to distributed systems.</p><p>The Thundering Herd is the digital equivalent of a resonant frequency. The ultimate goal of a senior systems architect isn’t just to build infrastructure that can hold massive weight — it is to design systems that inherently force the traffic to break step.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07b394d8aac2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching System Design Concept]]></title>
            <link>https://medium.com/@Alex_Murimi/caching-system-design-concept-53cfc25db76d?source=rss-6ff31833c88e------2</link>
            <guid isPermaLink="false">https://medium.com/p/53cfc25db76d</guid>
            <dc:creator><![CDATA[Alex Murimi]]></dc:creator>
            <pubDate>Fri, 29 May 2026 16:32:15 GMT</pubDate>
            <atom:updated>2026-05-29T16:32:15.099Z</atom:updated>
            <content:encoded><![CDATA[<p>Caching is a concept that involves storing frequently accessed data in a location that is easily and quickly accessible.</p><p>The primary purpose of caching is to improve the performance and efficiency of a system by reducing the time taken to access this frequently used data.</p><h3>How Does a cache work</h3><p>A web/mobile application stores data in a database. Reading data from a database requires network calls and I/O (Input or Output) operations, which is a time consuming process.</p><p>A cache reduces these network calls to the database, significantly speeding up the system performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eYl_tokGfiiDrHVwgVYOXw.png" /><figcaption>How cache works</figcaption></figure><ol><li><strong>Cache MISS:</strong> When a request is made for the first time, a call must be made to the dabtabase to process the query.</li><li>Before giving the result back to the user, the application saves a copy of the results in a cache.</li><li><strong>Cache HIT: </strong>When a user makes the same request a second time, the application checks the cache first. If the result is there, it is returned directly from the cache.</li><li>The response time for the second request will be lower than the first.</li></ol><h4>Types of Cache</h4><h4><strong>1. Application Server Cache</strong></h4><p>An application server cache resides direclty on the machine running your application code.</p><p>It utilizes the server’s own RAM or sometimes the local disk, e.g. In Django it is oftern achieved using local-memory caching.</p><p>HOW IT WORKS</p><p>When a request hits a specific server node, that node checks it own local memory, because the cache is on the same machine as the application, data retrival is practically instanteous.</p><p><em>The Catch: </em>If you have multiple application servers sitting behing a load balancer, each server maintains its own seperate cache. If server A caches a student record, Server B does not know about it. This can lead to <em>“cache drift” </em>if a user’s request bounce between different servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8fdDAnZ5vqcKSsC5wR0XQQ.png" /></figure><h4>2. Distributed Cache</h4><p>A distributed cache solves the “<strong><em>cache drift”</em></strong> problem of local caching by moving the cache out of the individual application servers and into its own independent cluster of servers.</p><p>Redis and Memcached are the industry standard for this.</p><p>HOW IT WORKS</p><p>The cache is split across multiple nodes, (using consistent hashing to determine which node holds which key).</p><p>Every application server points to this single cache cluster. No matter which application server handles a user’s request, it will always read from and write to the same shared cache state.</p><p><em>The Catch: </em>Because the cache is no longer on the same machine as the application, every cache hit requires a network call. Thus when it is faster than a database query, it is slightly slwoer than a local application server cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0NdwXIhjcfP3x5qemqqPw.png" /><figcaption>Distributed cache</figcaption></figure><h4>3. Global Cache</h4><p>A Global cache is a single, unified cache space. Instead of a distributed architecture where keys are hashed and split across many independent cache nodes, a global cache acts an obsolute single source of truth sitting directly between the application layer and the data store.</p><p>HOW IT WORKS</p><p>Every single application node routes its cache requests to this one monolithic cache.</p><p>In some architectures, the global cache actively manages itself, if it does experience a cache miss, the cache itself fetches the data from the database, rather than the application fetching it and writting it back.</p><p><em>The Catch: </em>A pure global cache can become a single point of failure and a massive network bottleneck. If your application’s traffic relies on one cache server, and that server goes down or gets overwhelmed, your system crashes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JV_TbpyQYz9VE2I9XazpLA.png" /></figure><h4>4. CDN (Content Delivery Network)</h4><p>A CDN is a specialized type of cache deployed at the “edge” of the network, meaning it is geographically placed as close to the end-user as possible.</p><p>HOW IT WORKS</p><p>If your primary servers are in Nairabi, a user in Tokyo will experience significant latency just waiting for the data to travel across the globe.</p><p>A CDN solves this by copying your static assets(images, Javascript, CSS and sometimes entire cached HTML/API responses) onto proxy serves located in Tokyo, London, New York, etc.</p><p><em>The Catch: </em>CDNs are brilliant for static files but very difficult to use for dynamic, heavily personalized API data. Cache Invalidation on a CDN can also take time, meaning users might temporarily see stale data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZRJ86ZYl19ja6BNpWziQw.png" /></figure><h3>Real-World Applications of Caching</h3><p>To understand caching in practice, here is how top-tier systems utilize different caching layers:</p><h3>1. Web Page Caching (E-commerce)</h3><p>During events like Black Friday, e-commerce landing pages receive millions of hits per minute.</p><p>Instead of generating the HTML and querying the database for product listings every single time, the entire HTML page is cached.</p><p>The web server instantly hands the pre-built page to the user.</p><h3>2. Database Caching (Gaming Leaderboards)</h3><p>Imagine a global gaming leaderboard. Calculating the “Top 100 Players” requires sorting millions of rows, which is a heavy database query.</p><p>Instead of running this query for every player looking at the leaderboard, the system runs it once every 5 minutes, caches the result in Redis, and serves that cached list to everyone.</p><h3>3. Session Caching (Social Media)</h3><p>When you log into an app like X (Twitter), you are authenticated.</p><p>In a distributed system with hundreds of backend servers, storing your login “session” on just one server means you’d get logged out if your next request hit a different server. By caching user sessions in a centralized Redis cluster, <em>any</em> server can instantly verify you are logged in.</p><h3>4. API Response Caching (Weather Apps)</h3><p>Weather APIs are queried constantly, but the actual weather data only updates periodically.</p><p>An API gateway can cache the JSON response for the endpoint /weather/nairobi for 10 minutes. If 10,000 people open their weather app in that 10-minute window, the backend database is only queried exactly <em>once</em>.</p><p>This really rounds out the educational value of the post. It gives developers both the theory and the practical headaches they need to watch out for.</p><h3>Cache Invalidation Strategies</h3><p>For systems that use caching to improve performance, cache invalidation is absolutely essential. While data is temporarily kept for faster access, that cached version goes out of date (becomes “stale”) the moment the original data in the database changes.</p><p>To guarantee users obtain the most recent information, invalidation techniques ensure out-of-date records are either updated or deleted. Without proper invalidation, you risk serving users obsolete, confusing, or downright incorrect content.</p><h3>1. Time-Based Expiration (TTL — Time to Live)</h3><p>The simplest approach. Every piece of data put into the cache is given a countdown timer. Once the timer reaches zero, the data is automatically deleted. The next time a user requests that data, it triggers a cache miss, and fresh data is fetched from the database.</p><ul><li><strong>Best for:</strong> Data that changes predictably or where slight delays in consistency are acceptable (e.g., daily weather forecasts, stock market closing prices).</li></ul><h3>2. Event-Driven Invalidation</h3><p>Instead of waiting for a timer to expire, the cache is actively purged or updated the exact moment the underlying database changes. This is often handled through application code or database triggers.</p><ul><li><strong>Best for:</strong> Highly dynamic data where users must see changes immediately (e.g., a user updating their profile picture, changing an account password, or transferring money).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvwCNcFzgbc_W0Se6pawaQ.png" /><figcaption>Types of cache</figcaption></figure><h3>Pros and Cons of Caching</h3><p>Adding a cache is not a magic bullet, it is an engineering tradeoff.</p><p>Here is what you gain and what you sacrifice.</p><h3>Pros of Caching</h3><ul><li><strong>Improved Performance:</strong> Caches store data in RAM, meaning retrieval times drop from milliseconds (database I/O) to microseconds.</li><li><strong>Reduced Database Load:</strong> By absorbing repetitive read requests, the cache prevents your primary database from being overwhelmed, especially during sudden traffic spikes.</li><li><strong>Cost Savings:</strong> Scaling a relational database to handle massive read traffic is incredibly expensive. Provisioning a smaller database alongside a highly efficient cache (like Redis) is much more cost-effective.</li></ul><h3>Cons of Caching</h3><ul><li><strong>Data Consistency Challenges:</strong> You must accept the risk of “stale data.” If your invalidation logic fails, users might see old prices, outdated inventory, or old profile data.</li><li><strong>Cache Eviction Complexities:</strong> Memory (RAM) is finite and expensive. When your cache fills up, it has to delete old data to make room for new data. Choosing the right algorithm for this — like <strong>LRU</strong> (Least Recently Used) or <strong>LFU</strong> (Least Frequently Used) — requires careful tuning.</li><li><strong>Additional Architectural Complexity:</strong> Introducing a cache means adding another moving part to your infrastructure. You now have to monitor, maintain, and secure a Redis/Memcached cluster alongside your main database.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53cfc25db76d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Boost Your Authentication with Django REST OAuth2]]></title>
            <link>https://medium.com/@Alex_Murimi/how-to-boost-your-authentication-with-django-rest-oauth2-f68c3bd38c14?source=rss-6ff31833c88e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f68c3bd38c14</guid>
            <dc:creator><![CDATA[Alex Murimi]]></dc:creator>
            <pubDate>Wed, 17 Apr 2024 22:00:31 GMT</pubDate>
            <atom:updated>2024-04-17T22:00:31.490Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jxu3bPnKHm_NjhidsOblYQ.png" /></figure><p>It is clear that authentication is the process or action of verifying the identity of a user or process.</p><p>Web applications needs strong authentication to keep out unwanted visitors.</p><p>Ever signed into a website using your Google, Facebook, linkedin or your favourite account? Ever wonder how it knows its really you? Okay I get it, and that&#39;s where OAuth and OAuth2 comes into place. It is like a trusted friend that vouches for you. OAuth helps websites and apps verify your identity securely and quickly.</p><p>In this article, we’ll explore why good authentication matters for web application, and how to use OAuth2 which makes the process smooth and safe.</p><p>So let’s dive in and learn how to boost application authentication using OAuth.</p><h4>Understanding OAuth2</h4><p>Let’s start with some good news, <strong>OAuth2 has emerged as the industry standard for social and third-party authentication</strong>. Should we mention a few; <em>Google, Facebook, LinkedIn</em> etc.</p><p>Before OAuh2, if you wanted to use your Facebook account to sign in to a different website, you had to give that website your Facebook password. That is not safe at all! OAuth2 fixes this by letting the website ask Facebook for permission to access your account without ever seeing your password.</p><p>OAuth2 thus makes it easier and much safer to access to your favourite accounts to access different services without worrying about sharing your passwords everywhere.</p><h4>OAuth2 Flow</h4><p>We will need to:</p><ol><li><strong>Register an App:</strong> Before your app can let people sign in with other services like Google or Facebook, you have to tell those services about your app. You provide them with a special web address called <strong>callback URI </strong>where they can send information to your app.</li><li><strong>Get Secret Codes: </strong>When you tell these services about your app, they will give you two secret codes: <strong>a client key </strong>and <strong>a client secret. </strong>These are like secret passwords that your app will use to talk to the sign-in service.</li><li><strong>Use The Codes: </strong>When someone tries to sign in with your app, your app sends these secret codes along with the sign-in request. The sign-in service checks these codes to make sure its really your app asking for the sign-on.</li><li><strong>Tokens: </strong>After everything checks out, the sign-in service gives your app a special code called <strong>token. </strong>Your app can use this token to prove to the sign-in service that its already been verified, so it doesn’t have to go through all the secret code stuff again.</li></ol><p>Once everything set’s up, your app gets a special pass, token, to skip some of the security steps in the future.</p><h4>Setting up Django REST Framework with OAuth2</h4><p>Now, let’s make our Django backend work smoothly with OAuth2 authentication.</p><p><strong>Step 1: Installing Necessary Packages:</strong></p><p>First, install django-oauth-toolkit package using pip:</p><pre>pip install django-oauth-toolkit</pre><p><strong>Step 2: Configuring Django Settings:</strong></p><p>In your Django project’s settings.py file add &#39;oauth2_provider&#39; to the INSTALLED_APPS list</p><pre>INSTALLED_APPS = [<br>    # other apps ...<br>    &#39;oauth2_provider&#39;<br>]</pre><p>Then add &#39;oauth2_provider.middleware.OAuth2TokenMiddleware&#39; to the MIDDLEWARE list:</p><pre>MIDDLEWARE = [<br>    # other middleware...<br>    &#39;oauth2_provider.middleware.OAuth2TokenMiddleware&#39;,<br>]</pre><p>Next, configure Django REST Framework to accept OAuth2 authentication by adding &#39;rest_framework.authentication.OAuth2Authentication&#39; to the DEFAULT_AUTHENTICATION_CLASSES setting:</p><pre>REST_FRAMEWORK = {<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: (<br>        &#39;rest_framework.authentication.OAuth2Authentication&#39;,<br>        # other authentication classes...<br>    ),<br>}</pre><p><strong>Step 3: Configuring OAuth2 Providers:</strong></p><p>Configuration for Google and Facebook OAuth2 providers and how to obtain the client ID and client secret for each.</p><p><strong>A : Obtain OAuth2 Credentials:</strong></p><p>For Google:</p><ol><li>Go to the <a href="https://console.cloud.google.com/">Google Cloud Console</a>.</li><li>Create a new project or select an existing one.</li><li>Navigate to the “Credentials” page.</li><li>Click on “Create Credentials” and select “OAuth client ID”.</li><li>Choose “Web application” as the application type.</li><li>Add your website’s URL as an authorized redirect URI.</li><li>After creating the OAuth client, you’ll get the client ID and client secret.</li></ol><p>For Facebook:</p><ol><li>Go to the <a href="https://developers.facebook.com/">Facebook Developers</a> website.</li><li>Create a new app or select an existing one.</li><li>Navigate to the “Settings” page of your app.</li><li>Under “Basic Settings”, you’ll find your App ID and App Secret.</li></ol><p><strong>B: Configure OAuth2 Providers in Django Settings:</strong></p><p>In your Django project’s settings.py file, add configuration settings for Google and Facebook OAuth2 providers:</p><pre><br># Google OAuth2 Provider Configuration<br>OAUTH2_PROVIDER = {<br>    &#39;SCOPES&#39;: {&#39;read&#39;, &#39;write&#39;, &#39;userinfo&#39;},<br>    &#39;CLIENT_ID&#39;: &#39;your-google-client-id&#39;,<br>    &#39;CLIENT_SECRET&#39;: &#39;your-google-client-secret&#39;,<br>    &#39;GOOGLE_EXTRA_DATA&#39;: [(&#39;id&#39;, &#39;id&#39;)],<br>}<br><br># Facebook OAuth2 Provider Configuration<br>OAUTH2_PROVIDER = {<br>    &#39;SCOPES&#39;: {&#39;read&#39;, &#39;write&#39;, &#39;userinfo&#39;},<br>    &#39;CLIENT_ID&#39;: &#39;your-facebook-app-id&#39;,<br>    &#39;CLIENT_SECRET&#39;: &#39;your-facebook-app-secret&#39;,<br>    &#39;FACEBOOK_EXTRA_DATA&#39;: [(&#39;id&#39;, &#39;id&#39;)],<br>}</pre><p>NOTE:</p><p>Replace &#39;your-google-client-id&#39; and &#39;your-google-client-secret&#39; with the client ID and client secret obtained from the Google Cloud Console.</p><p>Replace &#39;your-facebook-app-id&#39; and &#39;your-facebook-app-secret&#39; with the App ID and App Secret obtained from the Facebook Developers website.</p><p><strong>C: Update Django URLs:</strong></p><p>In your Django project’s urls.py file, include URL patterns to handle authentication with Google and Facebook OAuth2 providers:</p><pre>from django.urls import path, include<br><br>urlpatterns = [<br>    # other URL patterns...<br>    path(&#39;auth/&#39;, include(&#39;oauth2_provider.urls&#39;, namespace=&#39;oauth2_provider&#39;)),<br>]</pre><p><strong>D: Applying Changes</strong></p><p>Apply the changes to your Django project:</p><pre>python manage.py migrate</pre><p>Now our project is configured to work with OAuth2.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f68c3bd38c14" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>