<?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 Sithum Raveesha on Medium]]></title>
        <description><![CDATA[Stories by Sithum Raveesha on Medium]]></description>
        <link>https://medium.com/@sithum18raveesha?source=rss-5bc5fbc2718a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zHtdS1LZXJGip1g_</url>
            <title>Stories by Sithum Raveesha on Medium</title>
            <link>https://medium.com/@sithum18raveesha?source=rss-5bc5fbc2718a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 18 May 2026 11:40:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sithum18raveesha/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[Dynamic Price Optimization Using Reinforcement Learning]]></title>
            <link>https://medium.com/@sithum18raveesha/dynamic-price-optimization-using-reinforcement-learning-4a74776431a3?source=rss-5bc5fbc2718a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a74776431a3</guid>
            <dc:creator><![CDATA[Sithum Raveesha]]></dc:creator>
            <pubDate>Mon, 17 Feb 2025 07:44:27 GMT</pubDate>
            <atom:updated>2025-02-17T17:16:56.863Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*RAO8dSr49gR44EUV2o6JAQ.jpeg" /></figure><p>Hey everyone 👋, the main focus of this article is to explain how we can implement a <strong>Dynamic Price Optimization Agent Using Reinforcement Learning</strong>.</p><p>Pricing is one of the most critical aspects of any business, and with AI-powered techniques like <strong>Reinforcement Learning (RL)</strong>, companies can adapt their prices dynamically based on real-time market conditions.</p><p>In this blog, we will cover the fundamentals of RL in pricing, compare it with traditional AI techniques, and guide you through an implementation that optimizes pricing decisions using <strong>machine learning and data-driven strategies</strong>.</p><p>Let’s dive in! 🚀</p><h3>💡Understanding Dynamic Pricing</h3><p><strong>Dynamic pricing</strong> is a strategy where prices change in real time based on factors such as demand, inventory, competitor pricing, and customer behavior. This technique is widely used in industries like e-commerce, transportation, and hospitality.</p><h4>Why AI for Dynamic Pricing?</h4><p>AI enables businesses to make data-driven pricing decisions, adapting to market conditions instantly. <strong>Reinforcement Learning (RL)</strong> stands out as an advanced AI technique because it can learn optimal pricing strategies through continuous interactions with the environment.</p><h3>📈 Comparing AI Techniques for Dynamic Pricing</h3><p>Before implementing RL, let’s compare it with two other AI techniques: <strong>Regression Analysis</strong> and <strong>Time Series Analysis</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*rkKgtj_qWGLOGXauB-t6AQ.png" /><figcaption>Table 1: Comparison of AI Techniques</figcaption></figure><p><strong>Conclusion:</strong> While Regression and Time Series models provide useful insights, RL is the best choice for real-time price optimization due to its ability to adapt dynamically.</p><h3>⚒ How Reinforcement Learning Works in Pricing</h3><p>Reinforcement Learning (RL) is a type of machine learning where an agent learns by interacting with an environment. In dynamic pricing, the RL agent adjusts prices based on customer reactions and receives rewards in the form of revenue. Over time, it learns the best pricing strategy to maximize long-term profits.</p><h4>Key Components of RL in Pricing:</h4><ul><li><strong>State:</strong> Current market conditions (e.g., competitor price, inventory level)</li><li><strong>Action:</strong> Price adjustment decision</li><li><strong>Reward:</strong> Revenue generated from the pricing decision</li><li><strong>Policy:</strong> Strategy that the agent learns to optimize pricing decisions</li></ul><h3>Important RL Hyperparameters</h3><h4>1. Alpha (α) — Learning Rate 🧠</h4><p>Think of <strong>alpha</strong> as how much attention you give to new information versus old information.</p><ul><li>Suppose you’re learning a new way to solve a math problem. If you <strong>completely ignore</strong> your old method and only use the new one, you might make mistakes because you haven’t fully understood it yet. This is like having a <strong>very high alpha</strong> — you learn fast, but you might make a lot of errors along the way.</li><li>On the other hand, if you <strong>stick too much</strong> to what you already know and don’t accept new ideas, your learning becomes slow. This is like having a <strong>very low alpha</strong> — you’re more stable, but you don’t improve quickly.</li></ul><p>So, alpha controls <strong>how quickly the RL agent updates its knowledge</strong>. If alpha is too high, it keeps changing its decisions too much. If it’s too low, it learns very slowly.</p><h4>2. Gamma (γ) — Discount Factor ⏳</h4><p>Gamma helps the RL agent decide <strong>how much importance to give to future rewards</strong>.</p><ul><li>Imagine you have two options:</li></ul><ol><li>Get <strong>$5 now</strong> (short-term reward)</li><li>Get <strong>$20 next week</strong> (long-term reward)</li></ol><ul><li>If you really need money right now, you’ll take the $5 immediately — this is like having a <strong>low gamma</strong>, where the agent focuses only on <strong>immediate rewards</strong>.</li><li>However, if you’re thinking long-term and planning for a bigger gain, you’ll wait for the $20. This is like having a <strong>high gamma</strong>, where the agent is willing to be patient and wait for <strong>better rewards in the future</strong>.</li></ul><p>So, a high gamma value makes the agent <strong>focus on long-term gains</strong>, while a low gamma makes it <strong>only care about short-term rewards</strong>.</p><h4>3. Epsilon (ε) — Exploration Rate 🎲</h4><p>Epsilon controls the balance between <strong>exploring new things</strong> and <strong>using what we already know</strong>.</p><ul><li>Let’s say you always go to the same restaurant because you know the food is good. But what if there’s a much better restaurant nearby that you never tried? If you never explore, you’ll <strong>never find the best option</strong>!</li><li>However, if you try a new restaurant <strong>every single day</strong>, you might <strong>never settle on the best one</strong> and waste time eating at bad places.</li></ul><p>This is exactly what happens with an RL agent:</p><ul><li><strong>A high epsilon</strong> means it explores <strong>a lot</strong> and tries new actions often. This prevents it from getting stuck with a bad strategy.</li><li><strong>A low epsilon</strong> means it mostly sticks to what it already knows and stops experimenting.</li></ul><p>So, we usually <strong>start with a high epsilon</strong> (lots of exploring) and <strong>slowly decrease it</strong> over time so that the agent settles on the best strategy.</p><h4>📌Final Summary of RL Hyperparameters</h4><p><strong>Alpha (α) = Learning speed</strong> →</p><ul><li>High α = fast but unstable learning,</li><li>Low α = slow but steady learning</li></ul><p><strong>Gamma (γ) = Future thinking</strong> →</p><ul><li>High γ = plans long-term,</li><li>Low γ = focuses on short-term</li></ul><p><strong>Epsilon (ε) = Exploration</strong> →</p><ul><li>High ε = tries new things,</li><li>Low ε = sticks to what it knows</li></ul><p>By adjusting these values properly, we can make our RL agent <strong>learn smarter and make better pricing decisions</strong> over time.</p><h3>👨‍💻 Let’s see the Implementation</h3><p>To demonstrate how RL can be applied to pricing, we used a dataset containing sales, inventory levels, competitor prices, and other market variables.</p><p><a href="https://drive.google.com/file/d/1-vg0zxNCpcvTU8EU-ZhLKiyaaOHKKhwE/view?usp=sharing">retail_store_inventory.csv</a></p><h3>💰 Steps to Implement RL for Pricing:</h3><ol><li><strong>Data Preprocessing:</strong> Load sales data and clean missing values.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*yGo_sQKZnii7DyPTHHCTPA.png" /><figcaption>Fig 1: Initial data analysis</figcaption></figure><ol><li><strong>Feature Engineering:</strong> Extract key variables like demand trends and seasonal effects.</li><li><strong>Reinforcement Learning Model:</strong></li></ol><ul><li>Use <strong>Q-Learning</strong>, a popular RL algorithm, to train the model.</li></ul><pre>class QLearningAgent:<br>    def __init__(self, actions, alpha=0.1, gamma=0.9, epsilon=0.1):<br>        self.q_table = defaultdict(lambda: np.zeros(len(actions)))<br>        self.actions = actions<br>        self.alpha = alpha  # learning rate<br>        self.gamma = gamma  # discount factor<br>        self.epsilon = epsilon  # exploration rate<br>        <br>    def choose_action(self, state):<br>        # Epsilon-greedy action selection<br>        if np.random.uniform(0, 1) &lt; self.epsilon:<br>            return np.random.choice(len(self.actions))<br>        state_action = self.q_table[state]<br>        return np.random.choice(len(self.actions)) if np.all(state_action == state_action[0]) else np.argmax(state_action)<br>            <br>    def learn(self, state, action, reward, next_state):<br>        # Q-learning update rule<br>        predict = self.q_table[state][action]<br>        target = reward + self.gamma * np.max(self.q_table[next_state])<br>        self.q_table[state][action] += self.alpha * (target - predict)</pre><ul><li>The agent experiments with different price points and observes the effect on demand.</li><li>Over time, it learns the pricing strategy that maximizes revenue.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*D2PKI3QjKXJIJ5F3XHiPDA.png" /><figcaption>Fig 2: Training the RL Agent</figcaption></figure><p><strong>4. Training &amp; Evaluation:</strong> Test the model in simulated market conditions and analyze revenue improvements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*YCD8jDnSCBemmvJTv88MLw.png" /><figcaption>Fig 3: RL Agent Training Progress</figcaption></figure><h3>Results (According to the implementation done by me👀):</h3><ul><li><strong>Baseline Revenue (without RL):</strong> ~$12.8 per transaction</li><li><strong>Revenue After RL Optimization:</strong> ~$19.6 per transaction</li><li><strong>Price Accuracy:</strong> 82% correct price predictions</li><li><strong>Revenue Accuracy:</strong> 86% alignment with optimal revenue</li></ul><p>These results indicate that RL significantly improves pricing decisions compared to static methods.</p><h3>🧩 Challenges and Considerations</h3><p>While RL offers significant advantages, it comes with challenges:</p><ul><li><strong>Computational Cost:</strong> Training RL models requires powerful hardware and time.</li><li><strong>Data Requirements:</strong> A large dataset is needed for the model to learn effectively.</li><li><strong>Market Uncertainty:</strong> RL models may struggle with unexpected economic shifts or sudden customer behavior changes.</li></ul><h3>🔑 Future Improvements:</h3><ul><li><strong>Hybrid Models:</strong> Combining RL with Time Series models for better forecasting.</li><li><strong>Automated Feature Engineering:</strong> Using deep learning to extract hidden patterns in customer behavior.</li><li><strong>Explainability:</strong> Enhancing model transparency to understand why certain pricing decisions are made.</li></ul><h3>🏁 Conclusion</h3><p>Reinforcement Learning is a powerful tool for dynamic pricing, offering real-time adaptability and maximizing revenue. While traditional AI techniques like Regression and Time Series models provide useful insights, RL outperforms them by continuously learning and adjusting prices based on actual market conditions.</p><p>With further advancements in AI, dynamic pricing models will continue to evolve, helping businesses stay competitive and profitable in rapidly changing markets.</p><h3>📍Final Thoughts</h3><p>For students and professionals interested in AI-driven pricing strategies, exploring RL can provide valuable insights into real-world business applications. As computational power and data availability increase, RL-based pricing will become an essential component of modern retail and e-commerce strategies.</p><p><em>If you’re passionate about AI and business applications, dive into reinforcement learning and explore its potential in various industries beyond retail!</em></p><h4>Have thoughts or questions? Leave a comment below!</h4><blockquote>GitHub link to the project : <a href="https://github.com/sithum20210380/RL-Based-Dynamic-Price-Optimisation">https://github.com/sithum20210380/RL-Based-Dynamic-Price-Optimisation</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a74776431a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Architecting Serverless Applications with AWS]]></title>
            <link>https://medium.com/@sithum18raveesha/architecting-serverless-applications-with-aws-5b0b4db3baf7?source=rss-5bc5fbc2718a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b0b4db3baf7</guid>
            <dc:creator><![CDATA[Sithum Raveesha]]></dc:creator>
            <pubDate>Thu, 30 May 2024 16:43:50 GMT</pubDate>
            <atom:updated>2024-05-30T16:43:50.458Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0RidGZ5EKWgoL8IAUBiSGA.png" /></figure><h3><strong>What is Serverless Architecture?</strong></h3><p>Serverless architecture (also known as serverless computing) represents a paradigm shift in how we think about developing and deploying applications. Unlike traditional server-based approaches, serverless computing enables developers to concentrate solely on writing code, without having to worry about the underlying infrastructure. This means no more server provisioning, OS management, or dealing with hardware failures.</p><p>There are two key components in Serverless Architecture,</p><ul><li>Functions as a Service (FaaS)</li><li>Backend as a Service (BaaS)</li></ul><p><strong>How it differs from traditional server-based architectures</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5QzKYjhvUE5YHx8VRRxPQ.png" /><figcaption>Figure 1: Comparison between serverless and server-based architectures</figcaption></figure><p>1. Infrastructure Management:</p><ul><li>Traditional Server-Based Architecture: Requires manual provisioning, configuration, and management of physical or virtual servers. Administrators are responsible for patching, scaling, and maintaining the servers.</li><li>AWS Serverless Architecture: The cloud provider automatically handles server management, including provisioning, scaling, and maintenance. Developers focus solely on writing and deploying code.</li></ul><p>2. Scalability:</p><ul><li>Traditional Server-Based Architecture: Scaling typically involves adding more servers (vertical or horizontal scaling) and often requires manual intervention or complex auto-scaling configurations.</li><li>AWS Serverless Architecture: Automatically scales up or down in response to demand. Functions and resources automatically scale to handle the load without any manual intervention.</li></ul><p>3. Cost:</p><ul><li>Traditional Server-Based Architecture: Costs are incurred for running servers 24/7, regardless of usage. Costs include server hardware, power, cooling, and maintenance.</li><li>AWS Serverless Architecture: Pay-as-you-go pricing model, where you only pay for the actual compute time used by your code. No costs are incurred when the application is idle.</li></ul><h3>Implementation</h3><p>Step 1: Create and Build a React app</p><p>Step 2: Create Node.js backend</p><p>Step 3: Deploy Lambda functions in the AWS Lambda Console</p><p>Step 4: Create an S3 Bucket and Enable Static Website Hosting</p><p>Step 5: Setting Up API Gateway to Expose the Lambda Function</p><p>Step 6: Configure CloudFront infront of S3</p><h3><strong>Step 1: Create and Build a React app</strong></h3><p>AddStudentForm.js</p><pre>import React, { useState } from &#39;react&#39;;<br>import axios from &#39;axios&#39;;<br><br>const AddStudentForm = () =&gt; {<br>    const [studentId, setStudentId] = useState(&#39;&#39;);<br>    const [name, setName] = useState(&#39;&#39;);<br>    const [email, setEmail] = useState(&#39;&#39;);<br><br>    const handleSubmit = async (e) =&gt; {<br>        e.preventDefault();<br>        try {<br>            await axios.post(&#39;https://y7gs0ssz03.execute-api.ap-south-1.amazonaws.com/prod/&#39;, { studentId, name, email });<br>            console.log(&#39;Submitting Data:&#39;, { studentId, name, email });<br>            alert(&#39;Student added successfully&#39;);<br>            setStudentId(&#39;&#39;);<br>            setName(&#39;&#39;);<br>            setEmail(&#39;&#39;);<br>        } catch (error) {<br>            console.error(&#39;Error adding student:&#39;, error);<br>            alert(&#39;Error adding student&#39;);<br>        }<br>    };<br><br>    return (<br>        &lt;form onSubmit={handleSubmit}&gt;<br>            &lt;input type=&quot;text&quot; placeholder=&quot;ID&quot; value={studentId} onChange={(e) =&gt; setStudentId(e.target.value)} /&gt;<br>            &lt;input type=&quot;text&quot; placeholder=&quot;Name&quot; value={name} onChange={(e) =&gt; setName(e.target.value)} /&gt;<br>            &lt;input type=&quot;email&quot; placeholder=&quot;Email&quot; value={email} onChange={(e) =&gt; setEmail(e.target.value)} /&gt;<br>            &lt;button type=&quot;submit&quot;&gt;Add Student&lt;/button&gt;<br>        &lt;/form&gt;<br>    );<br>};<br><br>export default AddStudentForm;</pre><p>StudentList.js</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br>import axios from &#39;axios&#39;;<br><br>const APIURL = &#39;https://y7gs0ssz03.execute-api.ap-south-1.amazonaws.com/prod/&#39;;<br><br>const StudentList = () =&gt; {<br>    const [students, setStudents] = useState([]);<br><br>    useEffect(() =&gt; {<br>        const fetchStudents = async () =&gt; {<br>            try {<br>                const response = await axios.get(APIURL);<br>                console.log(&#39;Response:&#39;, response);<br>                const responseData = response.data.body; <br>                const students = JSON.parse(responseData);<br>                console.log(&#39;Response Data:&#39;, students);<br>                setStudents(students);<br>            } catch (error) {<br>                console.error(&#39;Error fetching students:&#39;, error);<br>            }<br>        };<br>        fetchStudents();<br>    }, []);<br><br>    return (<br>        &lt;div&gt;<br>            &lt;h2&gt;Student List&lt;/h2&gt;<br>            {students.length &gt; 0 ? (<br>                &lt;ul&gt;<br>                    {students.map((student) =&gt; (<br>                        &lt;li key={student.studentId}&gt;<br>                            {student.name} - {student.email}<br>                        &lt;/li&gt;<br>                    ))}<br>                &lt;/ul&gt;<br>            ) : (<br>                &lt;p&gt;No students found&lt;/p&gt;<br>            )}<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default StudentList;<br><br></pre><h3>Step 2: Create Node.js backend</h3><p>handler for addStudent.js</p><pre>const AWS = require(&#39;aws-sdk&#39;);<br>const dynamoDB = new AWS.DynamoDB.DocumentClient();<br><br>exports.handler = async (event) =&gt; {<br>    const { studentId, name, email } = event;<br><br>    const params = {<br>        TableName: &#39;StudentDetails&#39;,<br>        Item: {<br>            studentId: studentId,<br>            name: name,<br>            email: email<br>        }<br>    };<br><br>    try {<br>        await dynamoDB.put(params).promise();<br>        return {<br>            statusCode: 200,<br>            body: JSON.stringify({ message: &#39;Student details added successfully&#39; }),<br>            headers: {<br>                &#39;Content-Type&#39;: &#39;application/json&#39;<br>            }<br>        };<br>    } catch (error) {<br>        return {<br>            statusCode: 500,<br>            body: JSON.stringify({ message: &#39;Error adding student details&#39;, error: error.message }),<br>            headers: {<br>                &#39;Content-Type&#39;: &#39;application/json&#39;<br>            }<br>        };<br>    }<br>};</pre><p>handler for getStudent.js</p><pre>const AWS = require(&#39;aws-sdk&#39;);<br>const dynamoDB = new AWS.DynamoDB.DocumentClient();<br><br>exports.handler = async (event) =&gt; {<br>    const params = {<br>        TableName: &#39;StudentDetails&#39;,<br>    };<br><br>    try {<br>        const data = await dynamoDB.scan(params).promise();<br>        return {<br>            statusCode: 200,<br>            body: JSON.stringify(data.Items),<br>            headers: {<br>                &#39;Content-Type&#39;: &#39;application/json&#39;<br>            }<br>        };<br>    } catch (error) {<br>        return {<br>            statusCode: 500,<br>            body: JSON.stringify({ message: &#39;Error getting student details&#39;, error: error.message }),<br>            headers: {<br>                &#39;Content-Type&#39;: &#39;application/json&#39;<br>            }<br>        };<br>    }<br>};</pre><h3>Step 3: Deploy Lambda functions in the AWS Lambda Console</h3><p>First, navigate to the AWS Lambda service and click on the “Create function” button. You’ll be prompted to choose a method to create your function. Select “Author from scratch,” which allows you to manually configure all the necessary details. Give your function a name, such as NodeJsServerlessFunction, and choose Node.js as the runtime environment. For this example, you might select Node.js 16.x. Optionally, you can configure an execution role, either by creating a new role with basic Lambda permissions or by using an existing role.</p><p>After writing your function and configuring triggers, deploy the function by clicking on the “Deploy” button in the upper right corner of the Lambda console. Once deployed, you can test your function directly in the console. Click on the “Test” button, create a new test event with a sample payload, and run it to see how your function responds. The results will be displayed in the console, allowing you to verify that your function is working as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DF3i7XNJjbN27O_7FbNogA.png" /><figcaption>Figure 2: Steps to create and deploy the lambda functions</figcaption></figure><h3>Step 4: Create an S3 Bucket and Enable Static Website Hosting</h3><p>First, sign in to the AWS Management Console and navigate to the S3 service. Once there, click the “Create bucket” button. You’ll need to enter a unique bucket name, select the AWS region where you want the bucket to reside, and optionally configure settings such as versioning, tags, and default encryption. After configuring these details, click “Create bucket” to finalize the creation.</p><p>With the bucket created, you can now enable static website hosting. Open your bucket’s properties by clicking on its name in the S3 console. In the “Properties” tab, locate the “Static website hosting” section and click “Edit.” Choose the “Enable” option to activate static website hosting. You’ll need to specify an index document (e.g., index.html) and an error document (e.g., error.html). These documents will serve as the entry point and error page for your website. Once you’ve specified these, click &quot;Save changes&quot; to apply the configuration.</p><p>Next, you need to upload your website content. Navigate back to the bucket overview and click the “Upload” button. Add all the files necessary for your website, in react application, upload the files in the build folder, then click “Upload” to transfer the files to your S3 bucket. By default, these files are private, so to make your website publicly accessible, you need to adjust their permissions. Select the uploaded files, click the “Actions” button, choose “Make public,” and confirm the action.</p><p>Finally, to access your static website, go to the “Properties” tab of your bucket again. In the “Static website hosting” section, you’ll find the “Bucket website endpoint,” which is the URL of your site (e.g., http://your-bucket-name.s3-website-your-region.amazonaws.com). Open this URL in a web browser to see your website live. This setup is ideal for hosting simple static websites without the need for backend server infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZAsi-WEE3QfDB755HFZFw.png" /><figcaption>Figure 3: Generate bucket policy</figcaption></figure><h3>Step 5: Setting Up API Gateway to Expose the Lambda Function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BMvHBNsRwR5BKVeS9yeY2A.png" /><figcaption>Figure 4: Create APIs to trigger lambdas</figcaption></figure><p>Navigate to API Gateway in the AWS Management Console to create a new API. Depending on your use case, you can choose either an HTTP API or a REST API. HTTP APIs are simpler and more cost-effective for most use cases. After selecting the type of API, fill in the API name and description, then proceed to create the API. For REST APIs, create a new resource (e.g., /greet) by clicking &quot;Actions&quot; and selecting &quot;Create Resource.&quot; For HTTP APIs, add a new route (e.g., GET /greet).</p><p>To integrate your Lambda function with API Gateway, set up the Lambda integration. For REST APIs, select the created method (e.g., GET), choose &quot;Lambda Function&quot; as the integration type, select the Lambda region, enter the Lambda function name, and save the settings. For HTTP APIs, add an integration to the route, choose &quot;Lambda Function,&quot; select your Lambda function, and save the integration.</p><p>Deploying the API is the next crucial step. For REST APIs, click “Actions” and select “Deploy API,” then create a new deployment stage (e.g., dev) and click &quot;Deploy.&quot; For HTTP APIs, create a new deployment in the &quot;Deployments&quot; section and deploy it to a new stage (e.g., dev). Note the Invoke URL from the deployment stage settings and use it to test the API with tools like Postman or your browser. For example, accessing https://&lt;api-id&gt;.execute-api.&lt;region&gt;.amazonaws.com/dev/greet?name=John should return a greeting.</p><h3>Step 6: Configure CloudFront in front of S3</h3><p>Using Amazon CloudFront in front of an S3 bucket can significantly improve the performance, security, and scalability of your web content. Here’s a detailed guide on how to set it up.</p><h4>Create a CloudFront Distribution</h4><p>Next, navigate to the CloudFront service in the AWS Management Console and click “Create Distribution.” Select “Get Started” under the “Web” delivery method. In the “Origin Settings,” specify your S3 bucket as the origin. You can either type the S3 bucket’s name or use the dropdown to select it.</p><h4>Configure Distribution Settings</h4><p>In the distribution settings, you can configure various parameters to suit your needs. For the “Origin Settings,” set the origin domain name to your S3 bucket’s URL and configure the origin path if your content is stored in a specific folder within the bucket. Enable “Restrict Bucket Access” to ensure that CloudFront is the only entity allowed to fetch content from your S3 bucket directly.</p><p>In the “Default Cache Behavior Settings,” set the “Viewer Protocol Policy” to “Redirect HTTP to HTTPS” to enforce secure connections. Configure caching settings, such as the allowed HTTP methods and cache TTL (Time to Live) values. For the “Distribution Settings,” set the price class according to your budget and expected geographic distribution of your users. Enable logging if you want to track access logs for your distribution and add alternate domain names (CNAMEs) if you have a custom domain name.</p><h4>Set Up Permissions</h4><p>If you enabled “Restrict Bucket Access,” you need to configure an origin access identity (OAI) to grant CloudFront permissions to access your S3 bucket. Create a new OAI or use an existing one, and update the bucket policy to allow CloudFront to fetch objects. You can do this by attaching a bucket policy that grants the OAI read access to the S3 bucket.</p><h4>Deploy the CloudFront Distribution</h4><p>Review your settings and click “Create Distribution.” CloudFront will start creating the distribution, which may take several minutes. Once deployed, you’ll receive a CloudFront domain name, such as d1234567890abcdef.cloudfront.net. Use this domain name to access your content.</p><h3>Conclusion:</h3><p>In this blog, we covered the essential steps to implement a serverless architecture using React and Node.js. Starting with creating and building a React app, we then set up a Node.js backend. The deployment of Lambda functions in the AWS Lambda Console followed, which is a core component of our serverless setup. Next, we created an S3 bucket and enabled static website hosting, making our frontend accessible over the web. To connect our backend logic with the frontend, we set up API Gateway to expose the Lambda functions. Finally, we configured CloudFront in front of our S3 bucket to enhance performance and security.</p><p>By following these steps, you can effectively deploy a serverless application that is robust, scalable, and cost-efficient. This architecture not only simplifies the deployment process but also provides flexibility and resilience, enabling you to build modern web applications with ease. Whether you are a seasoned developer or new to serverless technologies, these steps will guide you through creating and deploying your serverless applications successfully.</p><p>GitHub Repo: <a href="https://github.com/sithum20210380/my-serverless-app.git">https://github.com/sithum20210380/my-serverless-app.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b0b4db3baf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>