<?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 Hasini Rathnayaka on Medium]]></title>
        <description><![CDATA[Stories by Hasini Rathnayaka on Medium]]></description>
        <link>https://medium.com/@hasinichamodi4?source=rss-1c46a17551d0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*phhlzdWzbzqOoZc_zWzGiQ.jpeg</url>
            <title>Stories by Hasini Rathnayaka on Medium</title>
            <link>https://medium.com/@hasinichamodi4?source=rss-1c46a17551d0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:58:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hasinichamodi4/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[Understanding Web Authentication: Basic Auth, JWT, OAuth, Cookies, OIDC & SAML]]></title>
            <link>https://medium.com/@hasinichamodi4/understanding-web-authentication-basic-auth-jwt-oauth-cookies-oidc-saml-d3c3a00d5f5f?source=rss-1c46a17551d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3c3a00d5f5f</guid>
            <dc:creator><![CDATA[Hasini Rathnayaka]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 17:18:14 GMT</pubDate>
            <atom:updated>2026-07-19T17:18:14.547Z</atom:updated>
            <content:encoded><![CDATA[<p>Every web app eventually needs to answer the same two questions: <em>who are you</em>, and <em>are you allowed to do this?</em> The first question is authentication. The second is authorization. They sound similar, but they’re different problems — and the tools for solving them are different too.</p><p>There are seven main approaches you’ll run into in the real world. They’re not competing alternatives where you pick one and ignore the rest. They’re more like a toolkit — some you’ll use daily, some only in specific situations, and some only when connecting to enterprise systems. Here’s how each one actually works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PNoMQoUi57S2g7-OzDWXDg.png" /></figure><h3>The Simplest Starting Point: Basic Authentication</h3><p>Basic Auth is the oldest and most straightforward approach. When you make a request, you attach your username and password — base64 encoded — in a header. The server decodes it, checks the credentials, and either lets you in or rejects you.</p><p>That’s it. No tokens, no sessions, no handshakes. Every single request carries the credentials directly.</p><pre>Authorization: Basic dXNlcjpwYXNzd29yZA==</pre><p>The string after “Basic” is just user:password run through base64 — it&#39;s encoding, not encryption. Anyone who intercepts the request can decode it in seconds. This is why Basic Auth only makes sense over HTTPS, and even then it&#39;s mostly used for internal tools, simple scripts, or API clients where simplicity matters more than complexity.</p><p>In production consumer apps, you almost never reach for Basic Auth. But knowing how it works matters because everything more sophisticated is built on top of the same idea: attach proof of identity to the request.</p><h3>The Upgrade: Token Authentication</h3><p>Token Auth solves the biggest problem with Basic Auth — you stop sending credentials on every request. Instead, the flow works like a concert wristband:</p><ol><li>You log in once with your username and password.</li><li>The server verifies them and gives you a token — a long, opaque string.</li><li>From that point on, every request carries the token instead of the password.</li></ol><pre>Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...</pre><p>The server stores a record of valid tokens. When a request comes in with one, it looks it up, finds who it belongs to, and lets them through. When you log out, the server deletes the token — immediately and completely, with no ambiguity.</p><p>Token Auth gives you clean revocation (log someone out and their token stops working instantly), multiple active sessions (a phone and laptop can each have their own token), and better security than sending a password every time. It’s the basis for most modern API authentication.</p><h3>The Browser’s Approach: Cookie Based Auth</h3><p>For web browsers specifically, cookies give you something token auth doesn’t: automatic credential handling. You don’t have to write code to attach the token to every request — the browser does it for you.</p><p>The flow is similar to token auth at a high level. You log in, the server creates a session, and it sets a cookie in your browser containing a session ID. On every subsequent request to that domain, the browser automatically includes the cookie. The server looks up the session ID, finds who you are, and continues.</p><pre>Set-Cookie: session_id=abc123; HttpOnly; Secure; SameSite=Strict</pre><p>Those flags matter. HttpOnly means JavaScript on the page can&#39;t read the cookie — it&#39;s only sent in HTTP requests. Secure means it only travels over HTTPS. SameSite=Strict prevents the cookie from being sent on cross-site requests, which blocks a whole class of CSRF attacks.</p><p>Cookie-based auth is the default for traditional web apps — login forms, dashboards, anything where the browser is doing the navigating. It’s session-based and stateful: the server stores session data and the client just holds a reference to it. When you log out, the server destroys the session.</p><h3>The Token That Explains Itself: JWT</h3><p>JSON Web Tokens are the point where things get interesting. A JWT isn’t just an opaque identifier that the server looks up — it <em>contains</em> the information about the user, signed so nobody can tamper with it.</p><p>A JWT has three parts, separated by dots:</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.   ← Header (algorithm used)<br>eyJ1c2VySWQiOiIxMjMiLCJyb2xlIjoiYWRtaW4ifQ.   ← Payload (the data)<br>SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c   ← Signature (proof of integrity)</pre><p>The payload contains claims — things like user ID, role, email, and an expiry timestamp. The signature is created using a secret key only the server knows. Anyone can read the payload (it’s just base64), but nobody can change it without invalidating the signature.</p><p>This changes something fundamental about how servers work. With cookie sessions, the server has to store session data somewhere and look it up on every request. With JWTs, the server doesn’t store anything — it just verifies the signature. The token is self-contained. This makes JWTs a natural fit for distributed systems where you have multiple services and don’t want them all hitting a shared session store.</p><p>The tradeoff is revocation. If you issue a JWT that expires in an hour, you can’t easily “cancel” it before that — the token is valid until it expires. This is why JWTs work best for short-lived access tokens. Refresh tokens (longer-lived, stored server-side) handle the renewal cycle.</p><h3>Letting Someone Else Handle Login: OAuth</h3><p>OAuth isn’t really authentication — it’s authorization. The subtle distinction matters.</p><p>Authentication answers: <em>who are you?</em><br> Authorization answers: <em>what are you allowed to do?</em></p><p>OAuth was designed to answer the second question in a specific scenario: letting one application act on your behalf in another application, without giving it your password.</p><p>When you click “Connect with Google” inside some third-party app, you’re using OAuth. The flow:</p><ol><li>The app redirects you to Google’s login page.</li><li>You log in at Google (never at the app — they never see your password).</li><li>Google asks you: “This app wants to read your contacts and calendar. Allow?”</li><li>If you say yes, Google gives the app a limited access token.</li><li>The app uses that token to make API calls to Google on your behalf.</li></ol><pre>GET https://accounts.google.com/o/oauth2/auth<br>  ?client_id=YOUR_APP_ID<br>  &amp;redirect_uri=https://yourapp.com/callback<br>  &amp;scope=email profile<br>  &amp;response_type=code</pre><p>The key word is scope — OAuth lets you grant specific, limited access. The app can read your contacts but can&#39;t read your Gmail or change your password. If you revoke access later, the token stops working.</p><p>OAuth is what powers every third-party integration you’ve ever used. It’s also the foundation that OpenID Connect is built on.</p><h3>Who Are You, Actually: OpenID Connect</h3><p>OpenID Connect (often called OIDC) takes OAuth and adds the one thing OAuth was never designed to do: tell the app who you are.</p><p>OAuth gives the app a token to access resources. But the app still doesn’t know anything about <em>you</em> from that token alone. OpenID Connect adds a second token — the ID token — that contains verified identity information: your name, email, profile picture, and a unique identifier for your account.</p><p>This is what powers “Sign in with Google” or “Sign in with GitHub.” The flow looks like OAuth, but the purpose is authentication: proving who you are to the app, using an identity provider you already trust.</p><pre>{<br>  &quot;sub&quot;: &quot;1234567890&quot;,<br>  &quot;name&quot;: &quot;Alex Smith&quot;,<br>  &quot;email&quot;: &quot;alex@example.com&quot;,<br>  &quot;iss&quot;: &quot;https://accounts.google.com&quot;,<br>  &quot;exp&quot;: 1716239022<br>}</pre><p>The iss field tells you who issued this token (the identity provider). The sub is the unique user ID. The exp is when it expires.</p><p>OIDC is the protocol behind most modern “Login with X” buttons. It’s built on OAuth’s infrastructure, so if you already have OAuth set up, adding OIDC is straightforward.</p><h3>The Enterprise Standard: SAML</h3><p>SAML (Security Assertion Markup Language) is the older, XML-based protocol that enterprise systems use for single sign-on. Where OIDC is the modern web standard, SAML is the corporate IT standard — and both exist in the world simultaneously.</p><p>The scenario SAML was designed for: a large company with dozens of internal applications, and employees who should be able to log in once (at the company’s identity provider — Active Directory, Okta, Azure AD) and access all of them without logging in again. That’s Single Sign-On, or SSO.</p><p>The flow has three players:</p><ul><li><strong>User</strong> — the employee trying to access an app</li><li><strong>Identity Provider (IdP)</strong> — the company’s auth system (Okta, ADFS, Azure AD)</li><li><strong>Service Provider (SP)</strong> — the app the employee wants to use (Salesforce, Slack, your internal HR system)</li></ul><pre>User → tries to access Salesforce (SP)<br>Salesforce → redirects to Okta (IdP) with a SAML Request<br>User → logs in at Okta<br>Okta → sends a signed SAML Assertion (XML) back to Salesforce<br>Salesforce → trusts the assertion, lets the user in</pre><p>The assertion is a signed XML document that says: “I, Okta, confirm that this person is who they say they are, their email is alex@company.com, and their role is Sales Manager.” The service provider trusts this because the assertion is signed with a certificate it already has.</p><p>SAML is verbose and XML-heavy — not something you’d build from scratch in a modern greenfield app. But if you’re integrating with any large enterprise, there’s a good chance they’re going to ask for SAML SSO. Knowing what it is and how it works is important even if you never write the XML yourself.</p><h3>How They All Fit Together</h3><p>These seven approaches aren’t at odds with each other. Most real applications use several simultaneously.</p><p>A typical modern web app might use <strong>Cookie Auth</strong> for the main browser sessions, <strong>JWTs</strong> as short-lived access tokens for API requests, <strong>OAuth + OIDC</strong> so users can sign in with Google, and <strong>SAML</strong> to support enterprise customers who need SSO with their identity provider.</p><p>The foundation underneath all of it is the same: prove who you are, get issued proof you can carry, present that proof on every subsequent request. Basic Auth just sends the proof directly. Token Auth and Cookies abstract it behind a session or token. JWT makes the proof self-describing. OAuth and OIDC federate the proof to a trusted third party. SAML does the same thing for enterprise environments.</p><p>Once you see that thread running through all of them, each one clicks into place as a variation on the same core idea — not seven separate things to memorize, but seven different answers to the same question.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3c3a00d5f5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Web Servers: Nginx, Apache, Caddy, and IIS Explained]]></title>
            <link>https://medium.com/@hasinichamodi4/understanding-web-servers-nginx-apache-caddy-and-iis-explained-e9cdd9b0e79c?source=rss-1c46a17551d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9cdd9b0e79c</guid>
            <dc:creator><![CDATA[Hasini Rathnayaka]]></dc:creator>
            <pubDate>Fri, 26 Jun 2026 11:19:07 GMT</pubDate>
            <atom:updated>2026-06-26T11:19:07.233Z</atom:updated>
            <content:encoded><![CDATA[<p>Every time you open a website, something on the other end is listening. You type a URL, your browser fires off a request across the internet, and somewhere a piece of software receives that request, figures out what you’re asking for, and sends something back. That software is a web server.</p><p>It sounds simple, and at its core it is. But web servers also handle things that get complicated fast — thousands of simultaneous connections, SSL certificates, routing requests to the right application, serving files efficiently, logging everything. The four you’ll encounter in the real world — Nginx, Apache, Caddy, and IIS — each have a different philosophy for how to handle all of that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ffnqgJfWTJF2H6eikvQug.png" /></figure><h3>What a Web Server Actually Does</h3><p>Before getting into the specific tools, it helps to be clear on what a web server’s job actually is.</p><p>When your browser wants a webpage, it sends an HTTP request: “GET this URL.” The web server receives that, decides what to do with it, and sends back an HTTP response: usually an HTML page, a file, an image, a JSON payload — whatever was asked for.</p><p>That’s the core. Everything else — caching, compression, authentication, SSL termination, load balancing — is layered on top of that core loop.</p><p>In production, a web server rarely runs alone. It usually sits in front of your application — a Node.js server, a Django app, a Rails API — acting as a reverse proxy. The browser talks to the web server, the web server passes the request to your application, the application produces a response, and the web server sends that response back to the browser. This separation means the web server handles the network-level concerns (connections, TLS, compression) while your application handles the business logic.</p><h3>Nginx: Built for Scale</h3><p>Nginx (pronounced “engine-x”) was built specifically to solve a problem that Apache had in the early 2000s: handling tens of thousands of simultaneous connections without collapsing.</p><p>The old approach — the one Apache used by default — was to spawn a new process or thread for each incoming connection. Works fine with a few hundred connections. Starts buckling under the weight of thousands, because each process or thread consumes memory and the system spends more time switching between them than doing actual work.</p><p>Nginx took a different approach: a single-threaded, event-driven model. Instead of one thread per connection, Nginx uses a small number of worker processes, each handling thousands of connections by cycling through them — checking who has data ready, processing it, moving on. No waiting around. No idle threads burning memory.</p><pre>server {<br>    listen 80;<br>    server_name example.com;</pre><pre>    location / {<br>        proxy_pass <a href="http://localhost:3000;">http://localhost:3000;</a><br>    }</pre><pre>    location /static/ {<br>        root /var/www;<br>        expires 1y;<br>    }<br>}</pre><p>This config does two things: requests to / get forwarded to a Node.js app running on port 3000, and requests to /static/ get served directly as files with a one-year cache header. The separation between &quot;serve files&quot; and &quot;proxy to app&quot; is exactly the kind of work Nginx does well.</p><p>Today Nginx is probably the most widely deployed web server on the internet. It’s the default choice for high-traffic production systems, particularly for Linux-based infrastructure. It’s also commonly used just as a reverse proxy or load balancer in front of other services, without serving any files at all.</p><p>The config syntax takes some getting used to. Nginx configuration is powerful but terse — a single misconfigured block can route traffic somewhere unexpected. The mental model is: you define server blocks, and within those, location blocks that match URL patterns and specify what to do with matching requests.</p><h3>Apache: The Old Reliable</h3><p>Apache has been around since 1995. For most of the web’s history, when people said “web server” they meant Apache. It’s still widely used, particularly in shared hosting environments and among teams that have been running it for years and built a lot of institutional knowledge around it.</p><p>Apache’s defining feature — and where it differs most from Nginx — is .htaccess. This is a per-directory configuration file that Apache checks on every request. It lets anyone with access to a directory change how Apache handles requests for files in that directory, without touching the main server config. For shared hosting, this is powerful: one server, thousands of different customers, each controlling their own configuration.</p><pre>RewriteEngine On<br>RewriteCond %{REQUEST_FILENAME} !-f<br>RewriteRule ^(.*)$ index.php [QSA,L]</pre><p>This .htaccess snippet tells Apache: if the requested file doesn&#39;t exist on disk, route the request to index.php instead. This is the classic setup for PHP applications — WordPress, Laravel, Drupal — which is a big reason Apache is still so dominant in the shared hosting world.</p><p>Apache has a massive ecosystem of modules — mod_rewrite for URL rewriting, mod_ssl for HTTPS, mod_php for embedded PHP execution, hundreds more. You enable the ones you need, and they load into the server.</p><p>The tradeoff is performance at high concurrency. Apache’s default process/thread-per-request model means it can struggle under very high load in a way Nginx doesn’t. Apache has an async event-driven MPM (Multi-Processing Module) that improves this, but Nginx still has a reputation as the faster choice for raw connection handling.</p><h3>Caddy: The Modern Newcomer</h3><p>Caddy came out in 2015 and was designed from the ground up to solve the things that frustrated people about Nginx and Apache. Its headline feature: automatic HTTPS. Out of the box, with no additional configuration, Caddy provisions TLS certificates via Let’s Encrypt and renews them automatically.</p><p>In 2015 this was remarkable. Getting HTTPS working on Nginx or Apache involved installing Certbot, configuring it, setting up a renewal cron job, testing that it worked, and hoping nothing rotted over time. Caddy just does it.</p><pre>example.com {<br>    reverse_proxy localhost:3000<br>}</pre><p>That’s a complete, production-ready Caddy config. HTTPS is on. Certificate is managed. Requests are proxied to port 3000. The simplicity is intentional — Caddy’s Caddyfile format is designed to be human-readable and opinionated enough that most things just work without hunting for the right combination of directives.</p><p>Caddy also has a full HTTP API for configuration changes, which makes it popular in environments where you want to reconfigure the server dynamically without reloading config files or restarting processes.</p><p>The tradeoff is community size. Nginx and Apache have decades of Stack Overflow answers, tutorials, and production war stories behind them. Caddy’s ecosystem is smaller, and if you hit an unusual edge case, you’re more likely to be navigating the documentation alone. For teams starting fresh on infrastructure today, Caddy is worth serious consideration. For teams with existing Nginx or Apache setups, the switching cost is rarely justified just for cleaner syntax.</p><h3>Microsoft IIS: The Windows Server</h3><p>IIS — Internet Information Services — is Microsoft’s web server, bundled with Windows Server. If your organization runs a Windows-based backend, particularly if you’re using .NET, ASP.NET, or C#, there’s a good chance IIS is or has been part of your stack.</p><p>IIS integrates deeply with the Windows ecosystem. Authentication via Active Directory, centralized management through Windows Server tools, tight coupling with .NET runtime hosting, and a GUI-based configuration interface through IIS Manager — all of these make it the natural choice for enterprises that have standardized on Microsoft infrastructure.</p><pre>&lt;configuration&gt;<br>  &lt;system.webServer&gt;<br>    &lt;rewrite&gt;<br>      &lt;rules&gt;<br>        &lt;rule name=&quot;Redirect to HTTPS&quot; stopProcessing=&quot;true&quot;&gt;<br>          &lt;match url=&quot;(.*)&quot; /&gt;<br>          &lt;conditions&gt;<br>            &lt;add input=&quot;{HTTPS}&quot; pattern=&quot;^OFF$&quot; /&gt;<br>          &lt;/conditions&gt;<br>          &lt;action type=&quot;Redirect&quot; url=&quot;https://{HTTP_HOST}/{R:1}&quot; /&gt;<br>        &lt;/rule&gt;<br>      &lt;/rules&gt;<br>    &lt;/rewrite&gt;<br>  &lt;/system.webServer&gt;<br>&lt;/configuration&gt;</pre><p>IIS config lives in XML files (the web.config above handles an HTTPS redirect). The XML syntax is verbose compared to Nginx or Caddyfile, but IIS Manager provides a GUI on top of it so you can configure most things without writing XML directly.</p><p>IIS runs on Windows only. If your infrastructure is Linux — which most modern cloud deployments are — IIS isn’t an option. It’s not a limitation of quality; it’s a platform decision. IIS on Windows Server hosting ASP.NET apps is a well-understood, production-proven stack used at scale by large enterprises. It just doesn’t translate to non-Windows environments.</p><h3>How to Think About Choosing</h3><p>The choice usually isn’t as difficult as it sounds, because the options narrow themselves quickly based on your situation.</p><p>If you’re on Linux and starting from scratch, Nginx is the safe default. It handles high concurrency well, has excellent documentation, and the community knowledge behind it is enormous. Start here unless you have a specific reason not to.</p><p>If you’re running PHP applications on shared hosting, or inheriting an existing setup, Apache is probably already there. Its .htaccess system and module ecosystem are still genuinely useful, and there&#39;s no strong reason to migrate away from a working setup.</p><p>If you want HTTPS to just work without configuration ceremony, or you’re building a modern service where clean config matters and you’re okay with a smaller community, Caddy is worth trying. It’s particularly good for development environments and smaller production deployments.</p><p>If you’re in a Microsoft-standardized environment running .NET applications on Windows, IIS is the right tool. The deep Windows integration is exactly what you want in that context.</p><h3>The Core Idea to Remember</h3><p>A web server’s job is to sit at the edge of your infrastructure and handle the conversation between the internet and your application. It receives raw HTTP connections, decodes what’s being asked for, decides where to route it, and sends back the response.</p><p>Nginx, Apache, Caddy, and IIS all do this job. They differ in how they handle concurrency, what they make easy by default, what ecosystem they belong to, and what trade-offs they’ve made in design. Understanding those differences is what lets you pick the right one — or recognize which one you’ve inherited — and configure it with confidence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9cdd9b0e79c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Caching: Redis, Memcached, and HTTP Caching Explained]]></title>
            <link>https://medium.com/@hasinichamodi4/understanding-caching-redis-memcached-and-http-caching-explained-72c9e3f2bf5a?source=rss-1c46a17551d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/72c9e3f2bf5a</guid>
            <dc:creator><![CDATA[Hasini Rathnayaka]]></dc:creator>
            <pubDate>Fri, 26 Jun 2026 11:06:44 GMT</pubDate>
            <atom:updated>2026-06-26T11:19:53.064Z</atom:updated>
            <content:encoded><![CDATA[<p>Picture a chef who cooks a dish, and then every time someone orders the same thing, they go back and cook the entire thing from scratch — chopping, seasoning, timing, plating — even though the dish on the table five minutes ago was identical. That’s what an app does when it recalculates or re-fetches the same data on every single request. It’s expensive, it’s slow, and it’s completely unnecessary.</p><p>Caching is the chef keeping a tray of pre-made dishes warm on the counter. The next person who orders gets their food in seconds. The kitchen stays calm. The oven gets a break.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6CPy_qvtgB2F-y8ofckXLg.png" /></figure><p>At its core, caching means storing the result of something expensive — a database query, an API call, a computed value — so the next request can get the answer instantly, without doing the work again. The challenge is knowing <em>what</em> to store, <em>where</em> to store it, and <em>when</em> to throw it away. Get those three right, and a slow app can become a fast one without touching a single line of business logic.</p><h3>The Problem Caching Solves</h3><p>Every time a user loads a page, your app typically asks the database for data. If 10 people load the same page at once, that’s 10 identical queries going to the database. If it’s a popular product page with 10,000 users, it’s 10,000 identical queries — all fetching the same rows, running the same joins, returning the same result.</p><p>Databases are not cheap to query. Each query takes time, uses CPU, holds connection slots, and competes with every other query happening simultaneously. At scale, this becomes the bottleneck that everything else waits behind.</p><p>The data being fetched also doesn’t change that often. A product’s name, price, and description probably doesn’t change between one request and the next. If you can store that result somewhere fast and serve it from there, you can take the database almost entirely out of the picture for that data.</p><p>That’s the core of caching: the first request does the work, everyone else gets the result.</p><h3>Server-Side Caching: Storing Results Close to Your App</h3><p>Server-side caching happens in memory on your server infrastructure — between your application and your database. Your app asks the cache first. If the answer is there, it returns it immediately. If not, it hits the database, gets the result, stores it in the cache for next time, and then returns it.</p><p>This pattern is called cache-aside, or sometimes look-aside caching. It’s the most common approach and looks roughly like this in code:</p><pre>def get_product(product_id):<br>    cache_key = f&quot;product:{product_id}&quot;<br>    <br>    cached = cache.get(cache_key)<br>    if cached:<br>        return cached           # Cache hit — instant, no DB needed<br>    <br>    product = db.query(&quot;SELECT * FROM products WHERE id = ?&quot;, product_id)<br>    cache.set(cache_key, product, ttl=300)   # Store for 5 minutes<br>    return product</pre><p>The ttl (time-to-live) is how long the cached value is kept before being automatically deleted. After 300 seconds, the next request will go to the database again, refresh the cache, and the cycle repeats. TTL is how you balance freshness against performance — shorter TTL means fresher data but more database hits, longer TTL means stale data but fewer hits.</p><p>The two tools that dominate server-side caching are Redis and Memcached.</p><h3>Redis: The Cache That Does More</h3><p>Redis started as a cache and grew into something much larger. It’s an in-memory data store that supports not just simple key-value pairs but a wide range of data structures: strings, lists, sets, sorted sets, hashes, streams, and more.</p><p>This makes Redis genuinely versatile. You can use it as a cache, but also as a session store, a pub/sub message broker, a job queue, a leaderboard, or a rate limiter — all at the same time, all from the same instance.</p><pre># Simple string cache<br>redis.set(&quot;user:123:name&quot;, &quot;Alex&quot;, ex=3600)<br>redis.get(&quot;user:123:name&quot;)   # → &quot;Alex&quot;</pre><pre># Cache an entire hash (user profile)<br>redis.hset(&quot;user:123&quot;, mapping={&quot;name&quot;: &quot;Alex&quot;, &quot;role&quot;: &quot;admin&quot;, &quot;plan&quot;: &quot;pro&quot;})<br>redis.hget(&quot;user:123&quot;, &quot;role&quot;)   # → &quot;admin&quot;</pre><pre># A sorted set — perfect for leaderboards<br>redis.zadd(&quot;game:scores&quot;, {&quot;alice&quot;: 9800, &quot;bob&quot;: 7200, &quot;carol&quot;: 11500})<br>redis.zrange(&quot;game:scores&quot;, 0, 2, withscores=True, rev=True)<br># → [(&quot;carol&quot;, 11500), (&quot;alice&quot;, 9800), (&quot;bob&quot;, 7200)]</pre><p>Redis also persists to disk. If the server restarts, it can reload its data from a snapshot or a write-ahead log, so the cache survives reboots without becoming completely cold. This matters in production where a cache being wiped after a deploy can cause a thundering herd — every request suddenly hitting the database at the same time.</p><p>Redis is the default choice for most modern applications. If you’re unsure which to use, start here.</p><h3>Memcached: The Simpler, Faster One</h3><p>Memcached is older and far more focused. It does exactly one thing: store key-value pairs in memory, with no persistence, no complex data types, and no extra features. What it lacks in versatility it makes up for in simplicity and raw speed.</p><pre># Memcached stores and retrieves strings (or serialized objects)<br>mc.set(&quot;session:abc123&quot;, serialized_session_data, expire=1800)<br>mc.get(&quot;session:abc123&quot;)</pre><p>Memcached also has a built-in advantage for large-scale deployments: it’s trivially horizontally scalable. You add more servers, the client library distributes keys across them using consistent hashing, and the whole thing scales out linearly. Redis supports clustering too, but Memcached’s design makes it effortless.</p><p>The right time to reach for Memcached is when your caching needs are simple and predictable — you’re storing serialized objects by key, you don’t need persistence, and you want to keep the operational complexity low. For everything else, Redis has become the de facto standard.</p><h3>HTTP Caching: The Browser Does the Work</h3><p>Server-side caching stores results close to your application. HTTP caching stores results closer to the user — in the browser itself, or in a CDN (Content Delivery Network) sitting between the user and your servers.</p><p>The mechanism is controlled entirely through HTTP response headers. When your server responds to a request, it can include headers that tell the browser or CDN: “this content is valid for the next 24 hours, you don’t need to ask me again.”</p><pre>HTTP/1.1 200 OK<br>Cache-Control: public, max-age=86400<br>ETag: &quot;33a64df551425fcc55e4d42a148795d9f25f89d&quot;<br>Last-Modified: Wed, 18 Jun 2025 12:00:00 GMT<br>Content-Type: image/png</pre><p>The key headers:</p><p>Cache-Control is the main instruction. max-age=86400 means &quot;cache this for 86400 seconds&quot; (24 hours). public means any cache (including CDNs) can store it. private means only the individual user&#39;s browser can store it — useful for responses that contain user-specific data. no-cache is confusing — it doesn&#39;t mean &quot;don&#39;t cache&quot;, it means &quot;cache it, but revalidate with the server before using it.&quot; no-store actually means don&#39;t cache at all.</p><p>ETag is a fingerprint of the response content. When the browser has a cached response with an ETag and the cache expires, it asks the server: &quot;do you still have this content?&quot; by sending the ETag back. If the content hasn&#39;t changed, the server responds with 304 Not Modified — no body, just a confirmation — and the browser keeps using what it has. This saves bandwidth even when the cache needs to be validated.</p><p>Last-Modified does the same thing as ETag but uses a timestamp instead of a hash. ETag is generally preferred because it works even when timestamps aren&#39;t reliable.</p><p>HTTP caching is especially powerful for static assets — images, fonts, CSS, JavaScript files. A CSS file that hasn’t changed can be cached in the browser for a year with max-age=31536000. The trick is cache-busting: when the file <em>does</em> change, you change the filename (or add a hash to it), so the browser treats it as a new URL and fetches the new version.</p><pre>&lt;!-- Old URL — browser uses cached version --&gt;<br>&lt;link rel=&quot;stylesheet&quot; href=&quot;/styles.css&quot;&gt;</pre><pre>&lt;!-- New URL after content change — browser fetches fresh --&gt;<br>&lt;link rel=&quot;stylesheet&quot; href=&quot;/styles.a3f9b2c1.css&quot;&gt;</pre><p>Most build tools (Webpack, Vite, etc.) do this automatically.</p><h3>Cache Invalidation: The Hard Part</h3><p>There’s an old joke in software engineering: “There are only two hard things in computer science — cache invalidation and naming things.”</p><p>The reason cache invalidation is hard is that a cache is a copy of your data, and copies go stale. When the original changes, the copy is wrong. You need a strategy for handling that.</p><p>TTL expiry is the simplest approach. Every cached value has a time-to-live, and after it expires, the next request gets fresh data. This is eventually consistent: stale data can exist until the TTL runs out. Acceptable for most use cases, but not for anything where correctness matters immediately (bank balances, inventory counts, user account state).</p><p>Write-through invalidation is more precise. When your app writes updated data to the database, it also immediately deletes or updates the cached version. The cache never gets a chance to go stale. This is more complex to implement correctly — you have to remember to invalidate in every code path that updates the data — but it’s worth it for data that changes frequently and needs to be consistent.</p><p>Cache busting is used in HTTP caching with static assets. Instead of invalidating a cache entry, you change the URL so the old cached version is simply never requested again. New URL means fresh fetch. The old cached version quietly expires on its own.</p><p>The pattern that causes the most production bugs is partial invalidation — you update the data in the database, you remember to invalidate the main cache key, but you forget about the secondary cache key that stored a slightly different view of the same data. Both need to be invalidated, and only one is. This is why grouping related cache keys and naming them consistently matters more than it seems.</p><h3>The Core Idea to Remember</h3><p>Caching is always a trade-off between speed and freshness. The more aggressively you cache, the faster your app is — and the more likely users are seeing slightly stale data. How stale is acceptable depends entirely on what the data is.</p><p>A product listing can probably be cached for five minutes — nobody notices if the price is five minutes old. A user’s account balance probably can’t be cached at all, or for seconds at most. The code for making the decision is always the same: how expensive is this to compute, how often does it change, and what’s the cost of showing a stale version?</p><p>Start with the slow parts. Add caching where the data is expensive to fetch and doesn’t change often. Measure before and after. The improvements are usually dramatic — and unlike most performance optimizations, caching doesn’t require rewriting anything. It just remembers the answer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72c9e3f2bf5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monolithic vs Microservices Architecture]]></title>
            <link>https://medium.com/linkit-intecs/monolithic-vs-microservices-architecture-f7e2878391a1?source=rss-1c46a17551d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7e2878391a1</guid>
            <dc:creator><![CDATA[Hasini Rathnayaka]]></dc:creator>
            <pubDate>Sat, 14 Sep 2024 09:44:14 GMT</pubDate>
            <atom:updated>2024-09-14T09:44:14.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3F7U0BXYrrFH5KPhRE1-hA.png" /></figure><h3>Monolithic🏢</h3><p>Imagine you’re part of a small but ambitious startup. Your team is building a web application, and everything is streamlined and simple. All your code is in one place — it’s a monolithic architecture. At this stage, it feels like maintaining a compact, well-organized codebase. All your operations are within a single repository, making it easy to manage and coordinate. You can push new features, test them quickly, and roll out updates efficiently.</p><p>But as your business grows, so does your application. More users sign up, and new features are added at a rapid pace. What was once a straightforward codebase begins to expand into a large, complex repository. That once-simple project now feels like a sprawling codebase with too many interdependencies and tangled modules.</p><h4>Challenges of Monolithic Architecture 🧗‍♂️</h4><p>At first, your monolithic system works just fine. Debugging issues is a breeze — you can see everything in one place. Want to deploy? Just push the code live, test it in one go, and you’re good to go. The single structure makes it easy to manage small teams and streamline communication.</p><p>However, as the app expands, so do the problems. Now, to deploy even the tiniest feature, you have to roll out the entire application. Your CI/CD pipeline becomes a bottleneck as developers wait in line to push their changes. Onboarding new team members takes longer because they have to understand how the entire system works before they can contribute.</p><p>Scaling becomes another issue. Your app is getting more traffic, but it’s not evenly distributed across the system. Some features are overwhelmed, while others are barely used. To scale, you’re forced to increase resources for the whole system, even if only one part of the app needs extra capacity.</p><h3>Microservices🧩</h3><p>Instead of managing one massive codebase, microservices break the application down into smaller, independent services. Each microservice is responsible for a specific function and can be developed, deployed, and scaled separately. For instance, in an e-commerce app, you might have separate services for user authentication, managing the product catalog, and handling payments. Each one operates independently, but together they create a seamless user experience.</p><h4>How Microservice Architecture Works🛠️</h4><ul><li><strong>Independent Units</strong> Each microservice is an independent unit responsible for a distinct function. For example, in an e-commerce app, you might have separate services for user authentication, managing the product catalog, and handling payments. These services operate independently, allowing them to be developed, deployed, and scaled in isolation.</li><li><strong>Inter-Service Communication</strong> Microservices don’t exist in isolation; they need to communicate with each other. Unlike a monolith, where direct function calls are made, microservices communicate through well-defined APIs, usually using HTTP/REST or messaging protocols like gRPC or message queues. This enables each service to operate independently, even if they’re written in different programming languages.</li><li><strong>Decentralized Data Management</strong> Unlike monolithic architectures with a single shared database, microservices follow a decentralized data management approach. Each service has its own database, optimized for its specific task. For example, the product catalog might use a NoSQL database, while the payment service relies on a relational database. This reduces bottlenecks but introduces challenges like managing data consistency across services.</li><li><strong>Service Discovery</strong> In a microservices environment, services need to locate and communicate with each other. Service discovery allows services to dynamically discover the location (IP address and port) of other services in the system.</li><li><strong>Scalability</strong> One of the key benefits of microservices is scalability. Each microservice can be scaled independently, so you can increase resources only for the services that need it. For instance, if the login service is under heavy traffic while the product catalog is stable, you can scale up the login service without affecting the rest of the system.</li><li><strong>Failure Isolation</strong> In a monolithic system, a failure in one part of the system can bring down the entire application. With microservices, the failure of one service doesn’t necessarily impact the others. Techniques like circuit breakers and timeouts help isolate and manage failures, preventing them from cascading across the system.</li><li><strong>Containerization and Orchestration</strong> Microservices thrive in environments that support containerization. Each service is packaged with all its dependencies into a lightweight, portable container. Tools like Docker enable efficient management of containers, while orchestration platforms like Kubernetes ensure containers are deployed, scaled, and managed across distributed environments.</li><li><strong>Monitoring and Visibility</strong> Since there are multiple services working together, visibility is crucial. Tools like Prometheus, Grafana, and the ELK stack (Elasticsearch, Logstash, Kibana) help track the performance, health, and logs of each service, ensuring the system functions optimally.</li></ul><h4>Challenges of Microservices 🧗‍♂️</h4><p>Microservices introduce their own set of challenges:</p><ul><li><strong>Increased Complexity</strong> Managing multiple codebases, CI/CD pipelines, and infrastructure is complex. Smooth communication between services is essential, often relying on APIs or message brokers.</li><li><strong>Network Latency and Service Coordination</strong> Since services are separate, they must communicate over the network. You’ll need to handle latency, ensure services stay up and manage asynchronous tasks. Service meshes and network communication patterns become crucial.</li><li><strong>Infrastructure Overhead</strong> Each service requires its own deployment pipeline, monitoring, and infrastructure. Investing in tools to manage this overhead, such as Kubernetes for orchestration and Docker for containerization, is essential.</li></ul><p>In the end, choosing between monolith and microservices depends on your project’s needs💻. Monoliths work best for smaller applications, while microservices shine in environments where scaling and flexibility are critical.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7e2878391a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/monolithic-vs-microservices-architecture-f7e2878391a1">Monolithic vs Microservices Architecture</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CPU Scheduling in Operating Systems: An Overview]]></title>
            <link>https://medium.com/@hasinichamodi4/cpu-scheduling-in-operating-systems-an-overview-7fbc83417baa?source=rss-1c46a17551d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fbc83417baa</guid>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[multitasking]]></category>
            <category><![CDATA[computer-architecture]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Hasini Rathnayaka]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 17:47:04 GMT</pubDate>
            <atom:updated>2026-06-26T13:11:15.210Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oxYIOqinHtuExgKsxlHm3A.jpeg" /></figure><p>In a single-core processor computer system, the central processing unit (CPU) can execute only one process at any given moment. When a process is in execution, it may encounter situations where it needs to pause, such as waiting for input/output (I/O) operations to complete. During these idle periods, the CPU remains unutilized.</p><p>However, in a multiprogramming environment, the CPU is kept active and productive. Multiprogramming is a technique employed in operating systems where multiple processes are simultaneously resident in memory. These processes are effectively managed by the operating system, which chooses which process to assign the CPU to at any given time to manage their execution. This approach ensures that the CPU is continuously engaged in processing tasks, even when some processes are temporarily blocked, waiting for I/O or other resources.</p><p>To facilitate the allocation of the CPU’s time among competing processes, CPU scheduling algorithms are employed. These algorithms serve as the decision-making framework for determining the order and duration of process execution. Various CPU scheduling algorithms are available, each with its unique characteristics and objectives:</p><p><strong>First-Come, First-Served (FCFS):</strong></p><p>Processes run in the sequence they arrive in the ready queue. It’s straightforward and easy to implement, but short processes may experience long delays if they are queued behind longer ones.</p><p><strong>Shortest Job First (SJF):</strong></p><p>Chooses the process with the shortest predicted CPU burst time. This method effectively reduces the average waiting time but can be difficult to predict burst times and might cause longer processes to wait indefinitely.<br>Priority Scheduling:</p><p>Assigns CPU based on the priority of processes. Ensures that high-priority processes are executed first, making sure critical tasks are addressed quickly, though it might significantly delay lower-priority processes.</p><p><strong>Round Robin (RR):</strong></p><p>Allocates a fixed time slice (quantum) to each process in a round-robin fashion. It ensures equitable CPU time distribution and is well-suited for time-sharing systems, although its efficiency is highly dependent on the quantum length.</p><p><strong>Multilevel Queue Scheduling:</strong></p><p>Categorizes processes into multiple queues, each with a distinct scheduling algorithm. It offers great flexibility and allows tailored scheduling for different types of processes but can be complex to implement and manage.</p><p>CPU scheduling decisions occur in various scenarios within a computer system:</p><p>— When a process transitions from the running state to the waiting state (e.g., due to an I/O request or a synchronization event).</p><p>— When a process transitions from the running state to the ready state, typically in response to an interrupt (e.g., a hardware interrupt or a timer interrupt) that temporarily halts its execution. After the interruption, the process is placed in the ready state and can continue its execution once the CPU scheduler allocates the CPU again.</p><p>— When a process transitions from the waiting state to the ready state, usually after completing an I/O operation or satisfying a waiting condition. The CPU scheduler decides whether to allocate the CPU to this process or another in this scenario.</p><p>— When a process terminates its execution, releasing the CPU.</p><p>In summary, effective CPU scheduling is vital for making the most of CPU resources and ensuring fair process execution. By efficiently handling many processes, the operating system maintains consistent CPU usage, leading to better system performance and responsiveness.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fbc83417baa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>