<?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 Aryan Chari on Medium]]></title>
        <description><![CDATA[Stories by Aryan Chari on Medium]]></description>
        <link>https://medium.com/@aryaney0704?source=rss-7be5e1a8d248------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Yy6smMlxDCXTk-D3</url>
            <title>Stories by Aryan Chari on Medium</title>
            <link>https://medium.com/@aryaney0704?source=rss-7be5e1a8d248------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 12:52:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aryaney0704/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[A Comprehensive Guide on Optimizing Serverless APIs with AWS SQS and SES]]></title>
            <link>https://medium.com/@aryaney0704/a-comprehensive-guide-on-optimizing-serverless-apis-with-aws-sqs-and-ses-8b620ce6cf78?source=rss-7be5e1a8d248------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b620ce6cf78</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-sqs]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Aryan Chari]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 19:00:39 GMT</pubDate>
            <atom:updated>2026-09-28T19:00:39.406Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_HMXKi_5-7ltE4s1UhryQQ.jpeg" /><figcaption>Architectural Diagram</figcaption></figure><p>When building a serverless API, some work does not need to happen before the API responds to the user.</p><p>Sending an email is a good example.</p><p>If an API handler creates an account and then waits for a confirmation email to be sent, the user has to wait for both operations to finish.</p><p>A better approach is to move the email-sending work into the background using <strong>Amazon SQS</strong> and <strong>Amazon SES</strong>.</p><p>The basic idea is:</p><pre>Client<br>  |<br>  | HTTP request<br>  v<br>API Lambda<br>  |<br>  | 1. Perform the main operation<br>  |<br>  | 2. Send email job to SQS<br>  v<br>SQS Queue<br>  |<br>  | AWS reads the message<br>  | and invokes the worker Lambda<br>  v<br>Email Worker Lambda<br>  |<br>  v<br>Amazon SES<br>  |<br>  v<br>Email</pre><p>This allows the API to respond without waiting for the email to actually be sent.</p><h3>1. The problem with sending email directly from the API</h3><p>Suppose we have a simple registration API:</p><pre>module.exports.handler = async (event) =&gt; {<br>    try {<br>        const user = await createUser(event);<br>        await sendWelcomeEmail(user);<br>        return {<br>            statusCode: 201,<br>            body: JSON.stringify({<br>                message: &quot;Account created successfully&quot;<br>            })<br>        };<br>    } catch (error) {<br>        return {<br>            statusCode: 500,<br>            body: JSON.stringify({<br>                message: error.message<br>            })<br>        };<br>    }<br>};</pre><p>The flow is:</p><pre>HTTP Request<br>     |<br>     v<br>Create User<br>     |<br>     v<br>Send Email<br>     |<br>     v<br>HTTP Response</pre><p>The API cannot respond until sendWelcomeEmail() finishes.</p><p>This creates a few problems:</p><ul><li>The API response takes longer.</li><li>The user has to wait for work that is not directly related to the API response.</li><li>A temporary email/SES failure can affect the API request.</li><li>Email-sending logic becomes tightly coupled to the HTTP request.</li><li>Traffic spikes can create many simultaneous email operations.</li></ul><p>The email is usually not something the user needs to wait for. The important operation is the main API operation; the email can happen shortly afterward.</p><h3>2. What is a queue?</h3><p>A queue is simply a place where messages or jobs wait to be processed.</p><p>Think about a line at a counter:</p><pre>Job 1<br>Job 2<br>Job 3<br>Job 4</pre><p>A worker takes jobs from the line and processes them.</p><p>With AWS SQS:</p><pre>Producer<br>   |<br>   v<br>SQS Queue<br>   |<br>   v<br>Consumer / Worker</pre><p>The application that puts a message into the queue is the <strong>producer</strong>.</p><p>The application that processes the message is the <strong>consumer</strong> or <strong>worker</strong>.</p><p>In this example:</p><pre>API Lambda       = Producer<br>SQS              = Queue<br>Worker Lambda    = Consumer<br>SES              = Email service</pre><h3>3. What is Amazon SQS?</h3><p><strong>Amazon Simple Queue Service (SQS)</strong> is a managed message queue provided by AWS.</p><p>Instead of one Lambda directly performing slow background work, we can put a message into SQS.</p><p>For example:</p><pre>{<br>    &quot;to&quot;: [&quot;user@example.com&quot;],<br>    &quot;templateCode&quot;: &quot;WELCOME_EMAIL&quot;,<br>    &quot;payload&quot;: {<br>        &quot;username&quot;: &quot;John&quot;<br>    }<br>}</pre><p>The message describes the work that needs to be done.</p><p>The API does not need to know how the email is actually sent. It only needs to say:</p><blockquote><em>“Here is an email job. Please process it.”</em></blockquote><h3>4. What is Amazon SES?</h3><p><strong>Amazon Simple Email Service (SES)</strong> is AWS’s email-sending service.</p><p>The worker Lambda can use SES to actually send the email.</p><p>SQS and SES have different responsibilities:</p><pre>SQS<br>|<br>| Holds the email job<br>| Handles delivery to the worker<br>| Provides retries<br>| Can move failed messages to a DLQ<br>|<br>v<br>Worker Lambda<br>|<br>| Performs the email job<br>|<br>v<br>SES<br>|<br>| Actually sends the email<br>|<br>v<br>Recipient</pre><p>SQS does <strong>not</strong> send the email.</p><p>SES does <strong>not</strong> act as the queue.</p><p>The worker connects the two.</p><h3>5. The optimized API flow</h3><p>Instead of sending the email directly:</p><pre>await sendWelcomeEmail(user);</pre><p>we send an email job to SQS:</p><pre>await sqsClient.send(<br>    new SendMessageCommand({<br>        QueueUrl: process.env.EMAIL_QUEUE_URL,<br>        MessageBody: JSON.stringify({<br>            to: [user.email],<br>            templateCode: &quot;WELCOME_EMAIL&quot;,<br>            payload: {<br>                username: user.username<br>            }<br>        })<br>    })<br>);</pre><p>The API flow now becomes:</p><pre>HTTP Request<br>     |<br>     v<br>API Lambda<br>     |<br>     +----&gt; Perform main operation<br>     |<br>     +----&gt; Send email job to SQS<br>     |<br>     v<br>HTTP Response</pre><p>The email itself happens separately:</p><pre>SQS Queue<br>     |<br>     v<br>Worker Lambda<br>     |<br>     v<br>    SES<br>     |<br>     v<br>   Email</pre><p>The API does not wait for the entire email process.</p><h3>6. Sending a message to SQS</h3><p>Using the AWS SDK:</p><pre>const {<br>    SQSClient,<br>    SendMessageCommand<br>} = require(&quot;@aws-sdk/client-sqs&quot;);<br><br>const sqsClient = new SQSClient({<br>    region: process.env.AWS_REGION<br>});</pre><p>Then:</p><pre>const message = {<br>    to: [&quot;user@example.com&quot;],<br>    templateCode: &quot;WELCOME_EMAIL&quot;,<br>    payload: {<br>        username: &quot;John&quot;<br>    }<br>};<br><br>await sqsClient.send(<br>    new SendMessageCommand({<br>        QueueUrl: process.env.EMAIL_QUEUE_URL,<br>        MessageBody: JSON.stringify(message)<br>    })<br>);</pre><p>The important property here is:</p><pre>QueueUrl: process.env.EMAIL_QUEUE_URL</pre><p>The Queue URL tells SQS:</p><blockquote><em>“Put this message into this particular queue.”</em></blockquote><h3>7. Where does the Queue URL come from?</h3><p>Instead of hardcoding the URL, Serverless/CloudFormation can provide it as an environment variable.</p><p>For example:</p><pre>provider:<br>  environment:<br>    EMAIL_QUEUE_URL:<br>      Ref: EmailQueue</pre><p>And the queue can be defined as:</p><pre>resources:<br>  Resources:<br>    EmailQueue:<br>      Type: AWS::SQS::Queue<br>      Properties:<br>        QueueName: &#39;${self:service}-${sls:stage}-email-queue&#39;</pre><p>For an AWS::SQS::Queue, CloudFormation&#39;s Ref gives the queue URL.</p><p>So:</p><pre>EmailQueue<br>    |<br>    | Ref<br>    v<br>Queue URL<br>    |<br>    v<br>EMAIL_QUEUE_URL<br>    |<br>    v<br>process.env.EMAIL_QUEUE_URL</pre><p>The application therefore does not need to know the actual AWS-generated URL.</p><h3>8. How does SQS know which Lambda to trigger?</h3><p>This is where the <strong>SQS event source mapping</strong> comes in.</p><p>With Serverless Framework, we can configure:</p><pre>emailWorker:<br>  handler: handlers/queues/email-worker.handler  <br>  events:<br>    - sqs:<br>        arn:<br>          Fn::GetAtt:<br>            - EmailQueue<br>            - Arn</pre><p>This tells Serverless/AWS:</p><blockquote><em>“This Lambda is a worker for this SQS queue.”</em></blockquote><p>The queue has an ARN, and the Lambda also has an ARN. AWS uses the event-source configuration to create the relationship between the queue and the Lambda.</p><p>Conceptually:</p><pre>EmailQueue<br>    |<br>    | Queue ARN<br>    v<br>Event Source Mapping<br>    |<br>    | knows which Lambda to invoke<br>    v<br>emailWorker Lambda</pre><p>The ARN itself does not directly call the Lambda. The important concept is the <strong>event source mapping</strong> created from this configuration.</p><h3>9. What happens when a message arrives?</h3><p>Suppose our API sends this message:</p><pre>{<br>    &quot;to&quot;: [&quot;user@example.com&quot;],<br>    &quot;templateCode&quot;: &quot;WELCOME_EMAIL&quot;,<br>    &quot;payload&quot;: {<br>        &quot;username&quot;: &quot;John&quot;<br>    }<br>}</pre><p>The message is now sitting in SQS.</p><p>AWS’s SQS-to-Lambda integration reads messages from the queue and invokes the configured worker Lambda.</p><p>The worker receives an event containing records:</p><pre>module.exports.handler = async (event) =&gt; {  <br>  for (const record of event.Records) {<br>        const message = JSON.parse(record.body);<br>        console.log(message);<br>        // Process the email job<br>    }<br>};</pre><p>A single Lambda invocation can contain multiple SQS messages. That is why we usually iterate over event.Records.</p><h3>10. The worker Lambda</h3><p>The worker can now handle the actual email operation:</p><pre>const EmailRepository = require(&quot;../../repositories/email-repository&quot;);<br>module.exports.handler = async (event) =&gt; {<br>    try {<br>        for (const record of event.Records) {<br>            const {<br>                templateCode,<br>                payload,<br>                to,<br>                cc<br>            } = JSON.parse(record.body);<br>            await EmailRepository.publishEmail({<br>                to,<br>                cc,<br>                templateCode,<br>                payload<br>            });<br>        }<br>    } catch (error) {<br>        console.error(<br>            &quot;Error while processing email queue:&quot;,<br>            error.message<br>        );<br>        throw error;<br>    }<br>};</pre><p>The important part is:</p><pre>throw error;</pre><p>If the email operation fails, the Lambda invocation needs to fail. This allows the message to be processed again instead of treating it as successfully processed.</p><h3>11. The worker sends the email through SES</h3><p>The worker can eventually call SES:</p><pre>const {<br>    SESv2Client,<br>    SendEmailCommand<br>} = require(&quot;@aws-sdk/client-sesv2&quot;);<br><br>const sesClient = new SESv2Client({<br>    region: process.env.AWS_REGION<br>});</pre><p>Then:</p><pre>await sesClient.send(<br>    new SendEmailCommand({<br>        FromEmailAddress: process.env.FROM_EMAIL,<br>        Destination: {<br>            ToAddresses: to<br>        },<br>        Content: {<br>            Simple: {<br>                Subject: {<br>                    Data: subject<br>                },<br>                Body: {<br>                    Html: {<br>                        Data: body<br>                    }<br>                }<br>            }<br>        }<br>    })<br>);</pre><p>So the complete background process is:</p><pre>SQS Message<br>     |<br>     v<br>Worker Lambda<br>     |<br>     v<br>Build/render email<br>     |<br>     v<br>    SES<br>     |<br>     v<br>Recipient</pre><h3>12. What happens when the worker fails?</h3><p>One of the biggest benefits of using SQS is that a failed message can be processed again.</p><p>For example:</p><pre>Message<br>   |<br>   v<br>Worker<br>   |<br>   X<br>Failure<br>   |<br>   v<br>Retry</pre><p>We can also configure a <strong>Dead Letter Queue (DLQ)</strong>.</p><p>For example:</p><pre>Resources:<br>  EmailDLQ:<br>    Type: AWS::SQS::Queue<br>    Properties:<br>      QueueName: &#39;${self:service}-${sls:stage}-email-dlq&#39;<br>  EmailQueue:<br>    Type: AWS::SQS::Queue<br>    Properties:<br>      QueueName: &#39;${self:service}-${sls:stage}-email-queue&#39;<br>      RedrivePolicy:<br>        deadLetterTargetArn:<br>          Fn::GetAtt:<br>            - EmailDLQ<br>            - Arn<br>        maxReceiveCount: 3</pre><p>Now, if a message repeatedly fails, it can eventually be moved to the DLQ.</p><p>Conceptually:</p><pre>EmailQueue<br>    |<br>    | Attempt 1 -&gt; failure<br>    |<br>    | Attempt 2 -&gt; failure<br>    |<br>    | Attempt 3 -&gt; failure<br>    |<br>    v<br>EmailDLQ</pre><p>The DLQ prevents a permanently failing message from being retried indefinitely and gives you a place to inspect or redrive failed jobs.</p><h3>13. Queue URL vs Queue ARN</h3><p>Both identify the same queue, but they are used for different purposes.</p><h3>Queue URL</h3><p>Used when interacting with the queue through SQS APIs.</p><p>For example:</p><pre>new SendMessageCommand({<br>    QueueUrl: process.env.EMAIL_QUEUE_URL,<br>    MessageBody: JSON.stringify(message)<br>});</pre><p>Think:</p><blockquote><em>“Where is the queue I want to send this message to?”</em></blockquote><h3>Queue ARN</h3><p>Used to identify the AWS queue resource when configuring AWS relationships.</p><p>For example:</p><pre>events:<br>  - sqs:<br>      arn:<br>        Fn::GetAtt:<br>          - EmailQueue<br>          - Arn</pre><p>Think:</p><blockquote><em>“Which AWS resource is this?”</em></blockquote><p>A useful mental model is:</p><pre>Queue URL<br>    |<br>    +--&gt; Used to interact with the queue<br>Queue ARN<br>    |<br>    +--&gt; Used to identify the AWS queue resource<br>         and configure the SQS -&gt; Lambda relationship</pre><h3>14. The complete architecture</h3><p>Putting everything together:</p><p><strong>Refer to the architecture diagram</strong>. Notice that the API Lambda and email worker are now separated.</p><p>The API’s responsibility is:</p><pre>Receive request<br>     |<br>     v<br>Perform main operation<br>     |<br>     v<br>Create email job<br>     |<br>     v<br>Put job in SQS<br>     |<br>     v<br>Return response</pre><p>The worker’s responsibility is:</p><pre>Receive email job<br>     |<br>     v<br>Process job<br>     |<br>     v<br>Render email<br>     |<br>     v<br>Send through SES</pre><p>This is called <strong>decoupling</strong>.</p><h3>15. Why is this better than sending the email inside the HTTP Lambda?</h3><h3>1. Faster API responses</h3><p>Without SQS:</p><pre>API<br> |<br> +-- Database operation<br> |<br> +-- Email operation<br> |<br> +-- Response</pre><p>With SQS:</p><pre>API<br> |<br> +-- Database operation<br> |<br> +-- Put job in SQS<br> |<br> +-- Response</pre><p>The API no longer waits for the entire email-sending process. The user gets the response sooner.</p><h3>2. Email failures are separated from the main API operation</h3><p>Imagine the main operation succeeds but SES temporarily has a problem.</p><p>Without a queue, the API is directly dependent on the email operation.</p><p>With SQS:</p><pre>API<br> |<br> +-- Main operation succeeds<br> |<br> +-- Email job stored in SQS<br> |<br> +-- API responds</pre><p>The worker can retry the email independently.</p><h3>3. Built-in retry behavior</h3><p>SQS can keep a message available for another processing attempt when the worker fails.</p><p>You can also configure a DLQ:</p><pre>Failed message<br>      |<br>      v<br>    Retry<br>      |<br>      v<br>    Retry<br>      |<br>      v<br>    Retry<br>      |<br>      v<br>     DLQ</pre><p>This provides a more resilient background-processing flow.</p><h3>4. Better separation of responsibilities</h3><p>Your HTTP Lambda does not need to contain all of the email logic.</p><p>Instead:</p><pre>API Lambda<br>    |<br>    | &quot;Send this email&quot;<br>    v<br>SQS<br>    |<br>    v<br>Email Worker<br>    |<br>    v<br>SES</pre><p>The API knows about the <strong>job</strong>, while the worker knows about the <strong>implementation</strong>.</p><p>This makes the system easier to maintain and extend.</p><h3>5. Better handling of traffic spikes</h3><p>Suppose your application suddenly needs to send a large number of emails.</p><p>Without a queue, the API layer could end up trying to perform many email operations at the same time.</p><p>With SQS:</p><pre>+-- Job<br>                 +-- Job<br>API ------------&gt;+-- Job<br>                 +-- Job<br>                 +-- Job<br>                       |<br>                       v<br>                    Worker<br>                       |<br>                       v<br>                      SES</pre><p>The queue acts as a buffer between the API and the background work.</p><p>Workers can process jobs as they become available.</p><h3>16. Where else can this pattern be used?</h3><p>The SQS + worker pattern is useful whenever some work can happen asynchronously.</p><h3>Notifications</h3><pre>API -&gt; SQS -&gt; Notification Worker -&gt; Push/SMS/Email</pre><h3>Image processing</h3><pre>API -&gt; SQS -&gt; Image Worker -&gt; Resize/Compress -&gt; S3</pre><h3>Report generation</h3><pre>API -&gt; SQS -&gt; Report Worker -&gt; Generate PDF -&gt; S3</pre><h3>Data processing</h3><pre>API -&gt; SQS -&gt; Worker -&gt; Process records -&gt; Database</pre><h3>Analytics</h3><pre>API -&gt; SQS -&gt; Analytics Worker -&gt; Store/process analytics</pre><p>The general pattern is:</p><pre>Synchronous request<br>       |<br>       v<br>Do the important work<br>       |<br>       v<br>Put background job in SQS<br>       |<br>       v<br>Return response<br>       |<br>       |<br>       |       Background<br>       |          |<br>       |          v<br>       |       SQS Queue<br>       |          |<br>       |          v<br>       |       Worker<br>       |          |<br>       |          v<br>       |      Actual work<br>       |<br>       v<br>     Client</pre><h3>Conclusion</h3><p>SQS is not an email service.</p><p>SES is not a queue.</p><p>They solve different problems.</p><p>A useful way to remember the architecture is:</p><pre>SQS    = &quot;Do this work later.&quot;<br>Worker = &quot;I&#39;ll do the work.&quot;<br>SES    = &quot;I&#39;ll send the email.&quot;</pre><p>For a serverless API, this separation allows the HTTP request to focus on the work that must happen immediately while slower background tasks can be processed independently.</p><p>The key flow is:</p><pre>API Lambda<br>    |<br>    v<br>Send message to SQS using Queue URL<br>    |<br>    v<br>SQS stores the job<br>    |<br>    v<br>AWS SQS/Lambda event source mapping<br>    |<br>    v<br>Worker Lambda is invoked<br>    |<br>    v<br>Worker processes the message<br>    |<br>    v<br>SES sends the email</pre><p>Once this mental model is clear, SQS becomes much less mysterious. It is essentially a reliable middle layer that allows your application to say:</p><blockquote><strong><em>“I have some work that needs to be done. Store it, and let a worker handle it.”</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b620ce6cf78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How ‘Sign in with Google’ Actually Works: A Deep Dive into Cognito + OAuth2]]></title>
            <link>https://medium.com/@aryaney0704/how-sign-in-with-google-actually-works-a-deep-dive-into-cognito-oauth2-cd544e01bcce?source=rss-7be5e1a8d248------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd544e01bcce</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cognito]]></category>
            <category><![CDATA[google-auth]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Aryan Chari]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 15:10:59 GMT</pubDate>
            <atom:updated>2026-08-14T15:10:59.417Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B3fjZfHy7zshXmXJapR7Jg.png" /></figure><p>Today I dug into how Google Sign-In works when it’s wired up through AWS Cognito. You’ve probably seen that “Sign in with Google” button on countless apps and wondered what’s actually happening behind the scenes. Here’s how it works.</p><p>Here’s a breakdown of the flow, step by step, along with example URLs and payloads.</p><h3>Why OAuth2 in the first place?</h3><p>Before OAuth2, if you wanted to let users sign in with their Google account, you’d basically need Google to hand you their username and password so you could verify it, which is a terrible idea for obvious security reasons. Nobody wants to give a third-party app their Google credentials.</p><p>OAuth2 solves this by introducing a <strong>delegation model</strong>: instead of sharing credentials, the user grants your app a <em>token</em> that proves “yes, I am who I say I am, and I’ve allowed this app to know that.” The actual authentication (checking password, 2FA, etc.) happens entirely on Google’s turf. Your app never sees a password, it only ever sees short-lived tokens that Google (or in this case, Cognito acting as a middleman) issues after the user consents.</p><p>This makes auth simpler in a few ways:</p><ul><li>You don’t have to build or store passwords for your users.</li><li>You inherit Google’s security (2FA, device checks, breach detection) for free.</li><li>The “identity provider” (Google) and “resource” (your app) are cleanly separated, so tokens can be scoped, expired, and revoked independently.</li></ul><p>Cognito sits in the middle of this as an <strong>identity broker, </strong>it talks to Google on your behalf, and then issues <em>its own</em> tokens to your app, so your app only ever has to integrate with one system (Cognito) instead of every identity provider individually.</p><h3>The Flow, Step by Step</h3><h3>Step 1: App redirects to Cognito’s authorize endpoint</h3><p>Your app kicks things off by sending the user’s browser to Cognito’s /oauth2/authorize endpoint.</p><pre>https://my-app-prod.auth.us-east-1.amazoncognito.com/oauth2/authorize?<br>  client_id=1a2b3c4d5e6f7g8h9i0j&amp;<br>  response_type=code&amp;<br>  scope=openid+email+profile&amp;<br>  redirect_uri=https://api.my-app.com/auth/callback&amp;<br>  identity_provider=Google</pre><p>Here, redirect_uri is the endpoint (in my case, a Lambda function) that Cognito will eventually send the user back to, but not yet. This value gets remembered by Cognito for later validation.</p><h3>Step 2: Cognito forwards the request to Google</h3><p>Cognito recognizes identity_provider=Google and redirects the browser again, this time to Google&#39;s own OAuth endpoint, constructing the required parameters itself (using the Google client ID/secret Cognito has registered with Google).</p><pre>https://accounts.google.com/o/oauth2/v2/auth?<br>  client_id=your-google-client-id.apps.googleusercontent.com&amp;<br>  response_type=code&amp;<br>  scope=openid+email+profile&amp;<br>  redirect_uri=https://my-app-prod.auth.us-east-1.amazoncognito.com/oauth2/idpresponse&amp;<br>  state=abc123xyz</pre><p>Notice the redirect_uri here points back to <strong>Cognito</strong>, not your app. Google doesn&#39;t know your app exists, it only knows Cognito.</p><h3>Step 3: User authenticates and consents on Google</h3><p>The user sees the familiar Google sign-in screen, logs in, and approves the requested scopes (email, profile, etc.).</p><h3>Step 4: Google redirects back to Cognito with a code</h3><p>Once the user consents, Google redirects the browser to Cognito’s /oauth2/idpresponse endpoint with an authorization code:</p><pre>https://my-app-prod.auth.us-east-1.amazoncognito.com/oauth2/idpresponse?<br>  code=4/0AX4XfWh...GoogleCode&amp;<br>  state=abc123xyz</pre><h3>Step 5: Cognito exchanges the Google code, then issues its own</h3><p>This is the part that’s easy to misunderstand. Cognito doesn’t just relay Google’s code onward, it does its own separate exchange:</p><ol><li>Cognito takes the Google code and calls Google’s token endpoint <strong>server-to-server</strong>, using its own registered Google client ID/secret, to get Google’s id_token/access_token.</li><li>Cognito uses the Google id_token to create (or link) a user in your Cognito User Pool.</li><li>Cognito then generates a <strong>brand-new authorization code of its own</strong> and redirects the browser to the original redirect_uri from Step 1 (it knows which one because it tracked that against the session/state it created back then).</li></ol><pre>https://api.my-app.com/auth/callback?<br>  code=cognitoAuthCode789&amp;<br>  state=abc123xyz</pre><p>So there are actually <strong>two separate codes</strong> involved, Google’s code (‘X’ in image reference) and Cognito’s code (‘Y’ in image reference), for two separate token exchanges.</p><h3>Step 6: Your Lambda exchanges Cognito’s code for tokens</h3><p>Your redirect_uri (a Lambda function, in my case) receives this Cognito code and makes a server-to-server POST request to Cognito&#39;s token endpoint:</p><pre>POST https://my-app-prod.auth.us-east-1.amazoncognito.com/oauth2/token<br>Content-Type: application/x-www-form-urlencoded<br><br>//request body<br>grant_type=authorization_code&amp;<br>client_id=1a2b3c4d5e6f7g8h9i0j&amp;<br>code=cognitoAuthCode789&amp;<br>redirect_uri=https://api.my-app.com/auth/callback</pre><p>A subtlety I initially got confused about: this redirect_uri isn&#39;t being used to redirect anywhere, this call is a plain POST. It&#39;s included purely as a <strong>security check</strong>: Cognito compares it against the redirect_uri used back in Step 1. If they don&#39;t match, the exchange is rejected. This stops a stolen code from being redeemed via a different endpoint than the one that started the flow.</p><p>Cognito responds with tokens:</p><pre>{<br>  &quot;id_token&quot;: &quot;eyJraWQiOiJ...&quot;,<br>  &quot;access_token&quot;: &quot;eyJraWQiOiJ...&quot;,<br>  &quot;refresh_token&quot;: &quot;eyJjdHkiOiJ...&quot;,<br>  &quot;expires_in&quot;: 3600,<br>  &quot;token_type&quot;: &quot;Bearer&quot;<br>}</pre><h3>Step 7 (optional): Fetch user details</h3><p>The id_token is a JWT that already carries basic claims; email, sub, name, etc; decoded straight from the token itself, no extra call needed. If your app wants app-specific data (profile settings, permissions, order history, whatever lives in your own database), you&#39;d look that up here using the sub (user ID) as the key.</p><p><strong>This step is optional, </strong>if all you need is to prove who the user is, you can skip a database round-trip entirely and just pass the tokens straight through.</p><h3>Step 8: Pass tokens (and optionally user details) to the frontend</h3><p>Finally, the Lambda returns the tokens, and the user details, if fetched, to the frontend, which stores them (however it manages sessions) and treats the user as logged in.</p><h3>Conclusion</h3><p>The biggest thing I learned is that this isn’t a single OAuth handshake; it’s <strong>two chained OAuth flows</strong> stitched together: Google↔Cognito, and Cognito↔your app. Cognito acts as a broker that abstracts away Google’s implementation details, so your app only ever needs to understand <em>one</em> OAuth integration (Cognito’s), no matter how many identity providers you plug in behind it. The redirect_uri also does double duty, first as a literal redirect target, and later as a security check during token exchange, which was the part that tripped me up the most until I understood <em>why</em> it&#39;s sent twice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd544e01bcce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning Discriminators in Mongoose]]></title>
            <link>https://medium.com/@aryaney0704/learning-discriminators-in-mongoose-3135f8e8c5b2?source=rss-7be5e1a8d248------2</link>
            <guid isPermaLink="false">https://medium.com/p/3135f8e8c5b2</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[mongoose]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aryan Chari]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 18:51:50 GMT</pubDate>
            <atom:updated>2026-07-21T02:19:02.467Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BFaNyGPocmY4giS94yOQ_Q.png" /></figure><h3>Why We Need Them</h3><p>There are cases where you want to store documents with varying data structures/schemas in a single collection, but they all share the same root document schema. That’s exactly when you use <strong>discriminators</strong> in Mongoose, they let you write sub-schemas under a parent/root schema.</p><p>This avoids the hassle of cramming every possible field into one giant UserSchema, which quickly becomes hard to read and maintain. Instead, each variant gets its own clean, focused schema, while still living in the same collection as the root schema.</p><h3>The Problem: One Schema, Trying to Be Everything</h3><p>Say you need one User collection to support both employees and managers. Without discriminators, you&#39;d typically end up cramming every field from every variant into a single schema, marking most of them optional:</p><pre>const UserSchema = new mongoose.Schema({<br>    email: {<br>        type: String,<br>        required: true,<br>        unique: true<br>    },<br>    name: {<br>        type: String,<br>        required: true<br>    },<br>    accountType: {<br>        type: String,<br>        enum: [&#39;EMPLOYEE&#39;, &#39;MANAGER&#39;],<br>        required: true<br>    }<br><br>// Only relevant if accountType === &#39;EMPLOYEE&#39;<br>    employeeId: {<br>        type: String,<br>        unique: true,<br>        sparse: true<br>    },<br>    reportingManager: {<br>        type: mongoose.Types.ObjectId,<br>        ref: &quot;User&quot;<br>    },<br>// Only relevant if accountType === &#39;MANAGER&#39;<br>    managerId: {<br>        type: String,<br>        unique: true,<br>        sparse: true<br>    },<br>    reportingEmployees: [<br>        {<br>            type: mongoose.Types.ObjectId,<br>            ref: &quot;User&quot;<br>        }<br>    ]<br>});<br>const User = mongoose.model(&#39;User&#39;, UserSchema);</pre><p>A few problems with this:</p><ul><li><strong>No real validation boundary.</strong> Nothing stops you from creating a document with accountType: &#39;EMPLOYEE&#39; that also has managerId and reportingEmployees filled in. You&#39;d have to hand-write custom validators to enforce &quot;these fields only make sense together.&quot;</li><li><strong>Readability suffers as variants grow.</strong> Add a third or fourth account type, and this schema balloons into a long list of loosely-related optional fields, with comments doing the work that separate schemas would do automatically.</li><li><strong>unique doesn&#39;t play well with optional fields.</strong> Fields like employeeId need sparse: true so the unique index doesn&#39;t choke on the many documents where it&#39;s undefined.</li><li><strong>No dedicated model per type.</strong> You lose the convenience of calling Employee.find() or Manager.create() directly, every query has to manually filter on accountType yourself.</li></ul><p>Here’s the same thing built with discriminators instead, the shared fields stay in one root schema, and each variant’s fields live in their own, isolated schema:</p><h3>The Example (Default discriminatorKey)</h3><p>Here’s the same setup, built with discriminators. If you don’t pass a discriminatorKey option at all, Mongoose falls back to its own default field for tagging documents: <strong>__t</strong>.</p><pre>const UserSchema = new mongoose.Schema({<br>    email: {<br>        type: String,<br>        required: true,<br>        unique: true<br>    },<br>    name: {<br>        type: String,<br>        required: true<br>    }<br>});<br><br>const EmployeeSchema = UserSchema.discriminator(&#39;EMPLOYEE&#39;, new mongoose.Schema({<br>    employeeId: {<br>        type: String,<br>        required: true,<br>        unique: true<br>    },<br>    reportingManager: {<br>        type: mongoose.Types.ObjectId,<br>        ref: &quot;User&quot;<br>    }<br>}));<br><br>const ManagerSchema = UserSchema.discriminator(&#39;MANAGER&#39;, new mongoose.Schema({<br>    managerId: {<br>        type: String,<br>        required: true,<br>        unique: true<br>    },<br>    reportingEmployees: [<br>        {<br>            type: mongoose.Types.ObjectId,<br>            ref: &quot;User&quot;<br>        }<br>    ]<br>}));<br><br>const User = mongoose.model(&#39;User&#39;, UserSchema);<br>const Employee = User.discriminators[&#39;EMPLOYEE&#39;];<br>const Manager = User.discriminators[&#39;MANAGER&#39;];<br>module.exports = { User, Employee, Manager };</pre><p>Here, User is the root schema, while Employee and Manager are discriminators built on top of it. No discriminatorKey option was passed, so Mongoose tags each document under __t automatically.</p><h3>What the Documents Look Like (Default __t Key)</h3><h3>A plain User document</h3><pre>await User.create({<br>    email: &quot;johndoe@example.com&quot;,<br>    name: &quot;John Doe&quot;<br>});</pre><pre>{<br>    &quot;_id&quot;: &quot;64f1a2b3c4d5e6f7a8b9c0d1&quot;,<br>    &quot;email&quot;: &quot;johndoe@example.com&quot;,<br>    &quot;name&quot;: &quot;John Doe&quot;,<br>    &quot;__v&quot;: 0<br>}</pre><p>No __t field is present, this is just a base document, nothing extra attached.</p><h3>An Employee document</h3><pre>await Employee.create({<br>    email: &quot;janedoe@example.com&quot;,<br>    name: &quot;Jane Doe&quot;,<br>    employeeId: &quot;EMP-042&quot;,<br>    reportingManager: &quot;64f1a2b3c4d5e6f7a8b9c0d3&quot;<br>});</pre><pre>{<br>    &quot;_id&quot;: &quot;64f1a2b3c4d5e6f7a8b9c0d2&quot;,<br>    &quot;__t&quot;: &quot;EMPLOYEE&quot;,<br>    &quot;email&quot;: &quot;janedoe@example.com&quot;,<br>    &quot;name&quot;: &quot;Jane Doe&quot;,<br>    &quot;employeeId&quot;: &quot;EMP-042&quot;,<br>    &quot;reportingManager&quot;: &quot;64f1a2b3c4d5e6f7a8b9c0d3&quot;,<br>    &quot;__v&quot;: 0<br>}</pre><p>Notice the __t: &quot;EMPLOYEE&quot; field, this is the default discriminator key that tags the document. Along with the base email and name fields, it also carries employeeId and reportingManager, which only exist on the Employee schema.</p><h3>A Manager document</h3><pre>await Manager.create({<br>    email: &quot;jackdoe@example.com&quot;,<br>    name: &quot;Jack Doe&quot;,<br>    managerId: &quot;MGR-007&quot;,<br>    reportingEmployees: [&quot;64f1a2b3c4d5e6f7a8b9c0d2&quot;]<br>});</pre><pre>{<br>    &quot;_id&quot;: &quot;64f1a2b3c4d5e6f7a8b9c0d3&quot;,<br>    &quot;__t&quot;: &quot;MANAGER&quot;,<br>    &quot;email&quot;: &quot;jackdoe@example.com&quot;,<br>    &quot;name&quot;: &quot;Jack Doe&quot;,<br>    &quot;managerId&quot;: &quot;MGR-007&quot;,<br>    &quot;reportingEmployees&quot;: [&quot;64f1a2b3c4d5e6f7a8b9c0d2&quot;],<br>    &quot;__v&quot;: 0<br>}</pre><p>Same base fields, but this time tagged __t: &quot;MANAGER&quot;, and carrying managerId and reportingEmployees instead.</p><h3>Passing a Custom discriminatorKey</h3><p>__t works fine, but it&#39;s not the most readable field name to see sitting in your documents. Mongoose lets you override it by passing a discriminatorKey option to the root schema:</p><pre>const UserSchema = new mongoose.Schema({<br>    email: {<br>        type: String,<br>        required: true,<br>        unique: true<br>    },<br>    name: {<br>        type: String,<br>        required: true<br>    }<br>}, {<br>    discriminatorKey: &#39;accountType&#39;<br>});</pre><p>Everything else about EmployeeSchema, ManagerSchema, and the model setup stays exactly the same as before. The only difference is the field name used for tagging. The resulting documents now look like this:</p><pre>{<br>    &quot;_id&quot;: &quot;64f1a2b3c4d5e6f7a8b9c0d2&quot;,<br>    &quot;accountType&quot;: &quot;EMPLOYEE&quot;,<br>    &quot;email&quot;: &quot;janedoe@example.com&quot;,<br>    &quot;name&quot;: &quot;Jane Doe&quot;,<br>    &quot;employeeId&quot;: &quot;EMP-042&quot;,<br>    &quot;reportingManager&quot;: &quot;64f1a2b3c4d5e6f7a8b9c0d3&quot;,<br>    &quot;__v&quot;: 0<br>}</pre><pre>{<br>    &quot;_id&quot;: &quot;64f1a2b3c4d5e6f7a8b9c0d3&quot;,<br>    &quot;accountType&quot;: &quot;MANAGER&quot;,<br>    &quot;email&quot;: &quot;jackdoe@example.com&quot;,<br>    &quot;name&quot;: &quot;Jack Doe&quot;,<br>    &quot;managerId&quot;: &quot;MGR-007&quot;,<br>    &quot;reportingEmployees&quot;: [&quot;64f1a2b3c4d5e6f7a8b9c0d2&quot;],<br>    &quot;__v&quot;: 0<br>}</pre><p>Same idea as __t, just a friendlier, self-documenting field name doing the tagging.</p><h3>One Collection, Varying Structures</h3><p>All three documents above, the plain User, the Employee, and the Manager , are stored in the <strong>same MongoDB collection</strong> (users). If you ran db.users.find() directly in the Mongo shell, you&#39;d see all of them side by side, each with a different shape depending on whether (and how) they&#39;re tagged.</p><p>This is the core benefit: one collection, one set of shared fields, but each discriminator can carry its own extra fields without polluting the others.</p><h3>Querying Across Root and Discriminators</h3><p>Since Employee and Manager are both built on top of User, all three point to the same underlying collection when querying:</p><pre>await User.find();<br>// Returns ALL documents in the users collection: plain Users,<br>// Employees, and Managers alike, mixed together.<br><br>await Employee.find();<br>// Returns ONLY documents where accountType === &#39;EMPLOYEE&#39;<br>// Mongoose automatically adds this filter behind the scenes,<br>// and gives back documents with Employee-specific fields intact.<br><br>await Manager.find();<br>// Returns ONLY documents where accountType === &#39;MANAGER&#39;<br>// Same idea - filtered and shaped according to the Manager schema.</pre><p>Each model (User, Employee, Manager) talks to the exact same users collection under the hood, the only difference is how much filtering and shaping Mongoose applies before handing you the result.</p><h3>What Mongoose Is Actually Doing Under the Hood</h3><p>Discriminators aren’t a special MongoDB feature, MongoDB has no idea what a “discriminator” is. It’s purely a Mongoose-level trick, and it comes down to two things:</p><ol><li><strong>Schema merging.</strong> When you call UserSchema.discriminator(&#39;EMPLOYEE&#39;, EmployeeSchema), Mongoose takes the fields from EmployeeSchema and merges them on top of a clone of UserSchema. The resulting model&#39;s schema is effectively { ...UserSchema.fields, ...EmployeeSchema.fields }, plus the discriminator key field, added automatically as an enum-constrained string (its allowed values are the discriminator names you&#39;ve registered, e.g. EMPLOYEE, MANAGER).</li><li><strong>Query filter injection.</strong> Every discriminator model shares the exact same underlying collection as the root model (they literally point at the same db.collection). When you call Employee.find() or Employee.create(), Mongoose silently adds { accountType: &#39;EMPLOYEE&#39; } (or { __t: &#39;EMPLOYEE&#39; }) to your filter/insert behind the scenes. That&#39;s the entire mechanism, there&#39;s no separate storage, no join, no magic at the database layer. It&#39;s just an automatically-applied WHERE clause plus a merged schema.</li></ol><p>This is also why the discriminator key ends up saved on every document: it’s not metadata Mongoose tracks separately, it’s a real field in the collection that the discriminator models use to filter themselves back out later.</p><h3>Conclusion</h3><p>Discriminators are worth reaching for whenever you have multiple entity types that share a common core but diverge in a few specific fields, like different account types, different content types in a CMS, or different notification types. Instead of one bloated schema riddled with optional fields, or multiple disconnected collections duplicating the shared fields, discriminators let you:</p><ul><li>Keep shared fields defined once, in one place</li><li>Add type-specific fields only where they’re relevant</li><li>Query either the full set or a specific subtype, with Mongoose handling the filtering automatically</li></ul><p>The result is schema code that’s easier to read, easier to extend, and a database structure that stays consistent without giving up flexibility.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3135f8e8c5b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Implemented Debounce for a Voting Mechanism]]></title>
            <link>https://medium.com/@aryaney0704/how-i-implemented-debounce-for-a-voting-mechanism-e7df000f6f38?source=rss-7be5e1a8d248------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7df000f6f38</guid>
            <category><![CDATA[debouncing-in-react]]></category>
            <category><![CDATA[frontend-engineering]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Aryan Chari]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 15:44:03 GMT</pubDate>
            <atom:updated>2026-07-07T15:44:03.401Z</atom:updated>
            <content:encoded><![CDATA[<h3>The problem</h3><p>Users can upvote or downvote an item in a list. Two requirements pull in different directions:</p><ul><li>The UI must feel instant, no waiting on a network round trip before the button visually responds.</li><li>The backend should not be hit on every single click. If a user rapidly toggles a vote back and forth, we don’t want a flood of requests, and we don’t want to report a “change” that nets out to no change at all.</li></ul><p>The design solves this by splitting <strong>what the user sees</strong> from <strong>what the server is told</strong>, and reconciling the two only after the user’s input has settled.</p><h3>Core approach: optimistic update + debounce + a “last known truth” reference</h3><p><strong>1. Update the screen immediately, assuming the vote will succeed.</strong> The moment a vote button is tapped, the local list is updated right away, flipping the upvoted/downvoted flag and adjusting the vote count. This is an “optimistic” update: we don’t wait for server confirmation before showing the new state, because we’re confident the request will normally succeed, and instant feedback matters more here than certainty.</p><p><strong>2. Don’t tell the server yet, wait for a pause in activity.</strong> Rather than firing a network request on every click, the intent to sync with the server is queued behind a short delay (about a second). Every new click during that window resets the delay. Only once the user stops clicking for the full delay does the “tell the server” step actually run. This means a rapid flurry of clicks collapses down to, at most, one outgoing request, the one representing the final state after the user is done interacting.</p><p><strong>3. Before actually calling the server, check whether anything really changed.</strong> Because a user might click up, then down, then up again, the <em>net</em> result of a flurry of clicks can be identical to the state the server already believes is true. To avoid sending a pointless request in that case, the last-confirmed state is compared against the final optimistic state right before the request goes out. If they match, no request is sent at all. If they differ, the request goes out, and the “last confirmed” record is updated to reflect it.</p><p><strong>4. Keep a separate, always-current record of “what the server last agreed to.”</strong> This is distinct from what’s currently rendered on screen. The rendered state can be many rapid optimistic guesses ahead of the server. The “last confirmed” record only moves forward when the server has actually been told and presumed to accept the change. This separation is what makes step 3’s comparison meaningful, comparing the optimistic guess against itself would always report “no change.”</p><p>A technical note on <em>why</em> this “last confirmed” record needed to be a different kind of storage than the on-screen list state: values used purely for rendering can go stale inside delayed/deferred callbacks, because those callbacks capture whatever the state happened to be at the moment they were created. The last-confirmed record needed to always reflect its true latest value at the moment it’s read, regardless of timing, so it lives in a different kind of container than the visual list.</p><h3>Why compute the debounced function once, not per render</h3><p>The delay-and-reset mechanism relies on remembering a pending timer between clicks. If the wrapping function were recreated on every re-render, each new version would have no memory of a previous version’s pending timer, two clicks in quick succession could end up on two different, disconnected timers instead of one being properly cancelled by the other. So the debounced function itself is created exactly once, the first time the component renders, and reused for the lifetime of the component.</p><h3>Summary of the overall shape</h3><ul><li>Immediate, optimistic visual feedback on every interaction.</li><li>Network requests are debounced to at most one per burst of activity.</li><li>A no-op is detected and skipped when a burst of activity nets out to the same state the server already has.</li><li>A separate “last known truth” store avoids stale-data bugs that plain render state would be prone to inside delayed callbacks.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7df000f6f38" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>