<?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 Amey Kulkarni on Medium]]></title>
        <description><![CDATA[Stories by Amey Kulkarni on Medium]]></description>
        <link>https://medium.com/@kulkarniamey2004?source=rss-5e71b191d697------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mSQnO4y-OoJhbgNbTLBixg@2x.jpeg</url>
            <title>Stories by Amey Kulkarni on Medium</title>
            <link>https://medium.com/@kulkarniamey2004?source=rss-5e71b191d697------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:37:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kulkarniamey2004/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[ Auth, Demystified: A Practical Deep Dive into Authentication & Authorization (with Diagrams)]]></title>
            <link>https://medium.com/@kulkarniamey2004/auth-demystified-a-practical-deep-dive-into-authentication-authorization-with-diagrams-e37d68a3d7a1?source=rss-5e71b191d697------2</link>
            <guid isPermaLink="false">https://medium.com/p/e37d68a3d7a1</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Amey Kulkarni]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 04:16:01 GMT</pubDate>
            <atom:updated>2026-08-22T04:16:01.206Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MhgTmlnNPahjXZFLFWR31Q.png" /></figure><h3>Authentication vs Authorization: The Foundation</h3><p>Before diving into protocols, tokens, and AWS services, it’s worth nailing down two terms that get used interchangeably, but mean very different things.</p><p><strong>Authentication</strong> answers one question: <em>Who are you?</em><br> It’s the process of verifying identity, usually through a login, a password, a token, or some credential that proves you are who you claim to be.</p><p><strong>Authorization</strong> answers a different question: <em>What are you allowed to do?</em><br> Once your identity is confirmed, authorization decides what resources, data, or actions you actually have access to.</p><p>In short:</p><ul><li><strong>Authentication</strong> → verifies <strong>identity</strong></li><li><strong>Authorization</strong> → verifies <strong>permissions</strong></li></ul><p>Here’s a flow I mapped out to visualize exactly where these two concepts kick in, and how they connect to the actual infrastructure behind a login:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cynJovD4C33H6i1WGEy8aA.png" /></figure><p>Walking through it:</p><ol><li>A user attempts to <strong>Login</strong>.</li><li>The system asks: <strong><em>Who is this?</em></strong> — this is the authentication check.</li><li>If the identity <strong>can’t be confirmed</strong>, the system returns an <strong>HTTP 401 (Unauthorized)</strong> and access is denied.</li><li>If the identity <strong>is confirmed</strong>, the system returns an <strong>HTTP 200 (OK)</strong> and access is granted.</li><li>Once access is granted, the request flows through the <strong>API Gateway</strong>, which routes it to the right <strong>resource</strong> in the API layer.</li><li>That resource is backed by a <strong>service</strong> (like a Lambda function), which is where the actual <strong>authorization logic</strong> — checking <em>what this user is allowed to do</em> — typically lives.</li><li>Finally, the service interacts with the <strong>data layer</strong> (like a DynamoDB table) to fetch or modify data, but only the data this specific user is permitted to touch.</li></ol><p>This is the core idea to hold onto before we go further: <strong>authentication happens first, at the gate. Authorization happens after, at every layer behind it.</strong></p><h3>Authentication Methods: The Four Building Blocks</h3><p>Before jumping into specific methods, it’s worth clarifying one thing that trips a lot of people up. <strong>An authentication method is not the same as an authorization framework</strong> (like OAuth). Authentication methods deal with proving who you are on each request. Authorization frameworks deal with what you’re allowed to do once you’re identified, and they often layer on top of one of these methods.</p><p>In simple terms: <strong>an authentication method is the mechanism a client uses to prove its identity to a server on every request.</strong></p><p>There are four foundational methods worth understanding, each with different trade-offs in security, simplicity, and scalability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OYbVNN0JPPpNc3e4uNiEGA.png" /></figure><ul><li><strong>Basic Authentication</strong></li><li><strong>Digest Authentication</strong></li><li><strong>API Key Authentication</strong></li><li><strong>Session-Based Authentication</strong></li></ul><p>Let’s go through each one.</p><h4>1. Basic Authentication</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DfVeFd6tCVPt6M40B7fa6w.png" /></figure><p>Basic Authentication is the simplest of the four, and also the weakest.</p><p>Here’s how it works:</p><ol><li>The client sends a request (e.g., GET /users) with no credentials.</li><li>The server rejects it with a <strong>401 Unauthorized</strong>.</li><li>The client encodes its credentials (username and password) using <strong>Base64</strong> and sends them again in the request header as Authorization: Basic &lt;encoded-credentials&gt;.</li><li>The server decodes the Base64 string and verifies the credentials. If valid, it responds with <strong>200 OK</strong> and the data. If invalid, it responds with <strong>401 Unauthorized</strong> again.</li></ol><p><strong>The concept that actually matters here:</strong> Base64 is encoding, not encryption. It’s trivially reversible. Anyone who intercepts the request can decode it in seconds and recover the raw username and password in plain text.</p><p>This is why Basic Authentication is considered insecure on its own, and should never be used without HTTPS/TLS underneath it. Even with TLS, it’s rarely chosen for modern systems, it mostly shows up in quick internal tools, simple scripts, or legacy integrations.</p><p><strong>Recommendation:</strong> Avoid this for anything user-facing or production-grade. If you see it in a system, treat it as a red flag unless there’s a very specific, low-risk reason for it.</p><h4>2. Digest Authentication</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n6W7UQeYL0m-M_joXzWm1Q.png" /></figure><p>Digest Authentication follows almost the same flow as Basic Authentication. The real difference is <em>how the credentials are protected in transit</em>.</p><p>Instead of sending credentials Base64-encoded (reversible), Digest Authentication sends them as an <strong>MD5 hash</strong>, a one-way function that scrambles input into a fixed-length string that can’t be reversed back into the original value.</p><p>The flow:</p><ol><li>Client sends a request without credentials.</li><li>Server responds with <strong>401 Unauthorized</strong>, along with a realm and a nonce (a unique, server-generated value used once).</li><li>The client hashes its credentials combined with that nonce using MD5, and sends the resulting hash in the Authorization header.</li><li>The server independently computes the same hash using the credentials it has on record and the same nonce, then compares the two. If they match, it returns <strong>200 OK</strong> with the data. If not, <strong>401 Unauthorized</strong>.</li></ol><p><strong>The concept that matters here:</strong> a hash is one-directional. You can turn a password into an MD5 digest, but you cannot turn that digest back into the password. This means the raw password itself never travels over the network, only its hash does.</p><p>That said, MD5 specifically is now considered cryptographically weak and vulnerable to collision attacks. So while Digest Authentication is a meaningful improvement over Basic, it’s still not something modern systems rely on as a primary defense.</p><p><strong>Recommendation:</strong> Better than Basic, but still outdated. Mostly seen in legacy systems today. Not something to build new systems around.</p><h4>3. API Key Authentication</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KcXodig7lRLAZO-L-Ker1w.png" /></figure><p>This method introduces a third entity: a <strong>database layer</strong> that stores and verifies API keys.</p><p>Here’s how it works:</p><ol><li>The client generates an API key, typically a long, random string issued once, often during account or project setup.</li><li>The client sends requests with the key attached, usually as a query parameter or header, for example GET /users?api_key=bcjkwbkwheuh.</li><li>The server checks that key against a DB table mapping user_id to api_key.</li><li>If a match is found, the server returns <strong>200 OK</strong> with the data. If the key is invalid or revoked, it returns <strong>401 Unauthorized</strong>.</li></ol><p><strong>This is the concept that really matters with API keys:</strong> they are long-lived credentials. That’s exactly what makes them convenient, and exactly what makes them risky.</p><p>A session or a token typically expires on its own after some time. An API key does not. If it leaks, it stays valid indefinitely until someone manually revokes it. This single property changes how API keys need to be treated: they should never be hardcoded in client-side code, never committed to a repository, and should ideally be scoped (limited to specific actions) and rate-limited so a leak causes minimal damage even before it’s caught.</p><p><strong>Recommendation:</strong> API keys are the industry standard for machine-to-machine communication, third-party integrations, and server-to-server calls, where there’s no human logging in interactively. They are not meant for authenticating end users in a web or mobile app.</p><h4>4. Session-Based Authentication</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTUudPKxLq1Edev1H24bjQ.png" /></figure><p>Session-based authentication introduces a <strong>session store</strong>, a place where the server keeps track of who is logged in. This store can be:</p><ul><li><strong>In-memory</strong> (fast, but tied to a single server instance)</li><li><strong>A database</strong> (durable, but slower)</li><li><strong>A Redis cache</strong> (fast and shareable across multiple servers, the most common choice in production)</li></ul><p>Here’s the flow:</p><ol><li>The client logs in with credentials.</li><li>The server creates a session and stores it in the session store, which returns a unique SessionId.</li><li>The server sends that session ID back to the client as a <strong>cookie</strong>.</li><li>On every subsequent request, the client automatically sends that cookie along with the request.</li><li>The server takes the session ID from the cookie and looks it up in the session store.</li><li>If the session is valid, the server returns <strong>200 OK</strong> with the data. If the session has expired or doesn’t exist, it returns <strong>401 Unauthorized</strong>.</li></ol><p><strong>The concept most people get confused about:</strong> a session and a cookie are not the same thing. A session is server-side state, it lives in the session store and represents “this user is logged in, here is their data.” A cookie is just the small piece of information the browser holds onto and automatically attaches to every request. In this case, the cookie carries the session ID, not the session itself.</p><p>If you’re curious enough to see this in action: open your browser’s DevTools, go to the <strong>Application tab</strong>, then <strong>Cookies</strong>, on any site you’re logged into. You’ll see the actual cookie being set, its name, and attributes like HttpOnly, Secure, and SameSite, flags that control how that cookie can be accessed and where it can be sent.</p><p>The trade-off with session-based auth is scaling. Since sessions are stored server-side, scaling across multiple servers requires a shared session store like Redis. Otherwise a user could get logged out simply because their next request landed on a different server that doesn’t recognize their session.</p><p><strong>Recommendation:</strong> Still one of the most widely used and battle-tested methods for traditional web apps with a login flow. It’s a strong default choice when you control both client and server, especially for browser-based applications.</p><h4>Quick Takeaway</h4><p>If you’re deciding what to actually use:</p><ul><li><strong>Basic and Digest</strong> exist mostly to help you understand the evolution of auth, not to be used in new systems.</li><li><strong>API Keys</strong> are the right call for machine-to-machine and service-to-service communication.</li><li><strong>Sessions</strong> are the right call for traditional web applications with human users logging in through a browser.</li></ul><p>Later in this article, you’ll see how modern systems (like OAuth 2.0 and JWTs) push this even further, especially for scenarios involving mobile apps, single-page applications, and distributed systems where sessions and API keys start to show their limits.</p><h3>OpenID Connect (OIDC): Letting Someone Else Handle the Login</h3><p>Before breaking down the flow in the diagram, let’s clear up two words that get thrown around a lot without much explanation: <strong>protocol</strong> and <strong>authentication protocol</strong>.</p><p>A <strong>protocol</strong>, in general, is just an agreed-upon set of rules that different systems follow so they can communicate with each other predictably. It doesn’t matter who built the systems or what language they’re written in, as long as everyone follows the same rulebook, they can talk to each other. HTTP is a protocol. TCP/IP is a protocol. In the same way, an <strong>authentication protocol</strong> is a standardized set of rules for proving identity between systems, so that any app and any identity provider can work together without custom, one-off integration logic every time.</p><p>This is exactly the problem <strong>OpenID Connect (OIDC)</strong> solves.</p><p>OIDC is an authentication protocol built directly on top of OAuth 2.0 (which we’ll cover in detail shortly). OAuth 2.0 by itself was designed to answer “what is this app allowed to access,” not “who is this person.” OIDC adds an identity layer on top of that, so an application can reliably answer both questions using one standard flow. This is precisely why “Sign in with Google,” “Sign in with Facebook,” and “Sign in with Apple” all feel similar wherever you encounter them. They’re all implementations of the same underlying protocol.</p><p>Here’s the flow I mapped out, using Google as the identity provider:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0JRUl-Qrw7S4ZsB8APaNg.png" /></figure><p>Walking through it:</p><ol><li>The <strong>user</strong> clicks “Sign in with Google” inside <strong>My App</strong>.</li><li>My App <strong>redirects the user to Google’s authorization endpoint</strong>. Notice that at this point, the user has left my app entirely and is now interacting directly with Google.</li><li>Google <strong>shows its own login screen</strong> to the user, not a screen built by my app. This matters a lot: my app never sees or handles the user’s Google password. Only Google does.</li><li>The user <strong>enters their credentials and gives consent</strong> (agreeing to share certain information with my app, like their name and email).</li><li>Google <strong>returns an authorization code</strong> back to my app. This code is short-lived and single-use, it’s not the actual token yet, just a temporary proof that the login happened successfully.</li><li>My app then <strong>exchanges that authorization code for tokens</strong> by making a direct, server-to-server call to Google.</li><li>Google responds with an <strong>Access Token and an ID Token</strong>.</li><li>My app <strong>sends the ID Token to my backend for verification</strong>. The backend checks that the token is genuine, hasn’t expired, and was actually issued by Google for this specific app.</li><li>Once verified, the user is <strong>logged in successfully</strong>.</li></ol><p>The one detail worth sitting with here is the difference implied in step 7: an <strong>Access Token</strong> and an <strong>ID Token</strong> are not the same thing, even though they arrive together. Broadly, the ID Token is the piece that answers “who is this person,” while the Access Token answers “what is this app allowed to do on their behalf.” We’ll go deeper into this distinction later in this article when we talk about JWTs and token types, but it’s worth noticing now, since it’s the exact moment OIDC hands identity back to your application.</p><p><strong>Where you’ll actually see this in the wild:</strong> any “Continue with Google / Apple / Facebook / Microsoft” button on a login screen is almost certainly OIDC under the hood. It’s the reason you can create an account on a brand new app in two clicks without ever typing a new password, the identity verification work is fully delegated to a provider you already trust.</p><p>Here’s Section 4: AWS Cognito basics.</p><h3>AWS Cognito: Identity and Access Management for Your Apps</h3><p>At this point, you’ve seen the fundamentals: authentication methods, and a real authentication protocol (OIDC) in action. The natural next question is: how does a cloud provider like AWS actually implement all of this for real applications?</p><p>That’s exactly what <strong>AWS Cognito</strong> is for. It’s an AWS service built specifically to handle <strong>secure identity and access management for apps</strong>, so you don’t have to build authentication systems from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IobvG8wrWwbfS5r-dyp52Q.png" /></figure><p>Cognito is split into two distinct services, and this is the single most important thing to get right before going further, because <strong>User Pools and Identity Pools solve two completely different problems:</strong></p><ul><li><strong>User Pools</strong> handle <strong>authentication</strong>. This is where user identities actually live, sign-up, sign-in, password resets, and verifying “who is this person.”</li><li><strong>Identity Pools</strong> handle <strong>authorization</strong> to AWS resources. This is about giving a user (or even a guest, someone who isn’t signed in at all) temporary AWS credentials to access AWS services directly, like S3 or DynamoDB.</li></ul><p>People often assume Cognito is one single thing. It’s actually two separate tools that are frequently used together, but don’t have to be.</p><h4>Three Ways Identity and Access Work in AWS</h4><p>To make this concrete, here’s a diagram showing three different entities all trying to get access to AWS resources, and three completely different paths they take to get there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MeYastN8qacq_Pi-YBrvwg.png" /></figure><p><strong>Path 1: IAM Role (direct AWS access)</strong></p><p>Here, someone says “I am the account admin” and directly requests access to AWS resources (like an S3 bucket) through <strong>IAM</strong>, AWS’s core Identity and Access Management service. IAM is how AWS manages permissions for people and services that already exist inside your AWS account, admins, developers, backend services, and so on. This path has nothing to do with app end users. It’s internal, account-level access control.</p><p><strong>Path 2: Cognito User Pool (authenticating app users)</strong></p><p>Here, a random user says “I am <a href="/service/mailto:amexx@gmail.com">amexx@gmail.com</a>, authenticate me please.” This request goes to the <strong>Cognito User Pool</strong>, which is responsible for verifying who this person actually is. Notice in the diagram that the User Pool can validate this identity either directly, or by delegating to an external identity provider like <strong>Google or Facebook</strong> (this should feel familiar, it’s the OIDC flow from the previous section, just plugged into Cognito). The User Pool’s job ends once it confirms identity. It answers “who are you,” nothing more.</p><p><strong>Path 3: Cognito Identity Pool (authorizing access to AWS resources)</strong></p><p>Here, someone says “I want temporary STS credentials, I am someone you can trust.” This request goes to the <strong>Cognito Identity Pool</strong>, which validates that trust (often using the identity that was just confirmed by the User Pool or an external IdP) and, if valid, returns <strong>temporary AWS credentials</strong> through <strong>STS (Security Token Service)</strong>. These temporary credentials are what actually let the user’s app or device talk to AWS resources like S3 directly, without ever exposing permanent AWS keys.</p><h4>Why This Distinction Matters</h4><p>Once these three paths are separated out clearly, a pattern emerges:</p><ul><li><strong>IAM</strong> answers: “Is this an AWS account principal, and what are they allowed to do inside AWS?”</li><li><strong>User Pools</strong> answer: “Is this a real, verified app user?”</li><li><strong>Identity Pools</strong> answer: “Now that we know who they are, what temporary AWS access should we hand them?”</li></ul><p>This is the same authentication vs authorization split from Section 1, just mapped directly onto AWS’s own services. Authentication (User Pools) happens first. Authorization to AWS resources (Identity Pools, backed by IAM roles behind the scenes) happens after, and only once identity has been established.</p><p>Keeping these three paths distinct in your head will make everything that follows, especially Cognito paired with OAuth 2.0, much easier to reason about.</p><h3>OAuth 2.0: The Framework Behind Modern Authorization</h3><p>Before going any further, one thing needs to be said clearly: <strong>OAuth 2.0 is not an authentication method. It’s an authorization framework.</strong></p><p>This is probably the single most common point of confusion in this entire space, so it’s worth repeating in plain terms. OAuth 2.0 was never designed to answer “who is this person.” It was designed to answer a completely different question: <strong>“can this application access this resource, on this person’s behalf, without ever seeing their password?”</strong></p><p>Think about it this way: when you click “Sign in with Google” on some random app, that app never actually sees your Google password. OAuth 2.0 is the framework that makes that possible. It lets one application be granted limited, specific access to your data on another service, through tokens, instead of through shared credentials.</p><p>(This is also why OIDC, which we covered earlier, exists as a separate layer on top of OAuth 2.0 specifically to bring identity, the “who is this person” part, back into the picture.)</p><p>To understand how OAuth 2.0 actually works, you first need to know the four core roles it defines.</p><h4>OAuth 2.0 Terminology</h4><ul><li><strong>Resource Owner:</strong> The person who owns the data or resource, and who gives permission to access it. In almost every real-world case, this is us, the end user.</li><li><strong>Client:</strong> The application that wants to access the Resource Owner’s data on their behalf.</li><li><strong>Public clients:</strong> applications that can’t securely store secrets, like a React app running in the browser.</li><li><strong>Private clients:</strong> applications that run on a trusted server and can securely store secrets, like a Node.js backend.</li><li><strong>Authorization Server:</strong> The server responsible for authenticating the user and issuing access tokens to the client. Examples include Cognito or Google.</li><li><strong>Resource Server:</strong> The server that actually stores or provides the protected data, and accepts access tokens as proof that the request is authorized.</li></ul><p>Keep these four roles in mind as you move forward, because every OAuth 2.0 flow you’ll see from here on is really just these four entities talking to each other in a specific sequence.</p><h4>OAuth 2.0 Grant Types</h4><p>A <strong>grant type</strong> is simply the specific method or “recipe” a client uses to obtain an access token from the authorization server. Different situations call for different grant types, depending on what kind of client is asking, and what kind of trust it can be given.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7UcFJQ-zJkq_8F0z4r0UzA.png" /></figure><p>The four grant types worth knowing:</p><ul><li><strong>Authorization Code:</strong> the most common and most secure grant type, used when a user is present and logging in through a browser. We’ll walk through this one in full detail next.</li><li><strong>Implicit Flow:</strong> an older, simplified flow originally designed for browser-based apps that couldn’t securely store a client secret. It’s now considered outdated and largely discouraged in favor of the Authorization Code grant (often paired with a technique called PKCE, which we won’t go into detail on here, but is worth knowing exists).</li><li><strong>client_credential:</strong> used when there is no human user involved at all. This is for machine-to-machine communication, where one service authenticates directly as itself to get a token.</li><li><strong>refresh_token:</strong> not a way to log in from scratch, but a way to get a new access token once the old one expires, without forcing the user to log in again.</li></ul><h4>OAuth 2.0 Authorization Code Grant Type, Step by Step</h4><p>This is the flow you’ll encounter most often in real applications, so it’s worth understanding thoroughly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ubB5wnaCbEFXxeg3p9ZjQ.png" /></figure><p>Here’s what’s happening, step by step:</p><ol><li>The <strong>Client</strong> sends an <strong>Authorization Request</strong> to the <strong>Authorization Server</strong>.</li><li>The Authorization Server <strong>redirects to its managed login UI</strong> (for example, Cognito’s hosted UI). This is important: the login screen belongs to the authorization server, not the client application.</li><li>The <strong>Resource Owner</strong> (the actual user) enters their <strong>credentials</strong> directly into that login screen.</li><li>If the credentials are valid, the Authorization Server sends back an <strong>authorization code</strong> to the Client, through a redirect: call_back_url?code=....</li><li>The Client then sends that <strong>authorization code</strong> back to the Authorization Server, but this time through a direct, secure, server-to-server call, sent to the token endpoint along with the <strong>client id</strong> and <strong>domain</strong>.</li><li>The Authorization Server verifies all of this and responds with a <strong>JWT</strong>, which contains the <strong>access token</strong>.</li><li>Finally, the Client uses that <strong>access token</strong> to talk to the <strong>Resource Server</strong>, which accepts it as proof of authorization and returns the protected data.</li></ol><p>The core idea to take away from this entire flow: <strong>the user’s credentials are only ever seen by the Authorization Server, never by the Client application.</strong> The Client only ever receives a temporary code, and later, a token. This separation is exactly what makes OAuth 2.0 safe to use even with third-party applications you don’t fully trust with your actual password.</p><h3>PKCE: Securing the Authorization Code Flow for Public Clients</h3><p>Earlier, when the Implicit Flow was mentioned as “outdated and largely discouraged in favor of the Authorization Code grant, often paired with a technique called PKCE,” this is exactly where that gets explained properly.</p><p><strong>First, the problem PKCE actually solves.</strong></p><p>The Authorization Code flow you just walked through works cleanly when the Client is a <strong>private client</strong>, a backend server (like Node.js) that can securely store a <strong>Client Secret</strong>. Remember from Section 5: the client exchanges the authorization code for a token by calling the token endpoint with its client id, domain, and (normally) its client secret. The client secret is what proves to the Authorization Server, “yes, this exchange request is genuinely coming from the real application, not an impostor.”</p><p>But here’s the catch: <strong>a React app, a mobile app, or any single-page application is a public client.</strong> It runs entirely on the user’s device or in their browser. Anything shipped to the browser, including a “secret,” can be extracted by anyone who opens dev tools or decompiles the app. So a Client Secret embedded in a public client isn’t actually secret at all.</p><p>This creates a real vulnerability in the Authorization Code flow: if an attacker can intercept the authorization code (for example, through a malicious app registered to intercept the same redirect URI on a shared device), and the client has no real secret to prove its identity during the token exchange, the attacker could potentially exchange that stolen code for a token themselves.</p><p><strong>This is exactly the gap PKCE closes.</strong></p><p>PKCE stands for <strong>Proof Key for Code Exchange</strong> (pronounced “pixy”). Instead of relying on a static, easily-stolen Client Secret, PKCE has the client generate a <strong>one-time, dynamic secret for every single login attempt</strong>. Even if an attacker intercepts the authorization code, they don’t have the matching one-time secret needed to exchange it for a token.</p><h4>How PKCE Actually Works, Step by Step</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QQkoFMJ6ooFm9TLD.png" /></figure><ol><li>Before even starting the login flow, the Client generates a random string called the <strong>code verifier</strong>, a long, unguessable, one-time secret created fresh for this specific login attempt.</li><li>The Client then runs that code verifier through a one-way hashing function (specifically SHA-256), producing a <strong>code challenge</strong>. This is the same idea as the hashing concept from Digest Authentication and JWT signing earlier in this article: one-way, meaning you can turn the verifier into the challenge, but you can’t reverse the challenge back into the verifier.</li><li>The Client sends the <strong>authorization request</strong> to the Authorization Server, but this time it includes the <strong>code challenge</strong> alongside it (the hashed version, not the original secret).</li><li>The user logs in normally, exactly as described in the standard Authorization Code flow.</li><li>The Authorization Server returns the <strong>authorization code</strong>, and it also remembers which code challenge was associated with this specific request.</li><li>Now, when the Client exchanges the authorization code for a token, it sends along the <strong>original code verifier</strong> (the un-hashed secret from step 1), instead of a Client Secret.</li><li>The Authorization Server takes that code verifier, hashes it itself using the same method, and checks: <strong>does this match the code challenge I was given back in step 3?</strong></li><li>If it matches, the Authorization Server knows this token exchange request is coming from the exact same client that started the login flow, and issues the <strong>access token</strong>. If it doesn’t match, the request is rejected.</li></ol><h4>Why This Actually Prevents the Attack</h4><p>The key insight is this: <strong>even if an attacker steals the authorization code, they don’t have the code verifier</strong>, since it was generated locally on the legitimate user’s device and never transmitted anywhere except as its hashed form (the code challenge). Without the matching verifier, the stolen code is useless to them, the Authorization Server will reject the exchange attempt.</p><p>This is the entire idea of PKCE in one sentence: <strong>it replaces a static, stealable secret with a fresh, one-time secret generated for that single login attempt, so intercepting the authorization code alone is no longer enough to steal the token.</strong></p><h4>Where PKCE Is Actually Required</h4><ul><li><strong>Public clients</strong>, React apps, mobile apps, single-page applications: PKCE should always be used with the Authorization Code grant. This combination (Authorization Code + PKCE) is now the industry-recommended standard, replacing the old Implicit Flow entirely.</li><li><strong>Private clients</strong>, backend servers that can securely store a Client Secret: PKCE is still commonly recommended as an added layer of defense, even though the client secret already provides protection. Many modern Authorization Servers, including Cognito, now support or even require PKCE regardless of client type, since it makes the entire flow more resistant to interception attacks with essentially no downside.</li></ul><p>The takeaway to carry forward: <strong>whenever you see “Authorization Code + PKCE” mentioned together, especially for a frontend or mobile app, this is the modern, secure standard, and it’s the direct replacement for the once-common but now-discouraged Implicit Flow.</strong></p><h4>Cognito User Pool with OAuth 2.0, in Practice</h4><p>Now let’s bring this back to something concrete: how this actually plays out with AWS Cognito and an external identity provider like Google.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rPQU01-WplC7skRUOpC-Q.png" /></figure><ol><li>The <strong>User</strong> tells <strong>My Application</strong>, “do a task for me.”</li><li>Since the user isn’t authenticated yet, My Application needs to verify who they are. It routes the user to <strong>Google</strong> for authentication.</li><li>The user provides their <strong>correct email and correct password</strong> directly to Google, not to My Application.</li><li>Once verified, the user receives a <strong>valid JWT</strong> back.</li><li>The user then goes back to <strong>My Application</strong>, this time saying “do a task for me, plus access token”, attaching the token they just received.</li><li>My Application, seeing a trusted, valid token, says <strong>“I trust you”</strong> and proceeds with the task.</li></ol><p>This is the exact same Authorization Code pattern from before, just made concrete with real players: Cognito (or Google, acting as the identity provider) issuing the token, and the application trusting that token instead of ever handling a password itself.</p><h3>JWT: The Token Format Behind Modern Auth</h3><p>Before going any further, one clarification needs to happen first, because it trips people up constantly: <strong>JWT is not an authentication type. It’s a token type.</strong></p><p>A JWT (JSON Web Token) is simply a specific, standardized <em>format</em> for representing data securely as a string. Various authentication methods and protocols, including session-based systems, OAuth 2.0, and OIDC, all use JWTs as the format for the tokens they issue. JWT itself doesn’t define how you log in. It defines what the resulting proof of identity or authorization looks like once you have logged in.</p><p>With that cleared up, let’s look at what a JWT actually is, structurally.</p><h4>The Structure of a JWT</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mzXmVNepN44aeArjxRB5Rg.png" /></figure><p>A JWT is made up of <strong>three Base64-encoded strings, separated by dots</strong>:</p><pre>Header.Payload.Signature</pre><p>Each part serves a distinct purpose:</p><ul><li><strong>Header:</strong> metadata about the token itself, like which algorithm was used to sign it.</li><li><strong>Payload:</strong> the actual data, called claims, that the token is carrying.</li><li><strong>Signature:</strong> a cryptographic proof that the header and payload haven’t been tampered with.</li></ul><p>Let’s break down what’s actually inside each part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mva1TzKE5_IlNz4EtO_5iQ.png" /></figure><p><strong>Header example:</strong></p><p>json</p><pre>{<br>  &quot;alg&quot;: &quot;RS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;,<br>  &quot;kid&quot;: &quot;abc123&quot;<br>}</pre><p>This tells you how the JWT was generated. alg is the signing algorithm used, typ confirms this is a JWT, and kid (key ID) tells the verifier which specific key to use when checking the signature.</p><p><strong>Payload example:</strong></p><p>json</p><pre>{<br>  &quot;sub&quot;: &quot;12345&quot;,<br>  &quot;name&quot;: &quot;Amey&quot;,<br>  &quot;role&quot;: &quot;admin&quot;,<br>  &quot;iss&quot;: &quot;https://cognito-idp.us-east-1.amazonaws.com/us-east-1_ABC&quot;,<br>  &quot;aud&quot;: &quot;6iffu8kd7eid8dt9qmlauo36cu&quot;,<br>  &quot;exp&quot;: 1786770000<br>}</pre><p>Each of these fields is called a <strong>claim</strong>, a piece of information the token is asserting about the user or the token itself. Some claims are standardized and show up across almost every JWT:</p><ul><li>sub (subject): who this token is about, typically a unique user ID.</li><li>iss (issuer): who created and signed this token.</li><li>aud (audience): who this token is intended for.</li><li>exp (expiration): the timestamp after which this token is no longer valid.</li></ul><p>Along with any custom claims the issuer decides to add, like name or role in this example.</p><p><strong>Signature:</strong> this is where things get interesting, and it’s the part that actually makes a JWT trustworthy.</p><h4>How Signing Actually Works</h4><p>The signature is generated by taking the Header and Payload together, and running them through a signing process using a <strong>private key</strong>.</p><p>This is a good moment to clarify two terms that come up constantly in this space: <strong>public key</strong> and <strong>private key</strong>.</p><p>A <strong>private key</strong> and a <strong>public key</strong> are a mathematically linked pair. Whatever is signed with the private key can be verified using the public key, but the public key cannot be used to create a new valid signature. The private key stays secret, known only to the issuer (like Cognito). The public key can be shared freely, and is exactly what other systems use to check that a token is genuine.</p><p><strong>Signing</strong>, then, is the process of using that private key to generate a unique signature based on the exact contents of the header and payload. If even a single character in the payload changes, for example, &quot;role&quot;: &quot;admin&quot; becomes &quot;role&quot;: &quot;superadmin&quot;, the resulting signature would be completely different.</p><p>This is exactly why an attacker cannot simply edit the payload of a JWT and get away with it. Here’s the scenario:</p><ol><li>An attacker intercepts a valid JWT.</li><li>They decode the payload (Base64 is not encryption, remember, it’s just encoding, so the payload is readable).</li><li>They change &quot;role&quot;: &quot;user&quot; to &quot;role&quot;: &quot;admin&quot;.</li><li>They send this modified token back to the server.</li></ol><p>The server, upon receiving this token, recomputes the signature using the public key and compares it against the signature attached to the token. Since the payload changed but the attacker doesn’t have the private key needed to generate a matching new signature, <strong>the signatures won’t match</strong>, and the server rejects the token outright.</p><p>This is the entire security model of a JWT in one sentence: <strong>the data inside a JWT is readable by anyone, but only verifiable and provably untampered by someone holding the correct key.</strong></p><h4>JWT-Based Authentication: The Standard Flow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOR5BZYvPfaIi26h4NGjXQ.png" /></figure><p>Here’s how a basic JWT-based authentication system works, without any external identity provider involved:</p><ol><li>The <strong>web client</strong> sends a <strong>username and password</strong> to the server.</li><li>The server checks: <strong>valid?</strong></li><li>If valid, the server <strong>creates a JWT</strong>, signing it with its own <strong>private key</strong>.</li><li>That JWT is sent back to the client, which stores it (in <strong>storage</strong>, typically local storage, memory, or a cookie depending on the app).</li><li>On future requests, the client sends its task along with the <strong>JWT in the header</strong>.</li><li>The server checks: <strong>valid JWT?</strong>, verifying the signature using its <strong>public key</strong>.</li><li>If valid, the server returns the <strong>result</strong>.</li></ol><p>The note in the diagram is worth calling out explicitly: <strong>this system is decentralized and stateless.</strong> Unlike session-based authentication, the server doesn’t need to look anything up in a database or session store to verify the request. All the information needed to verify the token is contained within the token itself, plus the public key. This is precisely why JWTs scale so well across multiple servers with no shared state required.</p><h4>JWT-Based Authentication with OAuth Flow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TlC0rvUWVdrb30F3bNZN8Q.png" /></figure><p>Now here’s the more realistic, production version of this same idea, where the authentication and the application are handled by two separate systems.</p><ol><li>The <strong>web client</strong> sends a <strong>username and password</strong>, but this time to a dedicated <strong>Authorization Server (Cognito)</strong>, not to the application itself.</li><li>Cognito checks: <strong>valid?</strong></li><li>If valid, Cognito <strong>creates a JWT</strong>, signed with a <strong>public private key pair</strong> it manages.</li><li>That JWT is sent back to the client and stored.</li><li>The client sends its task, with the <strong>JWT in the header</strong>, to <strong>My Application Server</strong>, a completely separate system from Cognito.</li><li>My Application Server needs to verify this JWT, but it didn’t issue the token itself, so it doesn’t already have the key. It <strong>fetches the public keys</strong> from Cognito to verify the JWT’s signature.</li><li>Once verified, it checks: <strong>valid JWT?</strong></li><li>If valid, it returns the <strong>result</strong>.</li></ol><h4>Comparing the Two Approaches</h4><p>The core difference between these two flows comes down to <strong>who issues the token versus who verifies it</strong>.</p><p>In the <strong>standard flow</strong>, the same server both issues and verifies the JWT. It holds both the private key (to sign) and the public key (to verify), all in one place.</p><p>In the <strong>OAuth-based flow</strong>, these responsibilities are split. Cognito (the Authorization Server) is solely responsible for authenticating users and issuing tokens. Your application server never sees a username or password at all. It only receives a token, fetches Cognito’s public keys, and verifies the signature independently.</p><p><strong>Advantages of the standard flow:</strong> simpler to set up, fewer moving parts, no external dependency for verification.</p><p><strong>Advantages of the OAuth-based flow:</strong> your application never touches raw credentials, authentication logic is centralized and reusable across multiple applications, and identity providers like Cognito handle the heavy lifting of security best practices (password policies, MFA, breach detection, and so on) so you don’t have to build and maintain that yourself.</p><p>This is exactly why most real-world, production systems today lean toward the second pattern, especially once you have more than one application that needs to share the same user base.</p><h3>ID Token vs Access Token vs Refresh Token: Knowing Which One to Use</h3><p>This is the point in learning Auth where most people start mixing things up, because all three of these are JWTs (well, almost, more on that shortly), they often arrive together, and they all live in the same request. But each one answers a completely different question, and using the wrong one in the wrong place is one of the most common mistakes in real implementations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u44rc7cY4y7DpYgMcc3iaA.png" /></figure><h4>ID Token: “Here’s who authenticated”</h4><p>The <strong>ID Token</strong> is an OpenID Connect (OIDC) identity token. Its entire purpose is to tell the client application <strong>who authenticated</strong>. Nothing more.</p><p>This is worth repeating clearly: <strong>the ID token exists to establish identity, not to grant access.</strong> It should never be used to authorize a request to an API.</p><p>Example payload:</p><p>json</p><pre>{<br>  &quot;sub&quot;: &quot;7f3b...&quot;,<br>  &quot;email&quot;: &quot;amey@example.com&quot;,<br>  &quot;name&quot;: &quot;Amey Kulkarni&quot;,<br>  &quot;email_verified&quot;: true,<br>  &quot;iss&quot;: &quot;https://cognito-idp.us-east-1.amazonaws.com/us-east-1_ABC&quot;,<br>  &quot;aud&quot;: &quot;6iffu8kd7eid8dt9qmlauo36cu&quot;,<br>  &quot;token_use&quot;: &quot;id&quot;,<br>  &quot;auth_time&quot;: 1786750000,<br>  &quot;iat&quot;: 1786750000,<br>  &quot;exp&quot;: 1786753600<br>}</pre><p><strong>What belongs in an ID token:</strong> sub (uniquely identifies the user), email, name, iss (issuer), aud (audience), exp (expiry), iat (issued at), auth_time, nonce.</p><p>One claim worth explaining properly since it causes confusion: <strong>aud stands for audience</strong>. It identifies <em>which specific client application</em> this token was issued for, in Cognito&#39;s case, this is the App Client ID. When an application verifies a token, it must check that the aud matches its own client ID. If it doesn&#39;t, the token was meant for a different application entirely, and should be rejected, even if the signature is otherwise valid. Skipping this check is a real vulnerability: it would let a token issued for App A be replayed and accepted by App B.</p><p><strong>What does not belong in an ID token, ever:</strong></p><ul><li>Passwords</li><li>Secrets, like stripe_secret_key or database_password</li><li>Large user profiles, bank account details, private financial information, medical information, or any other sensitive internal data</li></ul><p>Why this matters: an ID token (and JWTs in general) is <strong>not encrypted</strong>, it’s just Base64-encoded and signed. Anyone holding the token can decode and read the payload in plain text. The signature only proves it hasn’t been tampered with, it does nothing to hide the contents. So the golden rule is: <strong>never put anything in a token that you wouldn’t be comfortable showing to the user holding it.</strong></p><h4>Access Token: “Here’s what this client can do”</h4><p>The <strong>Access Token</strong> answers a completely different question: <strong>“Can this client access my API, and what exactly is it allowed to do?”</strong></p><p>Example payload:</p><p>json</p><pre>{<br>  &quot;sub&quot;: &quot;7f3b2c...&quot;,<br>  &quot;client_id&quot;: &quot;6iffu8kd7eid8dt9qmlauo36cu&quot;,<br>  &quot;scope&quot;: &quot;openid profile device.read&quot;,<br>  &quot;username&quot;: &quot;amey&quot;,<br>  &quot;iss&quot;: &quot;https://cognito-idp.us-east-1.amazonaws.com/us-east-1_ABC&quot;,<br>  &quot;token_use&quot;: &quot;access&quot;,<br>  &quot;iat&quot;: 1786750000,<br>  &quot;exp&quot;: 1786753600<br>}</pre><p>The most important concept here is <strong>scopes</strong>. A scope defines a specific, narrow permission, for example:</p><ul><li>device.read</li><li>device.write</li><li>device.delete</li></ul><p>These map directly onto real API operations. A GET /devices request requires the device.read scope. A POST /devices request requires device.write. A DELETE /devices/123 request requires device.delete. This is a practical implementation of <strong>Role-Based Access Control (RBAC)</strong>: instead of an API just checking &quot;is this request authenticated,&quot; it checks &quot;does this specific token carry the specific scope needed for this specific action.&quot;</p><p>Cognito can also attach <strong>custom claims</strong>, like cognito:groups, which might list something like [&quot;admins&quot;]. This is useful, but comes with an important caveat: <strong>a claim can inform an authorization decision, but your API must still enforce that decision itself.</strong> A claim saying someone is in the &quot;admins&quot; group doesn&#39;t automatically restrict anything, your backend logic still has to check for it and act on it.</p><p><strong>What does not belong in an Access token, ever:</strong></p><ul><li>Passwords</li><li>API keys</li><li>Database credentials</li><li>Secrets of any kind</li><li>Huge amounts of application data</li></ul><p>Same reasoning as before: it’s readable by anyone who has it. An access token should carry just enough information to make an authorization decision, nothing more.</p><h4>Refresh Token: “Let me back in without logging in again”</h4><p>The <strong>Refresh Token</strong> exists to solve one specific problem: access tokens are intentionally short-lived (for security), but forcing a user to log in again every time one expires would be a terrible experience. The refresh token is the mechanism that prevents that.</p><p>Here’s the flow:</p><ol><li>Cognito issues an <strong>Access Token</strong> to the client.</li><li>That access token <strong>expires</strong> after some time.</li><li>Instead of logging in again, the client uses its <strong>Refresh Token</strong> to ask Cognito for a <strong>new Access Token</strong>.</li><li>Cognito checks the refresh token and, if it’s still valid, issues a fresh access token, no re-login required.</li></ol><p>In plain terms, a refresh token is essentially saying: <strong>“I previously authenticated this client. Please give me a new access token without making me log in again.”</strong></p><p>Here’s a structural detail that matters: <strong>ID tokens and Access tokens are JWTs. Refresh tokens are typically opaque tokens.</strong> An opaque token isn’t a JWT at all, it’s just a random string with no readable structure. It has no meaning on its own; it only means something to Cognito, which is the only party that can look it up and validate it. This is actually a deliberate security design: since a refresh token is far more sensitive (it can be used to mint new access tokens over and over), keeping it as an opaque, non-decodable string reduces what an attacker could learn even if they intercepted one.</p><p><strong>What should never happen with a refresh token:</strong></p><ul><li>Never log refresh tokens</li><li>Never send refresh tokens to your backend unnecessarily</li><li>Never put refresh tokens in URLs</li><li>Never put them in analytics events</li><li>Never console.log() them</li></ul><p>These aren’t arbitrary rules. A refresh token is effectively a long-lived key to re-authenticate as the user. If it leaks, an attacker doesn’t just get one session, they get the ability to keep generating valid access tokens until the refresh token itself is revoked or expires. It should be treated with the same level of care as a password, if not more.</p><h4>Quick Reference: Where to Use What</h4><p>TokenAnswersUsed ForFormat<strong>ID Token</strong>Who is this?Displaying user identity to your frontend/client appJWT<strong>Access Token</strong>What can this client do?Authorizing API requests to your backend/resource serverJWT<strong>Refresh Token</strong>Can I get a new access token?Silently renewing sessions without re-loginOpaque token</p><p>The single rule to walk away with: <strong>never use an ID token to authorize an API call, and never expose a refresh token anywhere it doesn’t strictly need to be.</strong> Getting this one distinction right avoids most of the real-world security mistakes people make when implementing Auth.</p><h3>Cognito Identity Pool: Exchanging Identity for AWS Access</h3><p>Let’s start with the actual problem this solves, because that’s the part that makes everything else click.</p><p>Say you’ve built an app. Users sign in through <strong>Cognito User Pool</strong>, or maybe through Google or Facebook. At this point, you have a <strong>JWT</strong> proving who they are. Great, authentication is solved.</p><p>But now imagine your app needs to let that user directly upload a file to an <strong>S3 bucket</strong> from their phone or browser. Or read from a <strong>DynamoDB</strong> table directly. Or call some other AWS service, directly, without routing every single request through your own backend server first.</p><p>Here’s the problem: <strong>a Cognito JWT (or a Google token, or a Facebook token) means absolutely nothing to AWS on its own.</strong> AWS doesn’t know what a Cognito JWT is. AWS only understands its own permission system: <strong>IAM</strong>. To touch an AWS resource, you need actual <strong>AWS credentials</strong> (an access key, a secret key, and a session token), not a JWT from an identity provider.</p><p>So the real question becomes: <strong>how do you take a token from Cognito, Google, or Facebook, and turn it into real, temporary AWS credentials that are scoped to exactly what this user should be allowed to do?</strong></p><p>This is exactly what a <strong>Cognito Identity Pool</strong> is for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_X8YnH57kMn3-oEQx3QDQ.png" /></figure><h4>What an Identity Pool Actually Does</h4><p>An <strong>Identity Pool</strong> is a token exchange service. It takes an identity you already have (or no identity at all) and exchanges it for <strong>temporary AWS credentials</strong>, issued through <strong>AWS STS (Security Token Service)</strong>, mapped to a specific <strong>IAM Role</strong>.</p><p>This is the core distinction worth repeating: <strong>the User Pool answers “who is this person.” The Identity Pool answers “given who this person is (or isn’t), what temporary AWS access should they get.”</strong></p><p>There are two distinct paths through an Identity Pool, and the diagram lays both out clearly.</p><h4>Path 1: The Guest</h4><p>Looking at the diagram, <strong>any random user</strong>, someone who hasn’t logged in at all, can still hit the Identity Pool as a <strong>Guest</strong>. Guest access exists for exactly the situations where you want to allow some limited, unauthenticated functionality. Think of a public app that shows a read-only map, or lets anonymous visitors browse content before signing up.</p><p>In this path, the Identity Pool maps the guest straight to a <strong>ReadOnly Role</strong>, an IAM role with deliberately minimal permissions, just enough to do the safe, public-facing actions you’ve decided anonymous users are allowed to do.</p><h4>Path 2: The Authenticated User</h4><p>The second path is for a user who has already proven their identity, either through <strong>Cognito</strong>, or through an external identity provider like <strong>Google</strong>. Once that identity is established, the token from that provider is sent to the Identity Pool, which recognizes it as coming from a <strong>trusted, authenticated source</strong>.</p><p>Here’s where it gets more powerful: the Identity Pool doesn’t just hand out one generic “logged in” role. Looking at the diagram, an authenticated user can be mapped to <strong>different IAM roles depending on rules you configure</strong>, a “Role with edit,” a “Role with assign,” or some other custom role entirely. This mapping can depend on things like which identity provider they came through, or custom attributes and groups attached to their identity (this is that cognito:groups claim from the previous section coming back into play).</p><h4>Where This Actually Gets Used: API Gateway with IAM Authorization</h4><p>Here’s where this concept becomes very concrete in a real architecture.</p><p>Say you have an <strong>API Gateway</strong> in front of your backend, and you’ve configured it to use <strong>IAM authorization</strong> instead of a Lambda authorizer or a Cognito User Pool authorizer. This means API Gateway will only accept requests that are <strong>signed with valid AWS credentials</strong>, tied to a specific IAM role.</p><p>This is exactly the gap an Identity Pool fills. The flow looks like this:</p><ol><li>A user logs in through Cognito User Pool (or Google), and gets a JWT.</li><li>That JWT is exchanged with the <strong>Cognito Identity Pool</strong> for temporary AWS credentials, scoped to a specific IAM Role, based on who this user is.</li><li>The client uses those temporary credentials to <strong>sign requests directly to API Gateway</strong> (or directly to S3, or DynamoDB).</li><li>API Gateway’s IAM authorizer checks the signed request against IAM, confirming this request is coming from a valid, permitted role, and either allows or denies it accordingly.</li></ol><p>Notice what’s happening here: at no point does API Gateway need to understand JWTs, Cognito, or Google at all. It only ever deals in IAM, the language AWS itself speaks. The Identity Pool is the translator that sits between “an identity from some provider” and “an AWS-native credential AWS services actually understand.”</p><h4>User Pool vs Identity Pool: The Difference That Matters</h4><p>It’s worth locking this in clearly, since it’s the single most confused pairing in this entire topic:</p><p>Cognito User PoolCognito Identity Pool<strong>Solves</strong>AuthenticationAuthorization to AWS resources<strong>Answers</strong>Who is this person?What AWS access should they get?<strong>Output</strong>A JWT (ID Token, Access Token)Temporary AWS credentials via STS<strong>Understood by</strong>Your own applicationAWS services directly (S3, DynamoDB, API Gateway with IAM auth, etc.)</p><p>A useful way to think about it: the <strong>User Pool proves identity</strong>. The <strong>Identity Pool converts that identity into AWS-native permission</strong>. They’re often used together, one right after the other, but they are solving two entirely separate problems, and neither one can substitute for the other.</p><p>Here’s Sections 9 &amp; 10: Machine-to-Machine Authentication and SSO.</p><h3>Machine-to-Machine (M2M) Authentication: When There’s No Human in the Loop</h3><p>Everything covered so far, Basic/Digest/Session auth, OIDC, the Authorization Code grant, assumes a human is sitting at a screen, typing a password or clicking “Sign in with Google.” But a huge amount of real-world traffic has no human involved at all: a backend service calling another backend service, a scheduled job pulling data from a third-party API, a microservice talking to another microservice inside your own infrastructure.</p><p>This is exactly the situation <strong>Machine-to-Machine (M2M) authentication</strong> is built for, and it’s why the <strong>client_credential grant type</strong> exists (mentioned back in Section 5, this is where it actually gets used).</p><h4>How it works</h4><p>Recall the OAuth roles from earlier: Resource Owner, Client, Authorization Server, Resource Server. In a human login flow, the Resource Owner is a person approving access. In M2M, <strong>there is no Resource Owner at all</strong>. The client is simply authenticating as itself.</p><p>Here’s the flow:</p><ol><li>A service (the <strong>Client</strong>) has a <strong>Client ID</strong> and a <strong>Client Secret</strong>, issued once, ahead of time, when the integration is set up.</li><li>That service sends its Client ID and Client Secret directly to the <strong>Authorization Server</strong> (Cognito, or any OAuth-compliant provider), essentially saying “this is who I am, prove me right.”</li><li>The Authorization Server validates the credentials and issues an <strong>Access Token</strong>, the same JWT structure covered earlier, but this time the sub claim identifies the service itself, not a human user.</li><li>The service uses that Access Token to call the <strong>Resource Server</strong>, exactly like before.</li></ol><p>No login screen. No redirect. No browser. Just two systems, a shared secret established in advance, and a token exchange.</p><h4>Where you’ll actually see this</h4><ul><li>A backend job that syncs data from a payment provider’s API on a schedule</li><li>Two internal microservices authenticating to each other inside the same infrastructure</li><li>A CI/CD pipeline authenticating to a cloud provider to deploy infrastructure</li><li>Any scenario where “logging in” doesn’t make sense, because there’s no person to log in</li></ul><h4>The one thing that matters most here</h4><p>Since there’s no human re-entering a password to prove trust, <strong>the Client Secret itself becomes the single point of trust.</strong> If it leaks, an attacker can impersonate that entire service with no further verification needed. This is why Client Secrets are treated the way API keys were in Section 2: never hardcoded in source code, never committed to a repository, always stored in a secrets manager, and rotated periodically.</p><p>M2M authentication is really just OAuth 2.0 stripped down to its simplest form: two systems, one shared secret, one token, no human required.</p><h3>SSO: Single Sign-On, the User Experience Layer</h3><p>Unlike everything else in this article, <strong>SSO isn’t a protocol or a token type. It’s a user experience pattern.</strong> It describes a goal: <em>log in once, get access everywhere</em>, and multiple different protocols can be used underneath to achieve it.</p><p>You’ve actually already learned the exact protocol that makes most modern SSO possible: <strong>OIDC</strong>, from Section 3.</p><h4>The core idea</h4><p>Instead of every application maintaining its own separate login system, all of them trust a single, central <strong>Identity Provider (IdP)</strong>. Once a user authenticates with that IdP one time, every connected application can verify that same identity without asking the user to log in again.</p><p>This is the exact experience behind things like:</p><ul><li>Signing into Gmail once, and getting access to Google Docs, Google Drive, and YouTube without logging in again</li><li>A company using <strong>Okta</strong> or <strong>Azure AD</strong>, where one login gives an employee access to Slack, Jira, and their email, all without separate credentials for each</li></ul><h4>How it actually works under the hood</h4><p>The mechanics are the same building blocks from earlier in this article, just applied across multiple applications instead of one:</p><ol><li>A user tries to access <strong>App A</strong>. App A doesn’t handle login itself, it redirects the user to the central <strong>Identity Provider</strong>.</li><li>The user logs in once, at the Identity Provider.</li><li>The Identity Provider issues tokens (this is OIDC in action, an ID Token establishing who they are).</li><li>Now the user tries to access <strong>App B</strong>. App B also trusts the same Identity Provider. Since the Identity Provider already has an active session for this user, it issues a new token <strong>without asking the user to log in again</strong>.</li></ol><p>The user experiences this as “I only logged in once.” Under the hood, it’s the same OIDC flow from Section 3, just being reused across multiple applications that all agree to trust the same identity source.</p><h4>Identity protocols behind SSO</h4><p>A few protocols are commonly used to implement SSO, and it’s worth being able to name them, even briefly:</p><ul><li><strong>OIDC</strong>, the one covered in depth already, common in modern consumer and cloud-native apps.</li><li><strong>SAML (Security Assertion Markup Language)</strong>, an older, XML-based protocol, still very common in enterprise environments (this is often what’s happening when a company’s internal tools all connect to something like Okta or Azure AD).</li><li><strong>Kerberos</strong>, used mostly in traditional, on-premise corporate networks (like older Windows domain environments), predating both of the above.</li></ul><h4>The distinction to hold onto</h4><p>SSO is the <strong>what</strong>: log in once, access many things. OIDC (or SAML, or Kerberos) is the <strong>how</strong>: the actual protocol handling the identity verification and token exchange underneath it. Just like OAuth 2.0 is the framework and JWT is the token format, SSO is the experience, and it’s built on top of the same authentication and authorization mechanics covered throughout this entire article.</p><h3>Wrapping Up</h3><p>That’s the full journey, starting from a single question, “who are you, and what are you allowed to do,” all the way through Basic Auth, OIDC, AWS Cognito, OAuth 2.0, JWTs, token types, Identity Pools, M2M auth, and SSO.</p><p>If there’s one thread to pull through all of it: <strong>authentication and authorization are never really “solved” by memorizing a protocol.</strong> They’re solved by understanding <em>why</em> each piece exists, what problem it was built to fix, and where it fits next to everything else. That’s exactly why almost every section here kept circling back to the same core split: who is this, versus what are they allowed to do.</p><p>This entire write-up came out of my own notes while studying this space seriously, so if something here helped a concept click for you, or if you spot something you’d explain differently, I’d genuinely love to hear it.</p><p>If this was useful, a <strong>clap</strong> goes a long way, and if you have questions, corrections, or just want to talk auth, drop a <strong>comment</strong> below or feel free to <strong>get in touch</strong>. Always happy to nerd out about this stuff.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e37d68a3d7a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Was Tired of Watching 40-Hour Lectures, So I Built an AI Search Engine to Find Exact Answers]]></title>
            <link>https://medium.com/@kulkarniamey2004/i-was-tired-of-watching-40-hour-lectures-so-i-built-an-ai-search-engine-to-find-exact-answers-7e7f698216a8?source=rss-5e71b191d697------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e7f698216a8</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[spirituality]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Amey Kulkarni]]></dc:creator>
            <pubDate>Sun, 14 Jun 2026 13:07:49 GMT</pubDate>
            <atom:updated>2026-06-14T13:07:49.140Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YTr0ZuqVVhKyG1UJpwo4gw.png" /></figure><h3>The Problem: Too Much Content, Not Enough Time</h3><p>I had a very practical problem. There is an incredible amount of deep, spiritual knowledge locked away in thick PDFs and massive Y<strong>ouTube playlists</strong> specifically regional <em>Marathi</em> discourses.</p><p>As someone trying to genuinely understand these concepts, I wanted to find answers to specific disciple queries. But let’s be real: with today’s fast-paced lifestyle, manually sifting through <strong>40-hour video series or reading entire books just to find <em>one</em> specific answer</strong> is practically impossible.</p><p>I initially thought about using existing AI tools, but they totally miss the mark for this use case. If I have a question about a complex philosophical concept, I don’t want a generic, hallucinated summary from a chatbot. I want the <strong>exact teaching</strong>, the <strong>original parable</strong>, or the <strong>specific practical advice</strong>, delivered in its <em>original context</em>. Furthermore, standard search tools are terrible at handling regional languages natively.</p><p>I couldn’t find a tool that did this, <strong>so I built one.</strong></p><p>I engineered a <strong>Multimodal Video Search Engine</strong> a fully serverless application built on AWS that lets users search for spiritual concepts by <em>meaning</em>. Instead of just generating a summary, the system searches through transcripts and texts, understands the context, and instantly drops you at the <strong>exact video timestamp</strong> or the <strong>exact book page</strong> where your answer is discussed.</p><p>Building this wasn’t just about solving my own query problem; it ended up being a massive deep-dive into cloud engineering, handling incredibly messy regional data, and building real-world AI pipelines.</p><p>Here is exactly how I built it.</p><p>Here is the draft for Section 1. It is written directly from your perspective as the engineer, strictly follows the flow of your uploaded diagram, and keeps the technical explanation grounded and easy to digest without unnecessary jargon.</p><p>You can drop your diagram right below the section heading on Medium.</p><h3>Section 1: The Data Pipeline (Ingestion &amp; Chunking)</h3><p>Before the system can search for anything, it needs to ingest, process, and store the raw data. Looking at the architecture diagram, the pipeline is split into three distinct phases: gathering the data, chunking it intelligently, and converting it into a format the AI can understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xi4Zj-D_FU95ZkscoBcvhA.png" /></figure><p><strong>1. Getting the Data</strong></p><p>I had three completely different types of data sources to handle, so I built three dedicated ingestion routes:</p><ul><li><strong>YouTube Videos:</strong> Running heavy local speech-to-text models on gigabytes of video takes hours and destroys laptop CPUs. To keep things fast and lightweight, I completely bypassed local processing. Instead, I used the youtube-transcript-api to instantly pull native transcripts.</li><li><strong>Book PDFs:</strong> For scanned spiritual texts, the pipeline routes the documents through <strong>Tesseract and PyTorch OCR</strong> to extract the text accurately while preserving the structure.</li><li><strong>Raw Audio Input:</strong> For standalone audio files that don’t have pre-existing transcripts, the system relies on OpenAI’s <strong>Whisper</strong> model to generate the text.</li></ul><p><strong>2. Intelligent Chunking (Finding the Pauses)</strong></p><p>All three ingestion streams eventually funnel down into a single crucial step: <strong>Chunking</strong>.</p><p>This is where a lot of standard AI applications fail. The standard approach is to just chop the text every 500 characters. But if you blindly cut a sentence or a spiritual thought in half, the AI loses the entire context. To fix this, I engineered a chunking strategy that looks for <em>ideas</em> instead of just character counts.</p><p>The system accumulates the text, but it refuses to make a cut until it detects a <strong>natural pause</strong> like the speaker taking a breath or reaching the end of a thought. This ensures that the AI is digesting complete, meaningful blocks of information.</p><p><strong>3. Vectorization &amp; Storage (BGE-M3 and Qdrant)</strong></p><p>Once the chunks are contextually solid, they move to the Hugging Face <strong>BGE-M3 model</strong>. I chose this specific model because it is incredibly good at handling regional languages and complex text.</p><p>As shown in the diagram, the model processes the text into two distinct formats simultaneously:</p><ul><li><strong>Dense Vectors:</strong> These capture the underlying meaning and semantic “vibe” of the text (so a search for “finding peace” matches the Marathi equivalent).</li><li><strong>Sparse Vectors (BM25):</strong> These capture the exact keywords, acting like a traditional search engine so that specific names or quotes are never lost.</li></ul><p>Finally, both sets of vectors are loaded into the <strong>Qdrant Vector Database</strong>. By storing both the deep meaning and the exact keywords, the database is perfectly primed to answer highly specific disciple queries instantly.</p><h3>Section 2: Pinpointing the Exact Timestamp</h3><p>Once the text was properly chunked, I ran into another major issue: connecting those newly formed chunks back to the video.</p><p>When you pull transcripts from YouTube, they arrive as hundreds of tiny, disjointed fragments (often just a second or two long). To process them intelligently, I had to stitch all those fragments together into one massive, continuous text block. But the moment you glue everything together, you lose the connection to the original start times. If the AI finds the answer to a query in paragraph four, how do you know what exact second of the video that corresponds to?</p><p>To solve this, I built a background mapping system.</p><p>As the system stitches the tiny text fragments together, it builds a continuous <strong>Character-to-Time Map</strong>. For every single fragment, it records exactly where it was placed (the character index), when it started, and how long it lasted.</p><p>When a user searches for a concept and the database finds the matching chunk, the system uses that map to get the exact timestamp using two simple steps:</p><ol><li><strong>Binary Search:</strong> It quickly scans the map to find exactly which original transcript fragment the matched text belonged to.</li><li><strong>Proportional Math:</strong> It calculates how far into that fragment the specific word sits. For example, if the target word starts exactly halfway through the text fragment, the system applies that same ratio to the time. It takes the fragment’s start time, adds 50% of its duration, and calculates the precise second the word was spoken.</li></ol><p>This mathematical approach ensures that when a user clicks a search result, the video starts playing at the exact moment the speaker begins that specific thought, rather than just a rough guess.</p><h3>Section 3: Why OpenAI Failed &amp; BGE-M3 Triumphed (The Embedding Layer)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/0*li_sRh0uEHNsBfLh.png" /></figure><p>Once the text chunks and their exact timestamps were perfectly aligned, the next challenge was making them searchable. This required converting the text into mathematical vectors (embeddings).</p><p>My initial instinct was to use the industry standard: OpenAI’s text-embedding-ada-002. But after running a few tests, it completely fell apart. Standard models are overwhelmingly English-first. When fed native Marathi Devanagari text, they create isolated, poor-quality vectors. Furthermore, a disciple searching for &quot;spiritual awakening&quot; in English wouldn&#39;t match with the Marathi text for &quot;आत्मज्ञान&quot; (Self-realization).</p><p>I needed a model that could natively handle regional languages without requiring a clumsy, real-time translation layer in the backend.</p><p>The perfect solution was <strong>BAAI/bge-m3</strong> from Hugging Face. Running this lightweight (2.27 GB) model on a free Google Colab T4 GPU completely unlocked the project. It solved my three biggest bottlenecks simultaneously:</p><p><strong>1. Multi-Linguality (The Marathi-to-English Bridge)</strong> BGE-M3 was trained across 170+ languages and places concepts from different languages into the exact same semantic vector space. This means I didn’t need to translate the user’s search query. A user can search in English, native Marathi, or even Hinglish/Minglish, and the model inherently knows that the query maps directly to the corresponding native text in the database.</p><p><strong>2. Multi-Granularity (Beating the 512-Token Limit)</strong> Standard models have a strict maximum limit of 512 tokens. If a beautiful, 3-minute spiritual story about Saint Tukaram translates to 700 tokens, standard models brutally chop off the ending — destroying the moral of the story. BGE-M3 utilizes the MCLS method to extend its context window to a massive <strong>8192 tokens</strong>. This allowed me to embed massive blocks of text as a single, highly accurate vector without losing the deep philosophical context.</p><p><strong>3. Multi-Functionality (The Hybrid Search Advantage)</strong> When users search spiritual texts, they search in two very different ways. Sometimes they search by <em>meaning</em> (“how to control the ego”), and sometimes they search for <em>exact keywords</em> (“प्रारब्ध” or a specific saint’s name).</p><ul><li>If you only use Dense vectors (semantic search), highly specific names and quotes get blurred out.</li><li>If you only use Sparse vectors (keyword search), you lose all conceptual understanding.</li></ul><p>BGE-M3 computes both simultaneously in one pass. It generates <strong>Dense Vectors</strong> to capture the overarching “vibe” of the text, and <strong>Sparse Vectors</strong> (acting like an AI-powered BM25) to give a massive scoring boost to exact keyword matches.</p><p>By executing a Hybrid Search in the backend, I guaranteed that the user receives a result that conceptually answers their question <em>and</em> contains the exact spiritual terminology they searched for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vjBVXUoDxZbkOlHPU7YyHg.png" /></figure><p>Here is the draft for Section 4, written with a clean, respectful, and direct tone that focuses purely on the core engineering logic.</p><h3>Section 4: Turning Transcripts Into Structured Data With Gemini</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-FXhW2YUAQjLLc-KsGOOQ.png" /></figure><p>While having raw text transcripts is a great starting point, a wall of continuous text isn’t deeply useful on its own. These are rich spiritual discourses filled with distinct elements: deep philosophical questions from the audience, parables shared by the speaker, practical lifestyle advice, and sudden shifts into devotional singing.</p><p>If a user searches for a specific song or a practical meditation technique, standard text search can’t easily differentiate between a casual mention of a word and a dedicated segment. To solve this, I introduced a <strong>Gemini-driven enrichment layer</strong> to organize the data.</p><p>I passed the full transcripts to Gemini with a strict system prompt, instructing it to act as a structured analyst. Instead of summarizing the content, the model was forced to break down the discourse and output raw, structured JSON containing five distinct categories:</p><ol><li><strong>Queries:</strong> Actual, real-world questions that are directly answered in the discourse.</li><li><strong>Actionable Practices:</strong> Practical, everyday advice given to help a seeker in their daily routine.</li><li><strong>Stories &amp; Parables:</strong> Detailed anecdotes or traditional stories used to explain a concept, along with the specific moral of the story.</li><li><strong>Musical Segments:</strong> Dedicated instances of <em>Bhajans</em>, <em>Aartis</em>, or <em>Namasmarana</em> (chanting), while ignoring standard background filler music.</li><li><strong>Topics:</strong> Broader thematic tags to categorize the overall discussion.</li></ol><p><strong>The Logic Behind the Mapping</strong> Extracting these categories into JSON was only half the battle. If Gemini identified a beautiful story about a saint, how would the backend know exactly when that story started in the video?</p><p>To make this work, I instructed the prompt to return a field called exact_start_text. Gemini was required to copy the first 7 to 10 words of the segment exactly as they appeared in the raw transcript.</p><p>Once the JSON was generated, the backend script ran a quick text-matching routine to locate those exact 7 words within the stitched master text. As soon as it found the character index of that phrase, it passed it to the math engine we discussed earlier, calculating the exact second that story or Bhajan began.</p><p>Finally, to make the pipeline reliable when processing thousands of hours of content, I built in strict error handling. If the script hits API rate limits, it automatically pauses, sleeps, and backs off before retrying, ensuring the pipeline completes without crashing.</p><h3>Section 5: Improving Discovery through Intelligent Related Queries</h3><p>the knowledge graph of queries in qdrant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fkb-gF5bNhU-0zgWJl4i4w.png" /></figure><p>When you build a semantic search engine, suggesting “Related Queries” is a standard feature. However, while testing the system, I realized that a standard top-5 semantic search created a bit of an “echo chamber.”</p><p>In a spiritual context, if a user is searching for something heavy like <em>suffering</em> or <em>sorrow</em>, a standard engine will suggest five more queries strictly about sorrow. Instead of helping, this keeps the user stuck in a single, potentially negative mental loop. I wanted the engine to act more like a guide, helping the user move from a specific problem to a broader perspective.</p><p><strong>The Exploration Mix</strong> To fix this, I designed a specific “Exploration Mix” for the related queries fetched from the database. Instead of just taking the top five nearest results, the backend combines three different types of queries:</p><ol><li><strong>Direct Matches:</strong> The top three semantic results. These directly validate what the user is currently asking about.</li><li><strong>Tangential Matches:</strong> The system looks further down the list of the top 20 results and picks one at random. This offers an “adjacent” thought — something the user wasn’t directly asking, but is philosophically related.</li><li><strong>The Wildcard:</strong> The backend generates a completely randomized vector and searches the database. This pulls a query from an entirely different cluster of the map (as seen in the graph photo). It might pull a query about a completely different devotional practice or a story.</li></ol><p><strong>Visualizing the Ideas</strong> Looking at the graph of our query database, you can see how different spiritual concepts form “clusters.” By using this mix, the system can bridge the gap between these clusters.</p><p>This approach mirrors how a real teacher often answers a question. They start by addressing the student’s immediate doubt (Direct), then move into a broader philosophical concept (Tangential), and finally might suggest a devotional practice or a story (Wildcard) to shift the student’s focus toward a more positive state of mind.</p><p>By engineering the related queries this way, the search engine doesn’t just return data, it helps the seeker transition from doubt and intellect toward emotional calmness and spiritual practice.</p><h3>Section 6: Minimizing Costs with an AWS Serverless Architecture</h3><p>Building a complex, multimodal AI search engine is great, but hosting it can quickly become a financial black hole. If I had deployed this backend on a traditional EC2 instance or a 24/7 Docker container, I would be paying for idle compute time every single minute of the day.</p><p>Here is how the infrastructure is broken down to ensure a pay-per-request model:</p><p><strong>1. On-Demand Compute (AWS Lambda &amp; API Gateway)</strong> Instead of a constantly running server, the backend is split into independent, stateless <strong>Python 3.12 Lambda functions</strong> (e.g., /search, /videos, /stories). These functions sit behind an <strong>Amazon API Gateway</strong>.</p><ul><li>The compute resources physically do not exist until a user makes a query.</li><li>I only pay for the exact milliseconds the search takes to execute. When the system is idle, the compute cost is strictly zero.</li></ul><p><strong>2. The Dual-Database Strategy</strong> Storing high-dimensional vectors and rich metadata together in a traditional relational database gets expensive and slow. I split the data layer in two:</p><ul><li><strong>DynamoDB (Metadata):</strong> I used an On-Demand (PAY_PER_REQUEST) DynamoDB table to store the structured metadata extracted by the LLM. It provides single-digit millisecond lookups, and again, costs nothing when idle.</li><li><strong>Qdrant Cloud (Vectors):</strong> The actual semantic vectors are offloaded to Qdrant, which natively handles the mathematical search and pagination without requiring a secondary database.</li></ul><p><strong>3. Frontend Delivery (S3 + CloudFront)</strong> The frontend is a standard React/Vite Single Page Application (SPA). There is no Node.js server running the UI. The static assets are hosted in a private <strong>Amazon S3</strong> bucket and delivered globally via <strong>Amazon CloudFront</strong>.</p><ul><li>CloudFront caches the UI, meaning it loads instantly anywhere in the world for fractions of a cent.</li><li>To handle standard React Router behavior, CloudFront uses a simple Custom Error Response to redirect 404s back to index.html.</li></ul><h3>Conclusion:</h3><p>Building this search engine was never just a technical exercise; it was about removing the barriers to spiritual learning. By combining cloud-native architecture with multi-lingual AI, disciples no longer have to choose between their demanding modern lifestyles and their spiritual upbringing. They can ask complex, personal questions and instantly connect with the exact teachings, stories, and practices they need to find clarity and calmness.</p><p>But the platform is not entirely complete yet. While extracting the exact text and timestamping the original videos is a massive step forward, the ultimate medium of spiritual transmission is the Guru’s actual voice (वाणी).</p><p>My next engineering assignment is diving deeply into <strong>voice cloning using tools like ElevenLabs and Indic F5</strong>. As of right now, high-quality, emotionally accurate voice cloning for regional languages like Marathi simply does not exist in an appropriate, production-ready sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MHg5pPIvARnlpsEl.png" /></figure><p>Solving this Marathi voice-cloning gap will be the next evolution of this project. I found Elven labs as a good soln to actually work with.<br>The goal is to eventually allow the system to read retrieved textual answers, stories, or ancient PDFs aloud in the comforting, authentic cadence of the original speaker. Ultimately, this entire pipeline serves one single purpose: using modern cloud engineering to make timeless wisdom seamlessly accessible for the modern disciple</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e7f698216a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making AI Think Like a Software Architect]]></title>
            <link>https://medium.com/@kulkarniamey2004/making-ai-think-like-a-software-architect-e7bd88c248ca?source=rss-5e71b191d697------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7bd88c248ca</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agents-in-action]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[claude-skills]]></category>
            <dc:creator><![CDATA[Amey Kulkarni]]></dc:creator>
            <pubDate>Tue, 19 May 2026 08:27:14 GMT</pubDate>
            <atom:updated>2026-05-19T08:27:14.168Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Problem everyone is frustrated about With AI Coding Assistants</h3><p>I was building a backend system with the help of an AI assistant — the usual workflow. I’d describe a feature, the AI would propose an architecture, I’d click “implement,” and we’d move on. Fast, fluent, confident.</p><p>Except three weeks in, I noticed something unsettling: <strong>the AI had completely forgotten why we’d made our initial design decisions.</strong> The context window had aged out. The reasoning was gone. The new features it was generating were quietly conflicting with patterns we’d established at the start.</p><p>We weren’t building a coherent system anymore. We were accreting code.</p><p>That was problem number one.</p><p>Problem number two hit me when I stepped back and watched how the AI handled my proposals. Every time I suggested an approach, it would validate it. “Great idea.” “That approach makes sense.” “Let’s implement it.”</p><p>There was no friction. No pushback. No one saying: <em>“Wait — have you thought about what this costs at scale? Have you considered the IAM surface area here? What happens when this fails?”</em></p><p><strong>A senior engineer would have asked those questions. The AI just nodded and started typing.</strong></p><p>This is what I call the <strong>“Yes-Machine Problem.”</strong> Single-agent LLMs are, by their nature, agreeable. They don’t have competing internal priorities. They don’t have a FinOps engineer sitting across the table who will lose their mind if you spin up an NAT Gateway you didn’t need.</p><p>The result? Generic, happy-path implementations that look fine in isolation but fall apart under the weight of real production systems.</p><h3>The Insight: Adversarial Friction Is What Makes Good Engineering</h3><p>I started thinking about what separates good engineering teams from average ones. It’s not IQ. It’s not hours worked. It’s <strong>structured disagreement.</strong></p><p>In a good team:</p><ul><li>The architect proposes a design.</li><li>The security engineer immediately starts poking holes in it.</li><li>The platform engineer asks what this costs at 10x traffic.</li><li>The reliability engineer flags the single point of failure no one else noticed.</li><li>The engineering manager cuts through the noise and makes a pragmatic call.</li></ul><p>That adversarial dynamic is <em>why</em> good systems get built. The debate surfaces the failure modes before they become production incidents.</p><p>No single LLM agent replicates this. But <strong>a multi-agent system with specialized, competing personas can.</strong></p><p>That’s the core idea behind <strong>ThinkTank</strong>.</p><h3>What I Built: ThinkTank</h3><p>ThinkTank is a Claude skill — a structured, multi-agent orchestration workflow that refuses to let you implement anything until your idea has survived a committee of adversarial expert personas.</p><p>Here’s the committee:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0s5ZprKTinOXuHB9z9kzA.png" /></figure><p>Persona Role <strong>System Architect</strong> Proposes the initial design, pushing for elegant scalability <strong>Security Engineer</strong> Actively attacks the proposal — lateral movement vectors, IAM leaks, zero-trust violations <strong>FinOps Engineer</strong> Calculates the real cloud cost of the proposal and forces cheaper alternatives <strong>Reliability Engineer</strong> Flags single points of failure and DX anti-patterns <strong>Current State Expert</strong> Acts as a historian — enforces past architectural decisions and stops you from breaking what already works <strong>Engineering Manager</strong> Evaluates the debate, penalizes over-engineering, and makes the final call</p><p>Before a single line of code is written, your idea runs through all of them.</p><h3>The 5-Stage Engine</h3><p>ThinkTank is a strict state machine. It won’t generate code on the first prompt. Here’s what happens instead:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x8zufib9f2uoaBFoXS9Xag.png" /></figure><h3>Stage 1: Discovery &amp; Requirements</h3><p>The system asks 2–3 precise clarifying questions. What exactly are we building? What’s the primary optimization target — cost, availability, security, developer experience? You have to think before it thinks.</p><h3>Stage 2: Context Analysis</h3><p>ThinkTank silently scans the workspace. Greenfield project? It proceeds. Legacy/brownfield repo? It halts and asks you to document any existing architectural constraints before it designs anything new. This single step has saved me from introducing modern patterns that silently break legacy code.</p><h3>Stage 3: The Smart Debate</h3><p>This is the core. Your idea is routed to the expert committee.</p><ul><li><strong>Targeted Debate</strong>: If you specify a focus — [Focus: Security] or [Focus: Cost] — ThinkTank drops the irrelevant personas and runs a tight 3-node debate. Faster, cheaper, more focused.</li><li><strong>Full Debate</strong>: Otherwise, all five experts argue the trade-offs, with the Engineering Manager actively penalizing anyone pushing for over-engineering.</li></ul><h3>Stage 4: Final Decision &amp; Guardrails</h3><p>The Engineering Manager declares the outcome. You get a plain-English summary of what the architecture is optimized for, and a preview of the implementation guardrails. <strong>It explicitly asks for your approval before writing anything to disk.</strong></p><h3>Stage 5: Execution &amp; ADR Persistence</h3><p>On approval, ThinkTank does two things simultaneously:</p><ol><li>Silently writes a <strong>JSON Architecture Decision Record (ADR)</strong> into your .arch-decisions/ folder.</li><li>Hands off execution — either implementing the feature directly, or generating a step-by-step implementation plan with exact testing steps.</li></ol><h3>The Part That Changes Everything: Architecture Decision Records</h3><p>The ADR is the feature I’m most proud of, because it directly solves the forgetting problem.</p><p>When the debate concludes and you approve the architecture, ThinkTank generates a lightweight JSON file that records:</p><ul><li><strong>Context</strong>: Why was this decision made?</li><li><strong>Decision</strong>: What are we building, and how?</li><li><strong>Guardrails</strong>: The strict rules future agents must follow when touching this part of the codebase.</li></ul><p>Every future agent running in your repository silently ingests these ADRs. If it tries to generate code that violates a guardrail — say, adding a direct database call to a service that was architecturally decided to only use the event bus — it refuses and explains the conflict.</p><p>This is <strong>architectural persistence</strong>. The AI no longer forgets. The reasoning from week one is still alive in week ten.</p><h3>Token Optimization: The Engineering Behind the Magic</h3><p>One of the real challenges with multi-agent systems is cost. Running five expert personas through a full debate on every single feature request is wasteful.</p><p>ThinkTank solves this with <strong>targeted debates</strong>. When you specify a focus area, the system dynamically drops the personas that aren’t relevant and routes the task through a 3-node debate instead of a 5-node debate. Roughly 40% fewer tokens for focused tasks, with equivalent decision quality.</p><p>The ADR system also reduces token waste across sessions. Instead of re-analyzing the codebase from scratch every time, the next agent loads the ADR and already knows the architectural context. The “discovery” phase that normally eats hundreds of tokens is compressed to a single file read.</p><h3>What This Changes About How I Work</h3><p>The shift has been real. Before ThinkTank, I’d implement a feature and discover the problem three pull requests later. Now, the problems surface in the debate — before any code exists.</p><p>The Security Engineer has caught three IAM permission issues I would have shipped. The FinOps Engineer convinced me to swap an NAT Gateway for a VPC endpoint on one service, saving meaningful money at scale. The Reliability Engineer pushed back on a single-table DynamoDB design I was happy with, and the resulting multi-table design has been far easier to query in practice.</p><p>These aren’t hypothetical wins. They’re documented in the ADRs, with the debate context preserved.</p><p>Download the skill : <a href="https://drive.google.com/file/d/1FYr2z2Ba-mBZhKDlReMR20bztCU5AtDN/view?usp=sharing">https://drive.google.com/file/d/1FYr2z2Ba-mBZhKDlReMR20bztCU5AtDN/view?usp=sharing</a></p><h3>How to Use ThinkTank</h3><p>ThinkTank is a Claude Code skill. Installation is one command:</p><pre>claude skill add thinktank.skill</pre><p>To trigger the full architectural workflow:</p><pre>ThinkTank: I want to build a real-time notification system.</pre><p>To run a targeted, token-optimized debate:</p><pre>ThinkTank: I want to build a webhook handler [Focus: Security]</pre><p>The .arch-decisions/ folder is committed to your repo alongside your code. The reasoning lives with the system it describes.</p><h3>What’s Next</h3><p>A companion web platform is in development — a real-time visual interface for watching the multi-agent debate unfold and managing your ADR history across GitHub repositories.</p><p>But the core insight is already working: <strong>the best thing you can add to an AI coding workflow isn’t more intelligence. It’s structured disagreement.</strong></p><p>Build systems that argue. You’ll ship better code.</p><p><em>ThinkTank is an open Claude skill. If this resonates, I’d love to hear how your team handles architectural persistence in agentic workflows.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7bd88c248ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>