<?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 Basith on Medium]]></title>
        <description><![CDATA[Stories by Basith on Medium]]></description>
        <link>https://medium.com/@muhammedbasith?source=rss-a3fffc06f107------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KS7l2bmGWqZZey5SAT8klA.png</url>
            <title>Stories by Basith on Medium</title>
            <link>https://medium.com/@muhammedbasith?source=rss-a3fffc06f107------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 10:45:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muhammedbasith/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How Senior Engineers Actually Approach System Design (From First Principles)]]></title>
            <link>https://muhammedbasith.medium.com/how-senior-engineers-actually-approach-system-design-from-first-principles-343bd7f41221?source=rss-a3fffc06f107------2</link>
            <guid isPermaLink="false">https://medium.com/p/343bd7f41221</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Basith]]></dc:creator>
            <pubDate>Sat, 02 May 2026 15:09:57 GMT</pubDate>
            <atom:updated>2026-05-03T08:01:30.519Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*In0psEMz-ShEGHKBp6AwIw.png" /></figure><p>I want to start with something almost embarrassingly simple.</p><p>Imagine you write a to-do list app. You, one laptop, one file on your hard drive. When someone opens the app, it reads the file. When they add a task, it writes to the file. Done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sQ54DiG5q7T87qhyvznMcg.png" /></figure><p>This is a system. A real one. It has inputs, a process, and an output. It stores state (your tasks). It responds to requests. If you were the only user on earth, this design would be completely fine. You would never need to read another article like this one.</p><p>But you’re not the only user. And that’s where the interesting problems start.</p><p>Almost every concept in system design, from load balancers to distributed databases to message queues, exists because of one unavoidable truth: <strong>reality doesn’t cooperate</strong>.</p><p>Machines fail. Networks go down. Users multiply. Data grows faster than you expect. The gap between “it works on my laptop” and “it works for a million people” is not just a bigger version of the same problem. It’s a completely different set of problems.</p><p>This post is about learning to see those problems before they happen. Essentially, a dump of how i approach designing complex systems. About developing an intuition from first principles for why systems are designed the way they are, rather than memorizing patterns. Let’s build that intuition from scratch.</p><h3>The very first thing: what even is a “system”?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eTHq6bUmV0ArCqVDNZCOiQ.png" /></figure><p>When engineers say “system,” they usually mean a collection of components that work together to do something. Your to-do app is a system. Gmail is a system. Your home’s electrical wiring is a system.</p><p>What makes something a system worth “designing” is that it has at least these three things:</p><p><strong>State -</strong> something it needs to remember. For your to-do app, that’s your tasks. For Gmail, that’s your emails. State is the hard part. Anything that just computes and throws away the result (like a calculator) is almost trivially easy to scale. State sticks around, and that creates problems.</p><p><strong>Requests - </strong>something that asks it to do work. A user clicking a button. An API call. A cron job that runs at midnight. These arrive unpredictably, in bursts, from multiple places at once.</p><p><strong>Constraints -</strong> limited time, limited money, limited reliability of the underlying hardware. Every design decision is really a decision about which constraint you’re willing to sacrifice and which one you’re protecting.</p><p>The reason system design is hard is not the technology. The technology is actually pretty well understood at this point. The hard part is reasoning clearly about constraints and trade-offs under uncertainty.</p><h3>The first real problem: more users than you expected</h3><p>Back to your to-do app. It works great on your laptop. Now imagine 1,000 people are using it.</p><p>Your laptop is one machine. One processor, one disk, one network card. It can handle some number of requests per second before it starts to slow down and eventually fall over.</p><p>Now for those who wonder why, the reason is simpler than it sounds. Every request asks your machine to do real physical work. The processor has to run instructions. The disk has to spin and find data. The network card has to send and receive bytes. Each of these components can only do so much per second, not because of bad software, but because of physics. A processor has a fixed number of cores doing a fixed number of operations per clock cycle. A disk has a mechanical arm that moves to find data, and that arm can only move so fast. A network card has a maximum bandwidth, a ceiling on how many bytes it can push through the wire per second. When requests arrive slowly, the machine handles them comfortably. When they arrive faster than the machine can process them, work starts piling up, waiting its turn. The pile grows. Responses get slower. Eventually, the pile is so large that the machine is spending more time managing the backlog than actually doing work, and the whole thing grinds to a halt. Anyways, this number, the maximum throughput of your system, is called <strong>capacity</strong>. Capacity is the amount of work your system can handle in a given period before something bad happens.</p><p><em>Now, What is throughput?</em> Throughput is simply how much work gets done per unit of time. If your server can handle 500 requests per second, that’s its throughput. Think of a highway: the throughput is how many cars pass a certain point per hour. Widen the highway, you get more throughput.</p><p>When you hit capacity, the machine doesn’t immediately give up. The operating system holds incoming requests in a small waiting area while the server catches up. But that waiting area has limits too. Once it’s full, new requests start getting turned away entirely. This is queuing.</p><p>Queuing means: “I can’t handle this right now, so I’ll wait.”</p><p><em>What is a queue?</em> A queue is a line. First in, first out. Like a supermarket checkout. Your server is the cashier. When requests come in faster than the cashier can process them, the line grows. If the line grows without bound, people waiting at the back start experiencing huge delays, and eventually the system falls apart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6s0HTDfm3cvPI741h1d3Rg.png" /></figure><p>When requests pile up too fast, users experience <strong>latency</strong>. Latency is the time between “I asked for something” and “I got it back.” The reason latency matters so much is that humans have very little tolerance for waiting. Research by Google found that users start abandoning pages that take longer than 3 seconds to load (and, nowadays, probably less than that). That’s not a lot of time.</p><p>So, you have more users than your laptop can handle. What do you do?</p><h3>Two paths: scale up, or scale out</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NsvaeG5o0BvV2Qaqdsc0lg.png" /></figure><p><strong>Vertical scaling</strong> means making your one machine bigger. More CPUs, more RAM, a faster disk. If your laptop can’t handle the load, buy a bigger server.</p><p>This is the easiest solution, and you should always consider it first. The code doesn’t change. No new complexity. You just pay more for better hardware.</p><p>But vertical scaling has a ceiling. The biggest server money can buy is still finite. At some point, you genuinely cannot buy your way out of the problem with a single machine. This ceiling exists partly because of the physics of heat dissipation (more power in a single chip means more heat, and heat is hard to remove), and partly because a single machine is a single point of failure.</p><p><em>What is a single point of failure (spof)?</em> A single point of failure is any component in your system whose failure would bring down the entire system. If your whole app runs on one server and that server catches fire (this has happened), your app is down. There’s no backup, no fallback, nothing. Zero availability until the hardware is fixed.</p><p><strong>Horizontal scaling</strong> means running multiple machines and distributing the work across them. Instead of one big server, you have ten smaller servers. Each one handles a fraction of the load.</p><p>This solves the ceiling problem. You can keep adding machines, at least in theory. And it solves the single point of failure problem, because if one machine dies, the others keep working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JdHIsCMTklNXVLNW9ROPvQ.png" /></figure><p>But horizontal scaling introduces a new class of problems. Problems that are, frankly, much harder than the ones it solves.</p><h3>The network enters the picture</h3><p>When you have one machine, the components talk to each other through memory. Memory access takes nanoseconds. There is almost zero chance that a memory read will fail in the middle. Memory doesn’t randomly drop your request and pretend it never happened.</p><p>When you have multiple machines, the components have to talk to each other over a <strong>network</strong>. And the network is a completely different beast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqcEJkSz3ykeSvo6w_nbNA.png" /></figure><p>Networks are slow compared to memory. A network hop within the same datacenter might take around 0.5 milliseconds. That sounds tiny. But a memory access takes around 100 nanoseconds. So a network round-trip is about 5,000 times slower than a memory access.</p><p><em>What is a network hop?</em> A network hop is one leg of a journey a data packet takes as it moves from one machine to another. Each time a packet passes through a routing device (like a switch or a router), that’s a hop. More hops mean more latency.</p><p>Networks also fail. A cable gets cut. A switch overheats. A network partition happens, where two groups of machines can’t talk to each other even though both groups are still running fine internally.</p><p><em>What is a network partition?</em> Imagine your ten servers are split into two groups by a network failure. The servers in group A can talk to each other but not to group B, and vice versa. Neither group has crashed. They’re both healthy. But they can’t communicate. This is a partition. It’s one of the most interesting failure modes in distributed systems because it doesn’t look like a failure from the outside — the machines are running — but the system is broken in a subtle way.</p><p>And networks are unpredictable. A request might succeed in 2ms, or it might take 200ms for no obvious reason, or it might time out entirely. You genuinely cannot know in advance.</p><p>This is the fundamental challenge of distributed systems.</p><p>But, hold on, <strong>What is a distributed system? </strong>A distributed system is any system that runs across multiple computers connected by a network. Your ten-server setup is a distributed system. The internet itself is a distributed system. Distributed systems allow scale and redundancy that a single machine can’t provide, but they trade that benefit for the complexity that comes with unreliable networks. Anyways, the moment you go from one machine to many, you have introduced an unreliable communication channel that is orders of magnitude slower and far less predictable than what you had before.</p><p>The computer scientist Leslie Lamport has a quote that I keep coming back to: “A distributed system is one in which the failure of a computer you didn’t even know existed can render your own computer unusable.” This sounds extreme. It’s not. It’s just the reality.</p><h3>The problem of state, again</h3><p>Okay. So you have multiple servers. A user makes a request, and it goes to one of your servers. Great.</p><p>But here’s the problem. If that request needs to read or write state, and your state is on one specific server, then every request from that user has to go to that specific server. If it goes to a different server, that server won’t have the right data.</p><p>This is called <strong>stickiness</strong> or <strong>session affinity</strong>. And it’s a nightmare for horizontal scaling, because you lose one of the main benefits: the ability to send any request to any server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ahDp7XH-SO3UhDjH04gFog.png" /></figure><p>The cleaner solution is to make your servers <strong>stateless</strong>.</p><p><em>What does stateless mean?</em> A stateless server doesn’t remember anything about previous requests. Every request contains all the information needed to handle it. The server processes the request, returns a response, and forgets everything. Like a calculator that doesn’t care who pressed the buttons last time.</p><p>If your servers are stateless, any request can go to any server, and you get full flexibility in how you distribute the load.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xsq3-LInqXRzRny0n2LZOg.png" /></figure><p>But your application still needs state. You can’t just not have user data. Where does it go?</p><p>It goes to a shared place that all your servers can access: the <strong>database</strong>.</p><h3>The database: the most important and most misunderstood component</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QrABMAAVmpmgxjXaDbCEBA.png" /></figure><p>The database is where your state lives. All your servers are stateless; they read from and write to the database to do their work.</p><p>This is a good design. But it creates a new bottleneck. Now instead of one server being overloaded, you have one database being hit by ten servers at once.</p><p>Databases are good at handling many requests. That’s their whole job. But they have limits too, and the limits look different depending on what you’re asking the database to do.</p><p>There are two types of operations in a database:</p><p><strong>Reads</strong>: “Give me the user with ID 12345.” The database finds the data and returns it.</p><p><strong>Writes</strong>: “Update the email address for user 12345.” The database finds the record and changes it.</p><p>In most applications, reads massively outnumber writes. Think about Twitter: millions of people reading tweets for every person writing a new one. This asymmetry matters a lot for design.</p><p>Reads are relatively easy to scale. You can have multiple copies of the database and direct read requests to any of them.</p><p>Writes are hard to scale. When someone writes data, you need all copies of the database to agree on what the correct data is. Getting multiple machines to agree on something is one of the core hard problems in distributed systems.</p><p><em>What is a replica?</em> A replica is a copy of a database. You might have one main database (called the primary or leader) that handles all writes, and several replicas (called secondaries or followers) that handle reads. The replicas get updated whenever the primary receives a write. This is called <strong>replication</strong>.</p><p><em>What is replication lag?</em> When a write happens on the primary, it takes a small amount of time for that write to propagate to the replicas. During that window, a user who reads from a replica might see slightly old data. This delay is called replication lag. Usually it’s milliseconds. In overloaded systems or across geographic regions, it can be seconds. Whether this matters depends entirely on what your application does. A social media feed can tolerate showing a post that’s a few seconds delayed. A bank balance probably cannot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4dy-6eP6F0ko7nQWN1c8Q.png" /></figure><p>This brings us to one of the most important trade-offs in all of system design.</p><h3>Consistency vs. Availability: the trade-off that underlies almost everything</h3><p>Imagine you’re running a bank. A customer has $100. They withdraw $80 from an ATM in New York at exactly the same moment their spouse withdraws $80 from an ATM in London.</p><p>Your database is distributed across both locations. The network between them just went down.</p><p>What do you do?</p><p>Option A: Reject one of the withdrawals. Tell one of them “sorry, can’t process this right now.” The account never goes negative. Your data stays correct. But your service is down from the user’s perspective.</p><p>Option B: Allow both withdrawals. Both people get their money. Your service stays up. But now the account is at -$60. Your data is wrong.</p><p>There is no Option C where both transactions succeed AND the account balance is correct AND the service stays up. That option doesn’t exist. The network is down. You are forced to choose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O0hFRbCjz_3YzzCjt0BvtA.png" /></figure><p>This is the heart of the <strong>CAP theorem</strong>, one of the most important results in distributed systems, proved by computer scientist Eric Brewer in 2000 (and formally proved by Gilbert and Lynch in 2002).</p><p><em>What is the CAP theorem?</em> CAP stands for Consistency, Availability, and Partition tolerance.</p><ul><li><strong>Consistency</strong> means that every read from your system returns the most recent write, or an error. Every user sees the same data. No stale reads, no contradictions.</li><li><strong>Availability</strong> means that every request gets a response (not an error). The system is always up and responding, even if the response might be slightly stale.</li><li><strong>Partition tolerance</strong> means the system keeps working even when parts of the network fail and machines can’t communicate.</li></ul><p>The CAP theorem says: in a distributed system, you can only guarantee two of these three at the same time.</p><p>And here’s the thing about partition tolerance: you don’t really get to choose whether to have it. Networks partition. It’s not a matter of if, it’s when. So in practice, every distributed system must be partition tolerant, which means you’re really choosing between Consistency and Availability when a partition happens.</p><p>Most real systems don’t make a binary choice. They slide on a spectrum, choosing consistency for some operations and availability for others. Your bank’s balance calculation needs consistency. Your social media feed can tolerate slight inconsistency.</p><p>This spectrum is sometimes called <strong>eventual consistency</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e1wdx4mBqdwOj9fXCadujg.png" /></figure><p><em>What is eventual consistency?</em> Eventual consistency means that if you stop writing to a distributed system and wait long enough, all the replicas will converge to the same value. They won’t agree immediately. But eventually they will. During the window where they disagree, different users might see different data. For many applications, this is completely fine. Your Twitter likes counter might be off by a few for a second. Nobody is harmed. For a financial transaction, it’s not fine.</p><h3>The cache: making things fast by lying a little</h3><p>Even with a well-tuned database, reads can be slow. Every read requires going to disk (or across the network to another machine), finding the data, and returning it. If the same data is read thousands of times per second, you’re doing the same work thousands of times.</p><p>A <strong>cache</strong> fixes this by keeping frequently read data in memory, close to where it’s needed.</p><p><em>What is a cache?</em> A cache is a temporary storage layer that holds copies of data for fast access. When a request comes in, you check the cache first. If the data is there (a <strong>cache hit</strong>), return it immediately, no database trip needed. If it’s not there (a <strong>cache miss</strong>), go to the database, get it, store it in the cache for next time, and return it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQVCnfm4sCmXgc8Ca9nJIA.png" /></figure><p>Memory is much faster than disk. Reading from memory takes nanoseconds. Reading from a spinning disk takes milliseconds. That’s a difference of four to five orders of magnitude. For frequently accessed data, a cache can reduce your database load by 90% or more.</p><p><em>What is a cache hit?</em> A cache hit is when the data you’re looking for is already in the cache. You save the database trip entirely.</p><p><em>What is a cache miss?</em> A cache miss is when the data isn’t in the cache, so you have to go to the database. Cache misses are inevitable. They happen when data is accessed for the first time, or after data has been evicted from the cache to make room for other data, or after the cache has been cleared.</p><p>Caches sound like magic. They’re not, because of one problem: <strong>cache invalidation</strong>.</p><p><em>What is cache invalidation?</em> If the underlying data changes in the database, the cache still has the old version. Anyone who reads from the cache now gets stale data. Cache invalidation is the problem of figuring out when to update or remove data from the cache so that it stays in sync with the database.</p><p>Phil Karlton (a programmer at Netscape in the 90s) famously said: “There are only two hard things in computer science: cache invalidation and naming things.” It’s become a cliche, but it’s also true. Cache invalidation is genuinely hard because you need to know when to invalidate, and in a distributed system with multiple caches and multiple writers, “when” is not obvious at all.</p><p>There are several strategies:</p><p><strong>TTL (time-to-live)</strong>: Every cached item has an expiration time. After the time passes, the item is evicted. Next time it’s requested, it gets fetched fresh from the database. Simple. But your data might be stale right up until the TTL expires.</p><p><strong>Write-through</strong>: When a write happens to the database, you also update the cache at the same time. The cache always has fresh data. But writes are slower because they have to update two places.</p><p><strong>Cache-aside</strong>: The application code handles cache explicitly. On a miss, the app fetches from the database and populates the cache. On a write, the app updates the database and invalidates (deletes) the relevant cache entries. The next read will be a miss, which is fine because it’ll fetch the latest data from the database.</p><p>Which strategy you use depends on how much staleness you can tolerate and how write-heavy your workload is.</p><h3>Load balancing</h3><p>You have multiple servers. Requests come in. Which server handles each request?</p><p>This is what a <strong>load balancer</strong> does. It sits in front of your servers and distributes incoming requests across them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*lp5auo9e5iGw2UKGW0O-PQ.png" /></figure><p><em>What is a load balancer?</em> A load balancer is a component that receives incoming requests and forwards them to one of many backend servers. It also monitors the health of those servers and stops sending traffic to any that are down.</p><p>The simplest load balancing strategy is <strong>round-robin</strong>: server 1 gets request 1, server 2 gets request 2, server 3 gets request 3, then back to server 1. Equal distribution.</p><p>But round-robin is naive. Some requests take a millisecond. Some take a minute (maybe you’re generating a report). With round-robin, a slow request on server 1 doesn’t stop new requests from being sent to server 1. Server 1 might be drowning while servers 2 and 3 are idle.</p><p>Smarter strategies look at server load. <strong>Least connections</strong> sends each new request to whichever server has the fewest active connections. That’s a better proxy for “which server has capacity right now.”</p><p>There’s also <strong>weighted round-robin</strong>, where some servers get more traffic than others based on their capacity. Useful when your servers aren’t all identical.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*27vfuQYlak3IEymaGpqSrA.png" /></figure><p>Load balancers also handle <strong>health checks</strong>. Every few seconds, the load balancer pings each server. If a server doesn’t respond, the load balancer stops sending it traffic. This is basic resilience: when a server dies, traffic automatically flows to the healthy ones without any human intervention.</p><h3>The database doesn’t scale like servers do</h3><p>Here’s something that trips people up. Adding more servers to your application tier is relatively easy. But adding more databases doesn’t work the same way, because of the write problem.</p><p>If you add a second database and both databases accept writes, they might get different data. User A’s write might go to database 1. User B’s conflicting write might go to database 2. Now the databases disagree. Which one is right?</p><p>Getting multiple databases to agree on every write is possible, but it requires coordination. Every write has to be confirmed by a majority of the databases before it’s considered committed. This is called <strong>consensus</strong>, and there are well-known algorithms for it (Paxos, Raft). But consensus is slow, because it requires multiple round trips over the network before a write can complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U5O-qy_XI9Gw4TS_Xeb45g.png" /></figure><p><em>What is consensus?</em> Consensus is when a group of machines has to agree on a value. In distributed databases, consensus ensures that a write is durable (won’t be lost) and correct (all nodes agree it happened) before you tell the client “your write succeeded.” The price is latency: you’re waiting for multiple machines to confirm before responding.</p><p>For most applications, the solution to database scaling is more nuanced than just “add more databases”:</p><p><strong>Read replicas</strong>: One primary handles writes. Multiple replicas handle reads. Works well when reads dominate, which they usually do.</p><p><strong>Sharding</strong>: Split your data across multiple databases based on some key. All users with IDs 1–1000000 go to database 1. Users with IDs 1000001–2000000 go to database 2. Now writes are distributed too. But cross-shard queries (give me all users who meet some condition that spans shards) become very expensive.</p><p><em>What is sharding?</em> Sharding is horizontally partitioning your data. Instead of one database with all your data, you have multiple databases (shards), each holding a subset. The key you use to decide which shard a record goes to is called the <strong>shard key</strong>. Choosing a good shard key is important: if you choose poorly, some shards get much more traffic than others (called a <strong>hot shard</strong>), and you haven’t actually solved the problem.</p><h3>Message queues: decoupling for reliability</h3><p>So far, the systems we’ve described are mostly synchronous. A user makes a request. The server handles it. The server responds. The user waits for the whole thing to finish.</p><p>But some work takes a long time, and you don’t want the user to wait. Some work doesn’t need to happen immediately. Some work needs to happen even if the server that received the request crashes.</p><p>This is where <strong>message queues</strong> come in.</p><p><em>What is a message queue?</em> A message queue is a buffer that stores messages (work to be done) between the component that creates the work and the component that does the work. The producer puts a message into the queue. The consumer reads from the queue and does the work. The producer and consumer don’t need to be running at the same time. The producer doesn’t need to wait for the work to finish.</p><p>Think of it like a restaurant. The waiter (producer) takes your order and puts a ticket on the kitchen pass. The cook (consumer) picks up the ticket and makes the food. The waiter doesn’t stand next to the cook watching every dish get made. They go take more orders.</p><p>This decoupling has several benefits:</p><p><strong>Resilience</strong>: If a consumer crashes, the message stays in the queue. When a new consumer comes up, it picks up the message and processes it. Nothing is lost.</p><p><strong>Load smoothing</strong>: If you get a sudden burst of requests (say, a spike after a product launch), the queue absorbs the burst. The consumers process at their own pace. The work will take longer to complete, but nothing crashes from sudden overload.</p><p><strong>Retry logic</strong>: If a consumer fails to process a message, the message goes back into the queue and can be retried. You get automatic retry behavior without having to build it yourself.</p><p><strong>Async user experience</strong>: The user doesn’t wait for the slow work. You tell them “we received your request, we’ll email you when it’s done.” Users are surprisingly okay with this if you set expectations correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYOI5ZMP7xkPMlVoBvFh8A.png" /></figure><p>Examples of work that belongs in a queue: sending emails, processing images, generating reports, making external API calls, updating search indexes.</p><h3>The network, again, but worse</h3><p>Let’s talk about distributed systems failures more concretely. When you make a network call in a distributed system, there are actually four different things that can happen, not two.</p><ol><li>The request is sent, the server receives it, processes it, and the response comes back successfully.</li><li>The request is sent but never arrives (packet loss, cable cut).</li><li>The request arrives, the server processes it, but the response never comes back (server crash after processing, network drop on the return path).</li><li>The request arrives, the server starts processing it, but takes so long that you give up waiting (<strong>timeout</strong>).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LF2LRK8494lhC5Hxu1RC5Q.png" /></figure><p>The deeply tricky case is number 3. The server processed your request. The work happened. But you never got confirmation. So you don’t know whether it happened or not. From your perspective, the operation is in an unknown state.</p><p><em>What is a timeout?</em> A timeout is when you decide to stop waiting for a response after a certain amount of time. Timeouts are necessary because without them, you might wait forever. But they create a dilemma: when your request times out, you don’t know whether the server received and processed it, or whether it never arrived. Acting on either assumption can be wrong.</p><p>This is sometimes called the <strong>two generals problem</strong> (a classic thought experiment in computer science). Two army generals are trying to coordinate an attack by sending messengers through enemy territory. The messenger might be captured. Neither general can know if the other received their message. So neither can know whether to attack simultaneously. The problem has no perfect solution, and neither does the distributed systems equivalent.</p><p>In practice, engineers handle this with <strong>idempotency</strong>.</p><p><em>What is idempotency?</em> An operation is idempotent if doing it multiple times has the same effect as doing it once. Adding 1 to a number is not idempotent (doing it twice gives a different result than doing it once). Setting a number to 5 is idempotent (doing it a hundred times, you still end up with 5).</p><p>If your operations are idempotent, you can safely retry them without worrying about double-processing. The user clicks “pay” and you’re not sure if the payment went through, so you try again. If the first payment was processed and you retry, you need to make sure the customer doesn’t get charged twice. Banks handle this with idempotency keys: a unique ID attached to each payment attempt. If you see the same ID twice, you return the same response as before without actually charging again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CHNwZVlHWLp-aCZIyjNHlA.png" /></figure><h3>Putting it all together</h3><p>At this point you might feel like system design is an endless list of problems with no clean solutions. That’s partly true. Every solution introduces new trade-offs.</p><p>But there’s a pattern underneath all of it.</p><p>The pattern is: <strong>every bottleneck in a system is either a compute problem, a storage problem, or a network problem</strong>. And the solution to each is different.</p><p><strong>Compute problems</strong> (too much processing to do) are solved by adding more processing capacity: more servers, better algorithms, pushing work to clients (where possible), or deferring work with queues.</p><p><strong>Storage problems</strong> (too much data or too many reads/writes) are solved by caching (for reads), read replicas (for read scale), sharding (for write scale), or rethinking your data model entirely.</p><p><strong>Network problems</strong> (too much data moving, too slowly, across too many hops) are solved by moving data closer to users (CDNs and edge caching), by reducing the size of data you transfer (compression), or by reducing the number of round trips (batching requests, denormalizing data so one query gets everything you need).</p><p><em>What is a CDN?</em> A CDN (Content Delivery Network) is a geographically distributed network of servers that caches static content (images, videos, scripts, stylesheets) closer to users. Instead of a user in Tokyo fetching an image from a server in Virginia, they fetch it from a CDN node in Singapore. Fewer kilometers for the data to travel. Faster response.</p><p><em>What is denormalization?</em> In a normalized database, data is stored without redundancy. User information is in one table, order information is in another, and you join them together when you need both. In a denormalized database, you intentionally store redundant data to make reads faster. Instead of two tables you join, you have one table with all the fields already combined. You trade extra storage and more complex writes for simpler, faster reads.</p><p>When you look at any large system — Twitter, Uber, Netflix, Stripe — you’re looking at a collection of decisions along these axes, each one a response to a specific bottleneck that was hit at a specific scale. The design isn’t the result of someone sitting down and reasoning from first principles in one go. It’s the result of years of responding to real problems.</p><h3>What “from first principles” actually means in practice</h3><p>There’s a temptation in system design interviews and blog posts to treat systems as puzzles with correct answers. Design a URL shortener. Design Twitter. Here are the components you need.</p><p>That’s not design thinking. That’s pattern matching.</p><p>Real design thinking starts with questions:</p><ul><li>What are we actually trying to achieve? (What are the requirements, and which of them matter most?)</li><li>What could go wrong? (Where are the failure modes? What happens when a component fails?)</li><li>What are we optimizing for? (Latency? Throughput? Consistency? Cost? All four? You can’t have all four.)</li><li>What scale are we actually at? (Designing a system for a million users when you have a hundred is premature optimization. Build the simplest thing that works, then scale what actually becomes a bottleneck.)</li></ul><p>The first principles of system design are not “use a cache” or “use a message queue.” Those are tools. The first principles are the underlying constraints they’re responding to:</p><p>Memory is faster than disk. Local is faster than network. Simple is more reliable than complex. Everything fails. Consistency and availability don’t come free when the network is unreliable.</p><p>Once you internalize these, you can look at any system and understand its design choices without being told. You see a cache and think: they had a slow database read that was happening repeatedly, and they could tolerate slight staleness. You see a message queue and think: they had a burst-prone workload and needed to decouple the request from the processing.</p><p>This is the shift from “I memorized the patterns” to “I understand why those patterns exist.”</p><h3>A small example: let’s design a URL shortener</h3><p>Take a URL shortener. You give it a long URL; it gives you a short code. When someone visits the short code, they get redirected to the long URL.</p><p>Start with requirements. The core requirements are: create a short URL, redirect from short to long URL. What else matters?</p><p>How many URLs will be created? Let’s say 1 million new URLs per day. How long do we store them? Let’s say indefinitely. How many redirects per day? Redirects will be much higher than creations. Maybe 100:1 ratio. So 100 million redirects per day, roughly 1,150 per second on average, with peaks probably 10x that.</p><p>Now think about the data. Each URL mapping is tiny. A short code (7 characters, maybe) and the long URL (a few hundred bytes at most). 1 million URLs per day, running for 10 years, is 3.65 billion URLs. At a few hundred bytes each, that’s a few hundred gigabytes of raw data. Easily fits in a single database today. Storage is not the problem.</p><p>The problem is reads. 1,150 redirects per second on average, 10,000+ at peak. Every redirect is a database read. Can a single database handle 10,000 reads per second? Yes, actually. Modern databases can handle much more than that for simple key lookups. But we’re not building for today. We’re thinking about what breaks as we grow.</p><p><strong>Observation 1</strong>: Reads dominate (100:1 reads to writes). So the first thing we should add is a cache. The most popular short URLs get cached in memory. The cache hit rate for popular URLs will be very high, which dramatically reduces database load.</p><p><strong>Observation 2</strong>: Redirects need to be fast. Users are in the middle of doing something. A slow redirect is a bad experience. Since we’re caching, most popular redirects will be milliseconds. Good.</p><p><strong>Observation 3</strong>: Short code generation needs to be unique. If two writes happen at the same time and they both generate the same code, one of them will fail. This is a concurrency problem.</p><p><em>What is a concurrency problem?</em> A concurrency problem is when two or more operations happen simultaneously and interfere with each other in a way that produces an incorrect result. Classic example: two threads both read a counter (value: 5), both add 1, both write back (value: 6). But the correct answer is 7. This is called a <strong>race condition</strong>.</p><p>For short code generation, you can handle this by generating a random code and checking if it already exists in the database before writing. If it does, generate another. For very large systems, a dedicated ID generation service (that hands out guaranteed-unique IDs) is cleaner.</p><p><strong>Observation 4</strong>: What if the database is down? All redirects fail. That’s bad for a service that’s supposed to “just work.” You’d want at minimum a read replica to handle redirects even if the primary is down.</p><p><strong>Observation 5</strong>: How do you handle a viral link? If a tweet with a short URL suddenly gets retweeted by someone with 10 million followers, you might get 500,000 redirects in 5 minutes. That’s a sudden spike. Your cache should handle most of it (the URL will be in cache after the first few hits). But what if the URL isn’t cached yet? The first wave of requests all miss the cache and all hit the database simultaneously. This is the <strong>thundering herd</strong> problem.</p><p><em>What is the thundering herd problem?</em> When a cache entry expires (or is empty), many requests arrive at the same time for the same data. They all miss the cache and all stampede to the database simultaneously, potentially overwhelming it. Solutions include cache locking (only one request populates the cache, others wait) or slightly randomizing TTLs so not all entries expire at exactly the same moment.</p><p>The URL shortener example is “simple” but notice how many real distributed systems problems come up: caching, consistency, concurrency, spike handling, availability. Every system you design, no matter how simple it sounds, will have versions of these problems.</p><h3>Where to go from here</h3><p>The goal of this article was not to give you a complete list of system design patterns. There are plenty of books for that.</p><p>The goal was to show you that every pattern exists for a reason. Not as an arbitrary rule, but as a response to a concrete physical constraint: memory is faster than disk, networks are slow and unreliable, everything fails, you can’t have consistency and availability for free when partitions happen.</p><p>When you internalize those constraints, you start to see systems differently. You don’t ask “which pattern should I use?” You ask “what is the bottleneck?” and the right approach usually becomes obvious.</p><p>A few things worth doing from here:</p><p>Read about real outages. AWS, Cloudflare, Stripe, and others publish detailed post-mortems when their systems fail. These are the most educational documents in the field, because they show real systems failing in unexpected ways, and how engineers thought about the failure. The AWS post-mortem from the 2011 US-EAST-1 outage is a masterpiece of systems thinking, even today.</p><p>Build something and hit its limits. If you’ve never had a database fall over under load, if you’ve never had a race condition bite you in production, the concepts stay abstract. The fastest way to internalize these ideas is to build a small project, take it to some load, and watch it break.</p><p>Learn to ask “what happens when this breaks?” for every component in every system you build. The habit of asking that question, before the system is in production, is what separates experienced engineers from beginners. Not the knowledge of Kafka or DynamoDB or Kubernetes. The habit of thinking about failure.</p><p>System design is not a collection of patterns. It’s a way of thinking. Once you see it that way, the whole field opens up!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=343bd7f41221" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How React Really Works: Fiber, Virtual DOM, and Everything in Between.]]></title>
            <link>https://muhammedbasith.medium.com/how-react-really-works-fiber-virtual-dom-and-everything-in-between-a303e8e2020d?source=rss-a3fffc06f107------2</link>
            <guid isPermaLink="false">https://medium.com/p/a303e8e2020d</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Basith]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 16:47:33 GMT</pubDate>
            <atom:updated>2025-07-15T16:47:33.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6lkE8zCE_vAhkZdp" /></figure><p><em>If you’ve been using React for a while, chances are you’ve heard terms like “Virtual DOM” or “Fiber”. Maybe you’ve used </em><em>createRoot() in your latest React project, and wondered: </em>What exactly is React doing under the hood?</p><p><em>This article isn’t just about definitions. I want to take you through the actual journey of what happens from the moment you write:</em></p><pre>const root = ReactDOM.createRoot(document.getElementById(&quot;root&quot;));<br>root.render(&lt;App /&gt;);</pre><p><em>…all the way down to how React updates your screen so efficiently. And every time we hit a new term, like “Fiber Tree” or “Concurrent Rendering”, we’ll pause and explain it clearly. Nothing vague. No jargon without meaning.</em></p><p><em>So let’s start from the very beginning.</em></p><h3>What is React doing when you call createRoot()?</h3><p>When you write ReactDOM.createRoot(...), you’re telling React: “Hey, I’m going to manage this part of the page using React now.”</p><p>React will take that DOM element (div#root or any element you give) and internally create a <strong>Fiber Root Node</strong>. You won’t see this in your code, but behind the scenes, this root becomes the entry point to React’s own internal system, the <strong>Fiber Tree</strong>.</p><h3>What is this Fiber Tree?</h3><p>Think of Fiber Tree as React’s internal brain.</p><p>Whenever you build a UI using React components (&lt;App /&gt;, &lt;Header /&gt;, etc.), React turns each component into a <strong>Fiber node</strong>.</p><p>A <strong>Fiber node</strong> is just a plain JavaScript object. Each node holds information like:</p><ul><li>What component does it represent</li><li>Its props and state</li><li>Its parent and child nodes</li><li>What needs to be updated</li></ul><p>These Fiber nodes are connected to form a tree, the <strong>Fiber Tree</strong>.</p><h3>So, what happens when you call render(&lt;App /&gt;)?</h3><p>This is where React gets to work. First, it builds the <strong>Virtual DOM</strong>.</p><h3>What is the Virtual DOM?</h3><p>So, on another tangent, the Virtual DOM is a lightweight copy of the real DOM, built using JavaScript objects.</p><p>If your real DOM is the actual UI that the browser shows, the Virtual DOM is a version of that UI React builds and holds in memory. It’s not visible in the browser, but React uses it to figure out what changed.</p><p>For example:</p><pre>&lt;div&gt;<br>  &lt;h1&gt;Hello&lt;/h1&gt;<br>&lt;/div&gt;</pre><p>This becomes something like:</p><pre>{<br>  type: &#39;div&#39;,<br>  props: {},<br>  children: [<br>    {<br>      type: &#39;h1&#39;,<br>      props: {},<br>      children: [&#39;Hello&#39;]<br>    }<br>  ]<br>}</pre><p>This is your Virtual DOM tree.</p><h3>Why doesn’t React just update the real DOM directly?</h3><p>Because the real DOM is slow. Manipulating it often is <strong>expensive</strong>.</p><p>So React uses a smarter approach:</p><ol><li>Build a Virtual DOM tree in memory.</li><li>On each update, build a new Virtual DOM.</li><li>Compare it with the previous one.</li><li>Find the smallest difference.</li><li>Apply <strong>only</strong> that difference to the real DOM.</li></ol><p>This process is called <strong>reconciliation</strong>.</p><h3>What is Reconciliation?</h3><p>Reconciliation is React’s way of saying:</p><p><em>“Let me look at what changed between the last render and this one, and only touch the parts of the DOM that actually need an update.”</em></p><p>Instead of replacing everything, React updates only what’s needed. This makes UI updates much faster and smoother.</p><p>But there’s one problem…</p><h3>What if the component tree is huge?</h3><p>Imagine a massive page with hundreds of components. Should React pause everything and go through the entire tree before showing anything?</p><p>That used to be the case. React rendering was synchronous — it would block the browser until everything was done.</p><p>This is where <strong>React Fiber</strong> comes in.</p><h3>What is React Fiber really?</h3><p>React Fiber is React’s rendering engine. It’s the behind-the-scenes system that controls how React builds and updates the UI.</p><p>Before Fiber (in React 15 and earlier), React used a recursive algorithm to walk through the component tree. But it couldn’t be paused. That meant large updates would freeze the UI.</p><p>Fiber fixed that.</p><p>Now, React rendering can be:</p><ul><li><strong>Interruptible: </strong>it can pause work and resume later</li><li><strong>Prioritized: </strong>more important updates (like typing) can be done before less important ones</li><li><strong>Concurrent</strong>: multiple updates can be managed at the same time</li></ul><p>All of this is possible because Fiber breaks the work into small units and processes them in chunks.</p><h3>How does React break work into chunks?</h3><p>Each component becomes a <strong>unit of work</strong>.</p><p>React builds a Fiber node for each of these, and starts going through them one by one.</p><p>If the browser says, “Hey, I need time to respond to user input,” React can pause, let the browser do its thing, and then continue from where it left off.</p><p>This is what makes features like <strong>Concurrent Rendering</strong> possible.</p><h3>What is Concurrent Rendering?</h3><p>Concurrent Rendering is a new capability introduced in React 18.</p><p>It allows React to prepare multiple UI updates in the background and commit them only when ready. This improves responsiveness.</p><p>For example, if you’re typing in a form, React can prioritize that update over a slow image loading somewhere else.</p><h3>What changed with createRoot() in React 18?</h3><p>In older versions, you might have used:</p><pre>ReactDOM.render(&lt;App /&gt;, document.getElementById(&quot;root&quot;));</pre><p>This was fine, but didn’t support Concurrent Rendering.</p><p>React 18 introduced:</p><pre>const root = ReactDOM.createRoot(document.getElementById(&quot;root&quot;));<br>root.render(&lt;App /&gt;);</pre><p>This small change gives you access to all the new features: concurrent rendering, transitions, streaming, etc.</p><h3>Can you see all this in action?</h3><p>Not directly in the browser, but you can peek under the hood.</p><ul><li>Use <strong>React Developer Tools</strong> to explore the component tree.</li><li>If you console.log(root), you might see internal structures—though they’re not meant for public use.</li></ul><p>React’s internals like Fiber and the Virtual DOM aren’t exposed directly, but you can study how they behave by observing when components mount, update, or re-render.</p><h3>So what’s the flow from code to UI?</h3><p>Let’s sum it up:</p><ol><li>You call createRoot(...)</li><li>React builds a Fiber Root and prepares to manage updates.</li><li>You render your component tree.</li><li>React builds a Virtual DOM tree and Fiber Tree.</li><li>On updates, it:</li></ol><ul><li>Compares the new tree with the old</li><li>Figures out the minimal changes</li><li>Applies only those to the actual DOM</li></ul><p>All of this happens in a way that can be paused, resumed, and prioritized.</p><p>React does a lot behind the scenes to make your UI feel instant. But once you understand Fiber, Virtual DOM, and how rendering works, you realize, it’s not magic. Just smart design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a303e8e2020d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This One Shift Made My React Native App Faster, Leaner, and Smarter]]></title>
            <link>https://muhammedbasith.medium.com/this-one-shift-made-my-react-native-app-faster-leaner-and-smarter-ff55659ffb76?source=rss-a3fffc06f107------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff55659ffb76</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Basith]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 19:20:29 GMT</pubDate>
            <atom:updated>2025-04-22T19:20:29.986Z</atom:updated>
            <content:encoded><![CDATA[<p>Okay, let’s talk about choosing between REST APIs and GraphQL for mobile apps, especially when you’re building with React Native. I’ll give you my honest thoughts based on experience and research, keeping it straightforward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wehj8PWCF0cb15H_" /></figure><p>First, let’s think about Mobile Apps in General</p><p>Mobile apps are different compared to web apps running on a desktop. The biggest things I always keep in mind are:</p><ol><li>Network Connection: It can be spotty, slow, or jump between Wi-Fi and cellular. You can’t assume a stable, fast connection like you might on a desktop. Every network request costs time and potentially money (data plans).</li><li>Data Usage: Users care about how much data your app uses. Nobody likes an app that drains their data plan just by browsing.</li><li>Battery Life: Making lots of network requests chews through battery.</li><li>Screen Size &amp; UI: Mobile screens are small. You often need very specific bits of data from different places to build a single screen (like user info, their latest posts, maybe some notification counts).</li></ol><p>REST APIs</p><p>REST has been around forever. It’s basically using standard web URLs and methods (like GET, POST, PUT, DELETE) to interact with data.</p><ul><li>How it usually works: You ask for data from a specific URL (endpoint), like /users/123 to get user info, or /users/123/posts to get their posts. The server decides exactly what data fields it sends back for that endpoint.</li><li>My thoughts on REST for Mobile:</li><li>Simplicity: It’s generally simple to understand and get started with. Lots of public APIs are RESTful. Basic fetching is easy using standard tools (fetch or libraries like Axios).</li><li>The Pain Point — Over-fetching: Often, an endpoint like /users/123 gives you <em>everything</em> about the user – their ID, name, email, address, signup date, last login, favorite color... but maybe your mobile screen <em>only</em> needed their name and profile picture URL. You fetched a bunch of extra data you didn&#39;t need, wasting bandwidth and potentially slowing things down.</li><li>The Other Pain Point — Under-fetching: Sometimes, one screen needs data that requires multiple REST calls. Get the user (/users/123), <em>then</em> get their posts (/users/123/posts), <em>then</em> maybe get comments for the first post (/posts/456/comments). Each of these is a separate round trip over the network. On a slow mobile connection, this feels <em>really</em> sluggish and drains battery.</li><li>Versioning: As the API changes, you often see /v1/users, /v2/users, etc. Managing different versions across mobile app releases can be a bit annoying.</li></ul><p>GraphQL — The Precise Query Language</p><p>GraphQL works differently. Instead of many endpoints, there’s usually just <em>one</em> main endpoint. You, the client (your mobile app), send a <em>query</em> that describes <em>exactly</em> the data structure you need.</p><ul><li>The server receives this query, gathers <em>only</em> the requested data (name, avatarUrl, and the title of 3 posts), and sends it back in a structure that mirrors your query.</li><li>My thoughts on GraphQL for Mobile:</li><li>Solving Fetching Issues: This is GraphQL’s superpower for mobile. It directly solves over-fetching (you only get name and avatarUrl) and under-fetching (you get the user and their posts in <em>one single network request</em>). This is a massive win for mobile network performance, data usage, and battery life.</li><li>Flexibility: As your app’s UI changes, you just modify the GraphQL query in your app to ask for the new fields you need. You often don’t need the backend team to create a new REST endpoint. This makes iterating on mobile UIs much faster.</li><li>Strong Typing: GraphQL APIs have a schema that defines all the possible data types and fields. This makes development much safer, especially with tools like TypeScript, as you know exactly what data shape to expect. Great for catching errors early.</li><li>Setup Complexity: Honestly, setting up GraphQL on the <em>backend</em> is more work initially than a simple REST API. On the <em>client</em> (mobile app) side, while basic fetching is possible, you usually want to use a dedicated library.</li><li>Caching: Caching with GraphQL is different from REST (where you rely heavily on HTTP caching). Client libraries handle this, but it’s something to understand.</li></ul><p>Now, Focusing on React Native</p><p>React Native apps are all about components. Each component often needs specific pieces of data.</p><ul><li>With REST in RN: You’d likely use fetch or Axios, maybe combined with state management (like Zustand or Redux) and possibly a data-fetching library like react-query (TanStack Query) or SWR. These help manage loading/error states and caching, but you still face the underlying over/under-fetching issues of REST itself. You might find yourself writing logic to combine data from multiple requests.</li><li>With GraphQL in RN: This is where libraries like Apollo Client or Relay really shine. They are <em>specifically designed</em> for using GraphQL within React/React Native.</li><li>They handle sending the query, managing loading/error states, and most importantly, intelligent caching. They can normalize the data (store user 123 once, even if fetched in different queries) and automatically update components when the cache changes.</li><li>They often provide hooks (useQuery, useMutation) that integrate beautifully into your React Native components.</li><li>The strong typing from the GraphQL schema, combined with TypeScript in your React Native project, makes for a really robust developer experience. Tools can even auto-generate TypeScript types from your GraphQL schema!</li></ul><p>So, Which One Do I Prefer for React Native?</p><p>Generally, for anything beyond a very simple app, I lean towards GraphQL when building React Native applications, <em>if</em> I have control over the backend or if a GraphQL API is available.</p><p>Why?</p><ul><li>Performance: The ability to fetch exactly what’s needed in a single request is just too good to pass up for mobile constraints. It directly addresses the latency and data usage issues that plague mobile apps using traditional REST APIs with lots of calls.</li><li>Developer Experience: Client libraries like Apollo Client combined with GraphQL’s strong typing and tooling make development faster and safer once you’re set up. It feels very natural with React Native’s component model — components declare the data they need via fragments, and the library figures out how to fetch it efficiently.</li><li>Flexibility: Frontend (RN app) development can move faster without constantly waiting for backend changes to REST endpoints.</li></ul><p>When Might I Still Use REST in React Native?</p><ul><li>Existing API: If I <em>have</em> to consume an existing, third-party REST API that I can’t change.</li><li>Very Simple App: If the app’s data needs are extremely basic and unlikely to change much.</li><li>Team Familiarity: If the team is much more comfortable with REST and the overhead of learning/setting up GraphQL (especially on the backend) is a major blocker.</li><li>Backend Constraints: If the backend team strongly prefers or is only equipped to build REST APIs.</li></ul><p>So, in conclusion, while REST is simpler initially, GraphQL’s efficiency and flexibility often provide significant advantages for building complex, performant React Native apps by directly tackling the network and data challenges inherent in mobile development. The excellent client libraries available for React Native make integrating GraphQL a smooth experience once the initial learning curve is overcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff55659ffb76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Google Getting Dusty?]]></title>
            <link>https://muhammedbasith.medium.com/is-google-getting-dusty-6fc105f397fe?source=rss-a3fffc06f107------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fc105f397fe</guid>
            <category><![CDATA[thoughts]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[evolution]]></category>
            <dc:creator><![CDATA[Basith]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 06:54:03 GMT</pubDate>
            <atom:updated>2025-04-10T06:54:03.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wkTRF2QrWVPqLeHvbxnIhw.jpeg" /></figure><p>Ever opened Google, stared at the blinking cursor in the search bar, and thought… “You know what, I’ll just ask ChatGPT”?</p><p>Yeah. Same here.</p><p>More and more, I catch myself skipping Google entirely. Not because it’s bad, but because AI chat feels <em>easier</em>. Like I don’t have to wrestle with keywords, click through a dozen tabs, or dodge half a screen of ads before finding what I actually want.</p><h3>Why ChatGPT Feels Better (Sometimes)</h3><p>We’ve all had those moments where we kinda know what we’re looking for but don’t know the right words to type. Maybe it’s some layered, abstract idea floating around your head — and AI tools just get it when you try to describe it.</p><p>I remember once asking:</p><blockquote><em>“Is there a name for when your brain predicts what’s about to happen and kind of suppresses the sensory input for it, so you don’t notice familiar stuff unless something unexpected happens?”</em></blockquote><p>Google gave me “habituation,” “selective attention,” and “sensory adaptation,” but none of those hit the mark.</p><p>ChatGPT came back with:</p><blockquote><em>“What you’re describing sounds like </em><strong><em>predictive coding</em></strong><em>, a theory in neuroscience and cognitive science. It suggests the brain is constantly generating models to predict sensory input and only updates these models when there’s a mismatch — also called a ‘prediction error.’”</em></blockquote><p>I was floored. That was <em>exactly</em> the idea I had in my head. And now I had a term, theory, and papers to dive into.</p><p>And when you’re just learning something new, it feels way more natural to ask follow-up questions than to keep hitting the back button.</p><h3>But Let’s Not Throw Google Away Yet</h3><p>That said, I still need Google. A lot.</p><p>There are times when I want the source. Not a summary. I want to know if something came from a legit blog, a random Reddit post, or the actual docs. And if I’m looking for a specific link — say, the homepage of a niche tool I heard about — Google’s still faster and more reliable.</p><p>There’s also something nice about browsing. Scanning headlines, seeing different opinions, stumbling onto stuff you didn’t even know to ask about — that’s part of how we learn too.</p><p>And let’s be honest: AI still messes up. It can be super confident and still give the wrong info. So if it’s something important, I double-check anyway. Which sometimes takes just as long as Googling would have.</p><h3>So What Now?</h3><p>Honestly, it’s not about picking one over the other. I’ve kind of built my own rhythm:</p><ul><li>I use ChatGPT/other to make sense of something new, or to find the right words to search for.</li><li>I use Google when I need specific sources, current events, or official sites.</li><li>And sometimes, I’ll even combine the two — ask ChatGPT, then use Google to dig deeper.</li></ul><p>It’s not perfect, but it works. I guess the way we search is evolving. Not dying. Just shifting.</p><p>How about you? Still a Google-first person, or have you made the switch?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fc105f397fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hollywood Principle!]]></title>
            <link>https://muhammedbasith.medium.com/the-hollywood-principle-ad69226cc725?source=rss-a3fffc06f107------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad69226cc725</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[principles]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Basith]]></dc:creator>
            <pubDate>Thu, 15 Aug 2024 17:31:52 GMT</pubDate>
            <atom:updated>2024-08-15T17:31:52.088Z</atom:updated>
            <content:encoded><![CDATA[<p>Sounds fancy?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CbpEKFj_4GtHLDac" /></figure><p>So, I’ve Been Exploring Java Spring, and that’s when I stumbled upon the Hollywood Principle, which is a software design principle that states <strong>“don’t call us, we’ll call you.”</strong> In other words, it encourages loose coupling between modules by having high-level modules depend on abstractions rather than concrete implementations. This makes it easier to swap out implementations without affecting the rest of the system.</p><p>In Java, this principle can be implemented using interfaces and dependency injection. Interfaces allow for the creation of abstractions that can be implemented by multiple classes. Dependency injection allows for the injection of a concrete implementation at runtime, rather than having the class create its own dependencies.</p><p>Example code that violates the Hollywood Principle:</p><pre>//Bad Example, Tight Coupling<br>class BadMoviePlayer {<br>    public void playMovie() {<br>        //creating instance of concrete class<br>        MobileDevice mobileDevice = new MobileDevice();<br>        mobileDevice.playMovie();<br>    }<br>}</pre><p>In this example, the BadMoviePlayer class creates an instance of MobileDevice and calls its playMovie() method. This creates a tight coupling between the BadMoviePlayer class and the MobileDevice class, making it difficult to swap out the implementation without affecting the rest of the system.</p><p>A better way to implement this would be to use interfaces and dependency injection:</p><pre>interface Device {<br>    void playMovie();<br>}</pre><pre>class GoodMoviePlayer {<br>    private Device device;</pre><pre>    public GoodMoviePlayer(Device device) {<br>        this.device = device;<br>    }</pre><pre>    public void playMovie() {<br>        device.playMovie();<br>    }<br>}</pre><pre>class MobileDevice implements Device {<br>    public void playMovie() {<br>        // Perform action<br>    }<br>}</pre><p>In this improved example, GoodMoviePlayer doesn’t care what specific device it’s working with. It only needs a Device. You can pass in any class that implements the Device interface, making it super easy to swap out one device for another.</p><p><strong>Real-World example</strong></p><p>Let’s say you’re working on an Android app, and you need to change the network library. Instead of hunting down every instance of the old library in your code, you just create a new implementation of your Network interface and inject it where needed. Boom—problem solved.</p><p>Another great use case is with payment gateways. Imagine your app supports multiple payment options like PayPal and Stripe. By creating an interface that outlines the required payment methods, you can easily switch between different payment gateways without touching the rest of your code.</p><p>So, in conclusion, The Hollywood Principle is your ticket to writing flexible, maintainable code. Java makes it easy to implement, especially with tools like Spring.</p><blockquote>And just like in Hollywood, remember — you’re not the star, the code is. 👀</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad69226cc725" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crucial Metrics for Assessing Classification Model Performance]]></title>
            <link>https://muhammedbasith.medium.com/crucial-metrics-for-assessing-classification-model-performance-2cdd03cae3b?source=rss-a3fffc06f107------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cdd03cae3b</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Basith]]></dc:creator>
            <pubDate>Sat, 06 Jul 2024 17:14:31 GMT</pubDate>
            <atom:updated>2024-07-06T17:14:31.395Z</atom:updated>
            <content:encoded><![CDATA[<p>Measuring the performance of a classification model is essential for ensuring its effectiveness in real-world applications, and in this article, we’ll explore the most important metrics to understand how well your model is performing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gG3uEXg6OZ4P7dIa" /></figure><h3>1. Confusion Matrix</h3><p>A confusion matrix is a table that is often used to describe the performance of a classification model on a set of test data for which the true values are known. It is a table with four different combinations of predicted and actual values in the case for a binary classifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*_TgSCUtkdj4JzkB5ozQZXg.jpeg" /></figure><p>The confusion matrix for a multi-class classification problem can help you determine mistake patterns.</p><p>For a binary classifier:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*fqpbCld2q7UDmujd.png" /></figure><p>A <strong>true positive</strong> is an outcome where the model correctly predicts the positive<em> </em>class. Similarly, a <strong>true negative</strong> is an outcome where the model correctly predicts the negative class.</p><h4>False Positive and False Negative</h4><p>The terms false positive and false negative are used in determining how well the model is predicting with respect to classification. A false positive is an outcome where the model <em>incorrectly</em> predicts the <em>positive</em> class. And a false negative is an outcome where the model <em>incorrectly</em> predicts the <em>negative</em> class. The more values in main diagonal, the better the model, whereas the other diagonal gives the worst result for classification.</p><p><strong>False Positive</strong></p><p>False positive<strong> </strong><em>(type I error)</em><strong> </strong>— when you reject a true null hypothesis.</p><p>This is an example in which the model mistakenly predicted the <a href="https://developers.google.com/machine-learning/glossary/#positive_class">positive class</a>. For example, the model inferred that a particular email message was spam (the positive class), but that email message was actually not spam. It’s like a warning sign that the mistake should be rectified as it’s not much of a serious concern compared to false negative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*qln0mlW0XvPopiLL.png" /></figure><p><strong>False Negative</strong></p><p>False negative <em>(type II error)</em> — when you accept a false null hypothesis.</p><p>This is an example in which the model mistakenly predicted the <a href="https://developers.google.com/machine-learning/glossary/#negative_class">negative class</a>. For example, the model inferred that a particular email message was not spam (the negative class), but that email message actually was spam. It’s like a danger sign that the mistake should be rectified early as it’s more serious than a false positive.</p><h4>Accuracy, Precision, Recall, and F-1 Score</h4><p>From the confusion matrix, we can infer accuracy, precision, recall, and F-1 score.</p><p><strong>Accuracy</strong></p><p>Accuracy is the fraction of predictions our model got right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*Zenv_1xnut6hafsn.png" /></figure><p>Accuracy can also be written as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/0*-HNA-EVm_sMIOwz7.png" /></figure><p>Accuracy alone doesn’t tell the full story when working with a class-imbalanced data set, where there is a significant disparity between the number of positive and negative labels. Precision and recall are better metrics for evaluating class-imbalanced problems.</p><p><strong>Precision</strong></p><p>Out of all the classes, precision is how much we predicted correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Udt-n5PMdv06VYLVxVhJVg.png" /></figure><p>Precision should be as high as possible.</p><p><strong>Recall</strong></p><p>Out of all the positive classes, recall is how much we predicted correctly. It is also called sensitivity or true positive rate (TPR).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FdnWTxoSC0bDcCnR53zGqg.png" /></figure><p>Recall should be as high as possible.</p><p><strong>F-1 Score</strong></p><p>It is often convenient to combine precision and recall into a single metric called the F-1 score, particularly if you need a simple way to compare two classifiers. The F-1 score is the harmonic mean of precision and recall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h_sgIhysU3brAX2_NlEVEA.jpeg" /></figure><p>The regular mean treats all values equally, while the harmonic mean gives much more weight to low values thereby punishing the extreme values more. As a result, the classifier will only get a high F-1 score if both recall and precision are high.</p><h3>2. Receiver Operator Curve (ROC) &amp; Area Under The Curve (AUC)</h3><p>The ROC curve is an important classification evaluation metric. It tells us how well the model has accurately predicted. The ROC curve shows the sensitivity of the classifier by plotting the rate of true positives to the rate of false positives. If the classifier is outstanding, the true positive rate will increase, and the area under the curve will be close to one. If the classifier is similar to random guessing, the true positive rate will increase linearly with the false positive rate. The better the AUC measure, the better the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJVo3uDkFGEZF1z5hf8GBA.jpeg" /></figure><h3>3. Cumulative Accuracy Profile Curve</h3><p>The CAP of a model represents the cumulative number of positive outcomes along the <em>y</em>-axis versus the corresponding cumulative number of classifying parameters along the <em>x</em>-axis. The CAP is distinct from the receiver operating characteristic (ROC), which plots the true-positive rate against the false-positive rate. CAP curve is rarely used as compared to the ROC curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/0*CeQp88RhNMBG7Il2.png" /></figure><p>Consider a model that predicts whether a customer will purchase a product. If a customer is selected at random, there is a 50 percent chance they will buy the product. The cumulative number of elements for which the customer buys would rise linearly toward a maximum value corresponding to the total number of customers. This distribution is called the “random” CAP. It&#39;s the blue line in the above diagram. A perfect prediction, on the other hand, determines exactly which customer will buy the product, such that the maximum customers buying the property will be reached with a minimum number of customer selections among the elements. This produces a steep line on the CAP curve that stays flat once the maximum is reached, which is the “perfect” CAP. It’s also called the “ideal” line and is the grey line in the figure above.</p><p>In the end, a model should predict where it maximizes the correct predictions and gets closer to a perfect model line.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cdd03cae3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Networks Matter in Software Engineering.]]></title>
            <link>https://muhammedbasith.medium.com/why-networks-matter-in-software-engineering-141f26db4bf7?source=rss-a3fffc06f107------2</link>
            <guid isPermaLink="false">https://medium.com/p/141f26db4bf7</guid>
            <category><![CDATA[computer-networking]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Basith]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 14:17:54 GMT</pubDate>
            <atom:updated>2024-07-04T14:17:54.652Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s talk about computer networks. Nowadays, if you say you’re a web developer and I ask about the basics of networking, and you seem unbothered, well, that kind of says a lot. Without a grasp of networking fundamentals, it’s hard to excel in the field. It is a crucial aspect of software engineering that often goes unnoticed until you dive deep into the field. I used to be that person, completely uninterested in concepts like HTTP, TCP, and IP — they seemed like a foreign language. However, looking back, I realize how essential networking is to being a better engineer. So, let me take you through these concepts in simple terms and explain why they matter so much.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mnXCFx5qGJ_GWxHl" /></figure><h3><strong>What is Networking?</strong></h3><p>Networking in the context of software engineering refers to how different devices (like computers, smartphones, and servers) communicate with each other. This communication is crucial for various applications we use daily, like browsing the internet, sending emails, and streaming videos. So, let’s start with some key concepts.</p><p><strong>HTTP (HyperText Transfer Protocol)</strong></p><p>HTTP is the foundation of data communication on the web. It’s the protocol used by web browsers and servers to communicate. When you type a website address in your browser, it sends an HTTP request to the server, which then responds with the requested web page.</p><p>One drawback is that HTTP operates over plain text, which means the data sent between your browser and the server is not encrypted. This lack of encryption can potentially expose sensitive information to malicious interception, making it less secure for activities like entering passwords or sharing personal details.</p><p>On the other hand, HTTPS (HyperText Transfer Protocol Secure) addresses this security concern by adding an extra layer of protection through encryption. When you visit a website using HTTPS, your browser and the server encrypt the data being transmitted. This encryption ensures that even if someone intercepts the data, they cannot easily read or misuse it.</p><p>Imagine you’re shopping online and entering your credit card information to make a purchase. With HTTP, this information travels as plain text, vulnerable to interception. However, with HTTPS, the same information is encrypted, safeguarding it from potential hackers or eavesdroppers.</p><figure><img alt="Difference betwen HTTP and HTTPS." src="https://cdn-images-1.medium.com/max/675/1*bwXvRvnTLg8T_Wx2YLVoeA.png" /></figure><p><strong>TCP (Transmission Control Protocol)</strong></p><p>TCP is a core protocol of the Internet Protocol Suite. It ensures that data sent over the internet arrives at its destination accurately and in the correct order. Imagine TCP as a reliable mail service that makes sure all the letters (data packets) you send reach their destination intact.</p><p>So, how does TCP Work? The Three-Way Handshake;</p><p>TCP establishes a reliable connection between two devices using a process called the three-way handshake. This process ensures that both devices are ready to communicate and that the connection is established properly. Here’s a simple explanation of the three-way handshake:</p><ol><li>SYN (Synchronize):</li></ol><ul><li>The device that wants to establish a connection (let’s call it Device A) sends a TCP packet with a SYN (synchronize) flag to the other device (Device B).</li><li>This packet essentially says, “Hey, I want to start a conversation. Are you ready?”</li></ul><p>2. SYN-ACK (Synchronize-Acknowledge):</p><ul><li>Device B receives the SYN packet from Device A and responds with a SYN-ACK packet.</li><li>The SYN-ACK packet says, “Yes, I’m ready to start a conversation. Are you ready too?”</li></ul><p>3. ACK (Acknowledge):</p><ul><li>Device A receives the SYN-ACK packet and responds with an ACK packet.</li><li>This ACK packet says, “Great! I’m ready too. Let’s start communicating.”</li></ul><p>After these three steps, the connection is established, and data can be sent between the two devices.</p><p>Example:<br>Let’s say you want to load a webpage on your browser. Here’s how TCP and the three-way handshake work in this scenario:</p><ol><li>SYN: Your computer (Device A) sends a SYN packet to the web server (Device B) saying, “I want to load a webpage. Are you ready?”</li><li>SYN-ACK: The web server responds with a SYN-ACK packet saying, “I’m ready to send you the webpage. Are you ready to receive it?”</li><li>ACK: Your computer sends an ACK packet saying, “Yes, I’m ready. Send me the webpage.”</li></ol><p>Once this handshake is complete, the web server starts sending the webpage data to your computer using the HTTP protocol. The HTTP request is sent over the established TCP connection, and the server responds with the webpage data using HTTP. This process ensures that the packets arrive in the correct order and without errors.</p><p>So, here’s how it fits together:</p><ol><li>TCP Handshake: Ensures a reliable connection between your computer and the web server.</li><li>HTTP Request: Your browser sends an HTTP request over the established TCP connection to the web server, asking for the webpage.</li><li>HTTP Response: The web server sends back the requested webpage data using HTTP over the same TCP connection.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-3D95ui-B7XUi7VhyKehQ.png" /></figure><p><strong>Why Networking is Important in Software Engineering?</strong></p><ol><li>Communication: Most applications today rely on network communication. Whether it’s a mobile app fetching data from a server or a multiplayer game synchronizing actions between players, networking is at the heart of it.</li><li>Performance: Efficient networking can greatly enhance the performance of your applications. By optimizing how data is transmitted and received, you can ensure a smoother and faster user experience.</li><li>Security: Networking knowledge is vital for securing applications. Understanding how data travels over the internet helps you implement security measures to protect sensitive information from threats like hacking and data breaches.</li><li>Scalability: As your application grows, understanding networking helps you design systems that can scale effectively. This means your application can handle more users and more data without slowing down.</li></ol><p>Networking might seem complex at first, but it’s a fundamental part of software engineering. By understanding basic concepts like HTTP, TCP, and IP, you gain valuable insights into how applications communicate, perform, and scale. Adopt these concepts, and you’ll be better equipped to build robust, efficient, and secure software.</p><p>Thanks for reading! Stay curious and keep learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=141f26db4bf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Developer’s Paradox!]]></title>
            <link>https://muhammedbasith.medium.com/the-developers-paradox-f110511ba1b5?source=rss-a3fffc06f107------2</link>
            <guid isPermaLink="false">https://medium.com/p/f110511ba1b5</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[creativity]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[life]]></category>
            <dc:creator><![CDATA[Basith]]></dc:creator>
            <pubDate>Wed, 08 Nov 2023 13:41:25 GMT</pubDate>
            <atom:updated>2023-11-08T13:44:36.853Z</atom:updated>
            <content:encoded><![CDATA[<p>So let’s keep this plain. The “Paradox” is inescapable and is something all developers face in their careers at some point. And if you haven’t faced it yet, take some time to think about how you’ve grown as a developer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Uj0qWaVqq950U0e-" /></figure><p><strong>Now you may be thinking, “What is the paradox?”. It’s this:</strong></p><p>→ I feel like I’ve learned so much.</p><p>→ I feel like I don’t know enough.</p><p>These two conflicting feelings will lead you through highs and lows. You’ll have moments of thinking, “I’m a fantastic developer and I’m doing great,” but then you’ll quickly shift to, “I don’t know enough, and maybe I made the wrong career choice!”</p><p>Both feelings exist simultaneously and both will grow the longer you hone your craft. The more you learn and grow your skillset, the more you’ll become aware of tools, technologies, languages, concepts, or frameworks that are out there that you currently know nothing about or have no experience in.</p><p>It’s like saying “<em>The more I learn, the more I realize how much I don’t know</em>”.</p><p>This paradox is applicable to many aspects of life but particularly as a software developer with all the things going on this paradox that we’re talking about seems more applicable. The reason is that our industry evolves and changes at such a rapid pace, you learn some technology X and wake up tomorrow just to see that everything is deprecated or is out of context. Often, as soon as you’ve mastered one framework, there is another one ready to take its place, and the loop goes on and on and on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f110511ba1b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Five Essential Machine Learning Classification Algorithms to Familiarize Yourself With]]></title>
            <link>https://muhammedbasith.medium.com/five-essential-machine-learning-classification-algorithms-to-familiarize-yourself-with-d904e02f657b?source=rss-a3fffc06f107------2</link>
            <guid isPermaLink="false">https://medium.com/p/d904e02f657b</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Basith]]></dc:creator>
            <pubDate>Sun, 10 Sep 2023 09:47:27 GMT</pubDate>
            <atom:updated>2023-09-10T09:47:27.665Z</atom:updated>
            <content:encoded><![CDATA[<h4>A deep and thorough comprehension of classification algorithms within the world of machine learning.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6o_1y5nxoWv5MEjk" /></figure><p>Machine learning is the science (and art) of programming computers so they can learn from data.</p><blockquote>[Machine learning is the] field of study that gives computers the ability to learn without being explicitly programmed. — Arthur Samuel, 1959.</blockquote><p>A better definition:</p><blockquote>A computer program is said to learn from experience E with respect to some task T and some performance measure P, if its performance on T, as measured by P, improves with experience E. — Tom Mitchell, 1997.</blockquote><p>For example, your spam filter is a machine learning program that can learn to flag spam after being given examples of spam emails that are flagged by users, and examples of regular non-spam (also called “ham”) emails. The examples the system uses to learn are called the <strong>training set</strong>. In this case, the task (<em>T</em>) is to flag spam for new emails, the experience (<em>E</em>) is the training data, and the performance measure (<em>P</em>) needs to be defined. For example, you can use the ratio of correctly classified emails as <em>P</em>. This particular performance measure is called accuracy and it is often used in classification tasks as it is a supervised learning approach.</p><h3>Supervised Machine Learning Classification</h3><p>In supervised machine learning, algorithms learn from labeled data. After understanding the data, the algorithm determines which label should be given to new data by associating patterns to the unlabeled new data.</p><p>Supervised learning can be divided into two categories: <strong>classification </strong>and <strong>regression</strong>.</p><blockquote><strong>Classification</strong></blockquote><blockquote>Classification predicts the category the data belongs to. Some examples of classification include spam detection, churn prediction, sentiment analysis, dog breed detection, and so on.</blockquote><blockquote><strong>Regression</strong></blockquote><blockquote>Regression predicts a numerical value based on previously observed data. Some examples of regression include house price prediction, stock price prediction, height-weight prediction, and so on.</blockquote><h3>Five Types of Classification Algorithms for Machine Learning</h3><p>Classification is a technique for determining which class the dependent belongs to based on one or more independent variables.</p><blockquote>WHAT IS A CLASSIFIER?</blockquote><blockquote>A classifier is a type of machine learning algorithm that assigns a label to a data input. Classifier algorithms use labeled data and statistical methods to produce predictions about data input classifications.</blockquote><blockquote><em>Classification is used for predicting discrete responses.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*Ly3T5-t96E6llWp4.png" /></figure><h3>1. Logistic Regression</h3><p>Logistic regression is kind of like linear regression but is used when the dependent variable is not a number but something else (e.g., a “yes/no” response). It’s called regression but performs classification based on the regression and it classifies the dependent variable into either of the classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*bt-bq_KIVzSDTtUD.png" /></figure><p>Logistic regression is used for prediction of output which is <a href="https://builtin.com/software-engineering-perspectives/binary">binary</a>, as stated above. For example, if a credit card company builds a model to decide whether or not to issue a credit card to a customer, it will model for whether the customer is going to “default” or “not default” on their card.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/0*CccY5IigL9D3di5p.png" /></figure><p>Firstly, linear regression is performed on the relationship between variables to get the model. The threshold for the classification line is assumed to be at 0.5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/0*UcGbnQNd4Kn1ZRkn.png" /></figure><p>A logistic function is applied to the regression to get the probabilities of it belonging to either class.</p><p>It gives the log of the probability of the event occurring to the log of the probability of it not occurring. In the end, it classifies the variable based on the higher probability of either class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*oATqYo_2kUIhWr7h.png" /></figure><h3>2. K-Nearest Neighbors (K-NN)</h3><p>K-NN algorithm is one of the simplest classification algorithms and it is used to identify the data points that are separated into several classes to predict the classification of a new sample point. K-NN is a non-parametric<strong>, </strong>lazy learning algorithm. It classifies new cases based on a similarity measure (i.e., distance functions).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*ObNi1Y6fO6vw39zr.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*xNRJQFu12BcdEhmp.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*vRBGJuWIOlpaXSSM.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*3qEPnIRVvtyF1Zuc.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*kCrPaOkoYvEdcbQn.png" /></figure><p>K-NN works well with a small number of input variables (<em>p</em>), but struggles when the number of inputs is very large.</p><h3>3. Support Vector Machine (SVM)</h3><p>A support vector is used for both regression and classification. It is based on the concept of decision planes that define decision boundaries. A decision plane (hyperplane) is one that separates between a set of objects having different class memberships.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*lJesypWeR9xdKdA_.png" /></figure><p>It performs classification by finding the hyperplane that maximizes the margin between the two classes with the help of support vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*adttAunuGk-LXq5F.png" /></figure><p>The learning of the hyperplane in SVM is done by transforming the problem using some linear algebra (i.e., the example above is a linear kernel which has a linear separability between each variable).</p><p>For higher dimensional data, other kernels are used as points and cannot be classified easily. They are specified in the next section.</p><h4>Kernel SVM</h4><p>Kernel SVM takes in a kernel function in the SVM algorithm and transforms it into the required form that maps data on a higher dimension which is separable.</p><p>Types of kernel functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/0*4VRTQcniA6SZhpYK.gif" /></figure><blockquote>1. Linear SVM is the one we discussed earlier.</blockquote><blockquote>2. In a polynomial kernel, the degree of the polynomial should be specified. It allows for curved lines in the input space.</blockquote><blockquote>3, In the radial basis function (RBF) kernel, it is used for non-linearly separable variables. For distance, metric squared Euclidean distance is used. Using a typical value of the parameter can lead to overfitting our data. It is used by default in sklearn.</blockquote><blockquote>4. Sigmoid kernel, similar to logistic regression is used for binary classification.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*aKqub5cM-kdhNEO_.png" /></figure><p>Kernel trick uses<em> </em>the kernel function to transform data into a higher dimensional feature space and makes it possible to perform the linear separation for classification.</p><p><strong>Radial Basis Function (RBF) Kernel</strong></p><p>The RBF kernel SVM decision region is actually also a linear decision region. What RBF kernel SVM actually does is create non-linear combinations of features to uplift the samples onto a higher-dimensional feature space where a linear decision boundary can be used to separate classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*971nyImQV7J5WM74.png" /></figure><p>So, the rule of thumb is: use linear SVMs for linear problems, and nonlinear kernels such as the RBF kernel for non-linear problems.</p><h3>4. Naive Bayes</h3><p>The naive Bayes classifier is based on Bayes’ theorem with the independence assumptions between predictors (i.e., it assumes the presence of a feature in a class is unrelated to any other feature). Even if these features depend on each other, or upon the existence of the other features, all of these properties independently. Thus, the name naive Bayes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*35UWAFJzKbvWI8z2.png" /></figure><p>Based on naive Bayes, Gaussian naive Bayes is used for classification based on the binomial (normal) distribution of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*E_UzoNgj4X136qH-.png" /></figure><blockquote><em>P(class|data)</em> is the posterior probability of <em>class</em>(<em>target</em>) given <em>predictor</em>(<em>attribute</em>). The probability of a data point having either class, given the data point. This is the value that we are looking to calculate.</blockquote><blockquote><em>P(class)</em> is the prior probability of <em>class</em>.</blockquote><blockquote><em>P(data|class)</em> is the likelihood, which is the probability of <em>predictor</em> given <em>class</em>.</blockquote><blockquote><em>P(data)</em> is the prior probability of <em>predictor or marginal likelihood</em>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/0*TxVfitDuKl8sP5nT.png" /></figure><h4>Naive Bayes Steps</h4><p><strong>1. Calculate Prior Probability</strong></p><p><em>P(class) </em>= Number of data points in the class/Total no. of observations</p><p><em>P(yellow) </em>= 10/17</p><p><em>P(green)</em> = 7/17</p><p><strong>2. Calculate Marginal Likelihood</strong></p><p><em>P(data) </em>= Number of data points similar to observation/Total no. of observations</p><p><em>P(?) </em>= 4/17</p><p>The value is present in checking both the probabilities.</p><p><strong>3. Calculate Likelihood</strong></p><p><em>P(data/class) </em>= Number of similar observations to the class/Total no. of points in the class.</p><p><em>P(?/yellow) </em>= 1/7</p><p><em>P(?/green) </em>= 3/10</p><p><strong>4. Posterior Probability for Each Class</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/0*RU9njQL0ds_skp0w.png" /></figure><p><strong>5. Classification</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/0*ENTTiFeeWpjVAOKZ.png" /></figure><p>The higher probability, the class belongs to that category as from above 75% probability the point belongs to class green.</p><p>Multinomial and Bernoulli naive Bayes are the other models used in calculating probabilities. Thus, a naive Bayes model is easy to build, with no complicated iterative parameter estimation, which makes it particularly useful for very large datasets.</p><h3>5. Decision Tree Classification</h3><p>Decision tree builds classification or regression models in the form of a tree structure. It breaks down a dataset into smaller and smaller subsets while at the same time, an associated decision tree is incrementally developed. The final result is a tree with decision nodes and leaf nodes. It follows the Iterative Dichotomiser 3 (ID3) algorithm structure for determining the split.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*gOLH_cM4IAVpIx4h.png" /></figure><p>Entropy and information gain are used to construct a decision tree.</p><h4>Entropy</h4><p>Entropy is the degree or amount of uncertainty in the randomness of elements. In other words, it is a measure of impurity<strong><em>.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/0*8ZT-XR0ghxn-3jdW.png" /></figure><p>Intuitively, it tells us about the predictability of a certain event. Entropy calculates the homogeneity of a sample. If the sample is completely homogeneous the entropy is zero, and if the sample is equally divided it has an entropy of one.</p><h4>Information Gain</h4><p>Information gain measures the relative change in entropy with respect to the independent attribute. It tries to estimate the information contained in each attribute. Constructing a decision tree is all about finding the attribute that returns the highest information gain (i.e., the most homogeneous branches).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/0*HR9oEigpbbEmQA_H.png" /></figure><p>Where <em>Gain(T, X)</em> is the information gain by applying feature <em>X</em>. <em>Entropy(T)</em> is the entropy of the entire set, while the second term calculates the entropy after applying the feature <em>X</em>.</p><p>Information gain ranks attributes for filtering at a given node in the tree. The ranking is based on the highest information gain entropy in each split.</p><p>The disadvantage of a decision tree model is overfitting, as it tries to fit the model by going deeper in the training set thereby reducing test accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*A_XWokReZnJfgQ9J.png" /></figure><p>Overfitting in decision trees can be minimized by pruning nodes.</p><h3>Ensemble Methods for Classification</h3><p>An ensemble model is a <em>team of models</em>. Technically, ensemble models comprise several supervised learning models that are individually trained and the results are merged in various ways to achieve the final prediction. This result has higher predictive power than the results of any of its constituting learning algorithms independently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*83JM7qDJARl3pT9U.png" /></figure><h3>1. Random Forest Classification</h3><p>Random forest classifier is an ensemble algorithm based on bagging i.e. bootstrap aggregation. Ensemble methods<em> </em>combine more than one algorithm of the same or different kind for classifying objects (i.e., an ensemble of SVM, naive Bayes, or decision trees, for example.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*62hIa-g1SVRS5kD5.png" /></figure><p>The general idea is that a combination of learning models increases the overall result selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*y_z4qR8Wn62q4kxO.png" /></figure><p>Deep decision trees may suffer from overfitting, but random forests prevent overfitting by creating trees on random subsets. The main reason is that it takes the average of all the predictions, which cancels out the biases.</p><p>Random forest adds additional randomness to the model while growing the trees. Instead of searching for the most important feature while splitting a node, it searches for the best feature among a random subset of features. This results in a wide diversity that generally results in a better model.</p><h3>2. Gradient Boosting Classification</h3><p>The gradient boosting classifier is a boosting ensemble method. Boosting is a way to combine (ensemble) weak learners, primarily to reduce prediction bias. Instead of creating a pool of predictors, as in bagging, boosting produces a cascade of them, where each output is the input for the following learner. Typically, in a bagging algorithm, trees are grown in parallel to get the average prediction across all trees, where each tree is built on a sample of original data. Gradient boosting, on the other hand, takes a sequential approach to obtaining predictions instead of parallelizing the tree-building process. In gradient boosting, each decision tree predicts the error of the previous decision tree — thereby <em>boosting</em> (improving) the error (gradient).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*gt813zicoLqxg_XY.png" /></figure><blockquote><strong>Working of Gradient Boosting</strong></blockquote><blockquote>1. Initialize predictions with a simple decision tree.</blockquote><blockquote>2. Calculate residual (actual-prediction) value.</blockquote><blockquote>3. Build another shallow decision tree that predicts residual based on all the independent values.</blockquote><blockquote>4. Update the original prediction with the new prediction multiplied by learning rate.</blockquote><blockquote>5. Repeat steps two through four for a certain number of iterations (the number of iterations will be the number of trees).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/0*8xTbF2F6Z8oChIdM.png" /></figure><p>In a nutshell, this article has been your guide to the wild world of classification algorithms in machine learning. We’ve explored five trusty companions on your machine learning journey: <strong>Logistic Regression</strong> (the “yes/no” detective), <strong>K-Nearest Neighbors</strong> (your friendly neighbor for data advice), <strong>Support Vector Machine</strong> (the bouncer of data parties), <strong>Naive Bayes</strong> (the Bayesian brainiac), and <strong>Decision Trees</strong> (the branching storytellers).</p><p>We’ve even thrown in some fun with entropy and information gain — think of them as the spice that makes your data stew more flavorful. And to top it off, we’ve introduced you to the dynamic duo of Random Forest and Gradient Boosting, the superheroes of ensemble methods.</p><p>Now, armed with these algorithms, you’re ready to conquer the machine learning jungle, one classification conundrum at a time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d904e02f657b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Top 10 Machine Learning Algorithms Every Beginner Should Know!]]></title>
            <link>https://muhammedbasith.medium.com/the-top-10-machine-learning-algorithms-every-beginner-should-know-ee48bdf080fe?source=rss-a3fffc06f107------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee48bdf080fe</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[trends]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Basith]]></dc:creator>
            <pubDate>Sun, 27 Aug 2023 14:39:52 GMT</pubDate>
            <atom:updated>2023-08-27T14:39:52.831Z</atom:updated>
            <content:encoded><![CDATA[<p>These algorithms can help you learn how to use machine learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K0OIjlnaREhU-W2w" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the realm of machine learning, we encounter the intriguing “No Free Lunch” theorem. In essence, this theorem underscores the reality that no single machine learning algorithm can reign supreme across all possible problems. This notion holds especially true in the context of supervised learning, where the main objective is to create predictive models.</p><p>In simpler terms, claiming that a particular algorithm — let’s say neural networks — will always outperform others like decision trees, is an oversimplification. The interplay of diverse factors, including the nuances of the dataset’s size and structure, comes into play. This dynamic signifies that the efficacy of any algorithm hinges on the unique characteristics of the specific problem at hand. As a result, you should try many different algorithms for your problem, while using a hold-out “test set” of data to evaluate performance and select the winner.</p><p>Of course, the algorithms you try must be appropriate for your problem, which is where picking the right machine-learning task comes in. As an analogy, if you need to clean your house, you might use a vacuum, a broom, or a mop, but you wouldn’t bust out a shovel and start digging.</p><h3>THE BIG PRINCIPLE BEHIND MACHINE LEARNING ALGORITHMS</h3><p>However, there is a common principle that underlies all supervised machine learning algorithms for predictive modeling.</p><p><em>Machine learning algorithms are described as learning a target function (f) that best maps input variables (X) to an output variable (Y): </em><strong><em>Y = f(X)</em></strong></p><p>This is a general learning task where we would like to make predictions in the future (Y) given new examples of input variables (X). We don’t know what the function (f) looks like or its form. If we did, we would use it directly and we would not need to learn it from data using machine learning algorithms.</p><p>The most common type of machine learning is to learn the mapping Y = f(X) to make predictions of Y for new X. This is called predictive modeling or predictive analytics and our goal is to make the most accurate predictions possible.</p><h3>Most Common Machine Learning Algorithms</h3><p>For machine learning newbies who are eager to understand the basics and to grasp the fundamentals of machine learning, here’s a rapid overview of the ten key machine learning algorithms frequently employed by data scientists.</p><ul><li>Linear Regression</li><li>Logistic Regression</li><li>Linear Discriminant Analysis</li><li>Classification and Regression Trees</li><li>Naive Bayes</li><li>K-Nearest Neighbors (KNN)</li><li>Learning Vector Quantization (LVQ)</li><li>Support Vector Machines (SVM)</li><li>Random Forest</li><li>Boosting</li><li>AdaBoost</li></ul><p>So, let me throw this question right back at you: do these algo’s ring a bell, or are they venturing into uncharted territory? If it’s the latter, well, it seems like there’s a whole world of discovery waiting for you. But fret not! Rest assured, I’m considering treating you to a simplified overview of all these algorithms on a different day. Until then, here’s to an enriching journey of learning! Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee48bdf080fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>