<?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 Anurajshrestha on Medium]]></title>
        <description><![CDATA[Stories by Anurajshrestha on Medium]]></description>
        <link>https://medium.com/@anurajshrestha75?source=rss-bdccad9a5613------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zpG-BeFx5yZbS9kL</url>
            <title>Stories by Anurajshrestha on Medium</title>
            <link>https://medium.com/@anurajshrestha75?source=rss-bdccad9a5613------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:29:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anurajshrestha75/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[I Built a Staging Environment That Costs 85% Less and Never Gets in a Developer’s Way]]></title>
            <link>https://medium.com/@anurajshrestha75/i-built-a-staging-environment-that-costs-85-less-and-never-gets-in-a-developers-way-eb44222ad455?source=rss-bdccad9a5613------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb44222ad455</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[aws-cost-optimization]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Anurajshrestha]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 11:21:57 GMT</pubDate>
            <atom:updated>2026-07-09T11:21:57.245Z</atom:updated>
            <content:encoded><![CDATA[<p>How native AWS scheduling, a holiday-aware Lambda, and a single Slack command turned an always-on server into something that only runs when it’s actually needed, without ever blocking someone who wants to work at 2am.</p><h3>The Problem</h3><p>A staging server that runs 24/7 solves exactly one problem: availability. It also creates a second problem nobody asks for: you’re paying for compute at 2am on a Tuesday when nobody on the team is awake to use it, and you’re paying for it again on a public holiday when the whole office is closed.</p><p>The obvious fix is to turn it off outside working hours. The less obvious problem is what that fix breaks. Developers don’t always work nine to five. Someone debugging a production issue at midnight, or a developer in a different time zone, or a QA engineer who just wants to push one more test run before a deadline, all need staging available on their schedule, not the schedule a cost-saving script assumes everyone follows.</p><p>So the real requirement wasn’t “turn it off at night.” It was “turn it off by default, but never make it inconvenient for someone to turn it back on.”</p><p>That distinction shaped almost every decision in this build.</p><h3>The Core Idea</h3><p>Instead of one server running constantly, this setup uses an Auto Scaling Group with a minimum of zero instances, running on spot pricing, controlled by three independent mechanisms that never conflict with each other:</p><ol><li>A native AWS scheduled action that handles the routine daily cycle</li><li>A small Lambda function that checks a public holiday calendar and skips starting the server on days nobody’s working</li><li>A Slack command, /staging-start, that any developer can type at any hour to bring the server up immediately, no ticket, no waiting, no asking permission</li></ol><p>The third one is the piece that actually matters most. Cost savings are nice, but they’re worthless if they come at the expense of someone’s ability to do their job at an inconvenient hour. A developer debugging something at 2am shouldn’t need to know anything about Auto Scaling Groups, EventBridge, or Lambda functions. They should be able to open Slack, type one line, and have a working environment in a couple of minutes.</p><p>Here’s what the whole thing looks like end to end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wHZH5HQkOCmrrolebXaNpw.png" /><figcaption>Full architecture: Slack, holiday checks, and scheduling all feeding one Auto Scaling Group</figcaption></figure><p>Three separate paths in, all pointing at the same Auto Scaling Group. Everything downstream of that, the actual EC2 instance and the persistent storage attached to it, works the same way no matter which of the three caused the instance to launch. The next few sections walk through each piece of this picture.</p><h3>How the Scheduling Actually Works</h3><p>The routine part is the simplest. AWS Auto Scaling Groups support native scheduled actions, and recent versions accept a time zone parameter directly, so there’s no need to hand convert local time into UTC. The server scales up at 10am and down at 5pm, Monday through Friday, in the local time zone, with zero custom code involved.</p><p>Public holidays needed something smarter, since a fixed schedule has no idea what day it is on a national calendar. A small Lambda function runs every weekday morning, five minutes after the scheduled start, and checks Google’s public holiday calendar for that country. If today is a holiday, the Lambda forces the Auto Scaling Group back down. If it isn’t, the Lambda does nothing at all, and the server just keeps running as scheduled.</p><p>Letting the scheduled start happen first and then reversing it a few minutes later, rather than trying to prevent the start in the first place, avoids a coordination problem where two systems try to update the same resource at the same moment. The cost of that short overlap is a fraction of a cent. Worth it for the simplicity.</p><h3>The Part That Actually Matters: Never Blocking a Developer</h3><p>Here’s the part I think most cost optimization write ups skip past. It’s easy to build a system that turns something off reliably. It’s much easier to accidentally build a system that annoys the people who depend on it.</p><p>The fix was a Slack slash command. Type /staging-start, and within a couple of minutes the environment is live. Type /staging-stop if the team decides to close early for a half day, or if someone just remembers late that today was never going to need staging at all.</p><p>No calendar entry required. No advance notice. No waiting on someone else to notice and manually spin up an instance. Just a single line typed into a channel, verified against Slack’s own signing secret so nobody outside the team can trigger it, and it’s done.</p><p>This is the piece that makes the whole cost optimization philosophy honest. It would be easy to save money by making the server harder to access. That’s not a real win. The actual win is a system where the default state is off, but turning it back on is exactly as easy as it should be, regardless of the hour.</p><h3>Making Spot Instances Safe for Something Stateful</h3><p>Spot instances are the other half of the savings, but they come with a real tradeoff: AWS can reclaim them at any time, and a plain spot instance that gets interrupted just stays down until someone notices.</p><p>Running the spot instance inside an Auto Scaling Group solves that. If AWS interrupts the instance, the ASG automatically launches a replacement, with no human involvement.</p><p>The remaining problem was persistence. This staging server runs Certbot for SSL certificates and holds application data that can’t just vanish every time the underlying instance changes. The fix is a separate EBS volume that exists independently of any one instance. Every time the ASG launches a new instance, a lifecycle hook pauses that instance briefly, an event fires, and a small Lambda function reattaches the same persistent volume to the new instance before it’s allowed to go live. Certificates, data, everything survives, no matter how many times the actual compute underneath gets swapped out.</p><p>One specific lesson worth calling out: none of this certificate handling should ever live in a boot time script. Since the instance restarts daily, anything that requests a new certificate on every single boot will hit Let’s Encrypt’s rate limit within days. Certificates get issued once and then simply persist on the volume. The boot script’s only job regarding certificates is to make sure the volume carrying them is mounted, nothing more.</p><p>A second, related lesson from actually running this: Nitro-based instances, which includes every current-generation type in this fallback chain, don’t expose an attached EBS volume at the device name you specify when attaching it. A script waiting for that exact device name will simply hang forever, since it never appears. The volume shows up instead as an NVMe device whose exact name depends on attach order. The fix is waiting for a stable, ID-based symlink AWS provides specifically for this, rather than the device name given at attach time.</p><h3>Keeping a Domain Pointed at a Server That Keeps Changing</h3><p>Here’s a problem this whole approach creates that isn’t obvious until you actually try to point a real domain at it: every time the ASG launches a replacement instance, that instance gets a brand new public IP address. A spot interruption changes it. The daily restart changes it. A manual Slack start changes it. If a domain is pointed directly at a fixed IP, it breaks constantly.</p><p>The obvious fix is an Elastic IP, a static address that stays the same regardless of which instance it’s attached to. The obvious fix is also the expensive one for this specific setup. Under AWS’s current pricing, every public IPv4 address is billed hourly, whether it’s attached to something or just sitting idle. Since this server is intentionally offline most of the week, an Elastic IP would spend most of its life idle and billed anyway, working out to several times more than the cost of the ordinary, changing public IP the instance already gets for free during the hours it actually runs.</p><p>The better fix reuses infrastructure that’s already there. The same small function that reattaches the EBS volume on every instance launch also looks up the new instance’s public IP and pushes it straight to the DNS provider, updating the domain automatically within about a minute. No static IP required, no idle resource sitting around being billed for doing nothing. The domain simply always points at wherever the server currently is.</p><h3>What This Actually Costs</h3><p>Based on a Mumbai region deployment, a mid-size instance class, and roughly 35 working hours a week:</p><p>Compute on spot pricing runs somewhere around two to three dollars a month. The persistent EBS volume adds about a dollar sixty. Three small secrets stored for the Lambda functions, the calendar credentials, the Slack signing secret, and a DNS API token, add a little over a dollar combined. Everything else, the Lambda invocations themselves, the API Gateway routing Slack’s requests, the EventBridge rules, and the DNS updates, comes out to effectively nothing at this scale, well inside the free tier or genuinely free outright.</p><p>All in, the total lands somewhere between four dollars ninety five cents and five dollars sixty five cents a month.</p><p>The same instance class running around the clock on demand costs roughly thirty three dollars a month. That’s about an 85 percent reduction, for a system that’s actually more available to the people who need it, not less.</p><h3>Get the Code and Deploy It Yourself</h3><p>The full Terraform configuration for everything described above, the Auto Scaling Group, the launch template, the persistent EBS volume, all three Lambda functions, and the Slack integration, is available here:</p><p><a href="https://github.com/raj1552/Staging-on-demand"><strong>https://github.com/raj1552/Staging-on-demand</strong></a></p><p>If you want to run this yourself, here’s the short version of what that involves.</p><p><strong>Before you start</strong>, you’ll need an AWS account with permissions to create IAM roles, EC2 resources, Lambda functions, Secrets Manager secrets, API Gateway, and EventBridge rules. You’ll also need a Google Cloud project for the holiday check, a Slack workspace where you can install apps, and Terraform 1.5 or newer installed locally.</p><p><strong>Clone the repository</strong>, then copy terraform.tfvars.example to terraform.tfvars and fill in your own values: your VPC ID, a subnet ID inside it, the matching availability zone, your EC2 key pair name, and the IP address allowed to SSH in. The example file documents every field you need.</p><p><strong>Set up the Google side</strong> before running Terraform. Create a service account in Google Cloud Console under Application Data, skip granting it any project level permissions since it doesn’t need them, and generate a JSON key. If you only need official public holidays for your country, most countries already have a public Google Calendar for this, so no calendar sharing step is required at all. If you need to track company-specific closures too, that’s a private calendar shared with the service account’s email address instead.</p><p><strong>Create the AWS Secrets Manager entries</strong> before your first deploy, one for the Google service account JSON, one for a Cloudflare API token scoped to just the one DNS zone, and one placeholder for the Slack signing secret you’ll fill in properly once the Slack app exists. Terraform’s IAM policies reference these secrets by name, but the actual values only need to be real by the time the Lambdas run, not at deploy time.</p><p><strong>Run terraform init, then terraform plan, then terraform apply.</strong> Everything deploys in dependency order. If a specific resource fails partway through, fixing the issue and re-running apply picks up exactly where it left off.</p><p><strong>Create the Slack app last</strong>, using an app manifest and the API Gateway endpoint Terraform gives you as an output. Install it to your workspace, copy the real signing secret from the app’s settings, and update the placeholder secret in AWS with that real value. At that point both slash commands are live.</p><p>The repository’s own documentation goes into far more detail than fits here, including the specific errors we actually hit while building this (a security group description failing on a stray non-ASCII character, an IAM permissions gap on the deploying user, a Slack manifest validation quirk, and a Lambda caching bug that silently broke the Slack commands after a secret rotation). If you run into something unexpected, that’s the first place to check.</p><h3>How to Confirm It’s Actually Working</h3><p>Deploying this is one thing. Trusting it enough to stop watching it closely is another. Here’s what to check for each piece once it’s live.</p><p><strong>Slack integration</strong> Type /staging-stop, confirm the reply comes back and the Auto Scaling Group&#39;s desired capacity drops to zero. Type /staging-start, confirm the instance moves from pending to running within a minute or two.</p><p><strong>Holiday check</strong> Add a test event to the calendar for today, manually invoke the Lambda, and confirm the Auto Scaling Group gets forced to zero even though the schedule would normally have started it. Remove the test event and confirm a second invocation does nothing.</p><p><strong>Daily schedule</strong> Watch the Auto Scaling Group’s activity history around the two scheduled times. One scale up in the morning, one scale down in the evening, no Lambda involved in either.</p><p><strong>EBS reattachment</strong> Terminate the running instance manually. Once the replacement comes up, confirm the same EBS volume ID (not a new one) is attached to it, and confirm data from before the termination is still there.</p><h3>The Bigger Point</h3><p>Cost optimization is easy to get wrong in one specific way: by treating availability and cost as a straight tradeoff, where saving money always means someone, somewhere, has to wait longer or work around a schedule that isn’t theirs.</p><p>This setup tries to avoid that. The routine cost savings run entirely on autopilot, a fixed schedule and a holiday check that nobody has to think about day to day. But the moment a real person needs the environment outside that window, at 2am, on a weekend, during a supposed holiday that turned into a work day anyway, there’s a single command standing between them and a working staging server. Not a ticket. Not a wait. One line in Slack.</p><p>That’s really the whole idea. Save money automatically. Never make a person pay the price for it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb44222ad455" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating PostgreSQL & Media Files to AWS (GCP → RDS + S3)]]></title>
            <link>https://medium.com/@anurajshrestha75/migrating-postgresql-media-files-to-aws-gcp-rds-s3-7835c12727b7?source=rss-bdccad9a5613------2</link>
            <guid isPermaLink="false">https://medium.com/p/7835c12727b7</guid>
            <category><![CDATA[cloud-migration]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws-dms]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Anurajshrestha]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 07:45:12 GMT</pubDate>
            <atom:updated>2026-04-24T07:45:12.391Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Moving a production database and file storage to AWS doesn’t have to be painful. In this post, I’ll walk through exactly how I migrated a PostgreSQL database and application media files from a GCP Compute Engine VM to <strong>Amazon RDS</strong> and <strong>Amazon S3 </strong>with near-zero downtime using AWS DMS Serverless and Rclone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bIud_-yNk5y1C_1cLPetng.png" /></figure><h4>The Stack</h4><p><strong>Source (origin):</strong></p><ul><li>GCP Compute Engine VM</li><li>PostgreSQL running directly on the VM</li><li>Media files on local/persistent disk</li></ul><p><strong>Target (destination):</strong></p><ul><li>Amazon RDS for PostgreSQL (fully managed)</li><li>Amazon S3 for media/file storage</li><li>Amazon EC2 for the application layer</li><li>NAT Gateway for stable egress IP</li></ul><h3>Part 1 — Database Migration (PostgreSQL → Amazon RDS via AWS DMS)</h3><h4>Step 1: Enable Logical Replication on the Source PostgreSQL</h4><p>On your GCP Compute Engine, edit postgresql.conf:</p><pre>wal_level = logical<br>max_replication_slots = 5<br>max_wal_senders = 5</pre><p>Then restart PostgreSQL:</p><pre>sudo systemctl restart postgresql</pre><h4>Step 2: Create a DMS Replication User</h4><p>On the source database, create a dedicated user for DMS:</p><pre>CREATE USER dms_user WITH PASSWORD &#39;yourpassword&#39;;<br>GRANT REPLICATION TO dms_user;<br>GRANT SELECT ON ALL TABLES IN SCHEMA public TO dms_user;<br>ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO dms_user;</pre><h4>Step 3: Configure pg_hba.conf to Allow DMS Connections</h4><p>This is the part most tutorials skip. Your NAT Gateway’s Elastic IP needs to be whitelisted in pg_hba.conf on the source PostgreSQL:</p><pre># pg_hba.conf<br>host    all    dms_user    &lt;NAT_GATEWAY_ELASTIC_IP&gt;/32    md5</pre><p>Reload PostgreSQL after editing:</p><pre>sudo systemctl reload postgresql</pre><blockquote><strong><em>Why NAT Gateway?</em></strong><em> AWS DMS Serverless runs inside your VPC. The NAT Gateway gives it a static, routable public Elastic IP so you can whitelist it in GCP’s firewall — otherwise DMS connections get blocked.</em></blockquote><h4>Step 4: Open GCP Firewall for the NAT Gateway IP</h4><p>In GCP Console → VPC Network → Firewall, create an ingress rule:</p><ul><li><strong>Target:</strong> your Compute Engine instance</li><li><strong>Source IP:</strong> &lt;NAT_GATEWAY_ELASTIC_IP&gt;/32</li><li><strong>Port:</strong> 5432 (TCP)</li></ul><h4>Step 5: Provision Amazon RDS (PostgreSQL)</h4><p>Create your RDS instance with the <strong>same major PostgreSQL version</strong> as your source. Set it to be accessible from within your VPC (no need for public access if EC2 and RDS are in the same VPC).</p><h4>Step 6: Configure DMS Serverless</h4><p>In the AWS DMS Console:</p><ol><li>Create a <strong>Source Endpoint</strong> → PostgreSQL, pointing to your GCP VM’s public IP, port 5432, using dms_user credentials.</li><li>Create a <strong>Target Endpoint</strong> → Amazon RDS for PostgreSQL.</li><li>Create a <strong>Serverless Replication Configuration</strong>:</li></ol><ul><li>Migration type: <strong>Full Load + CDC</strong> (Change Data Capture)</li><li>This copies all existing data first, then continuously replicates new writes — giving you minimal downtime.</li></ul><h4>Step 7: Run the Pre-Migration Assessment</h4><p>Before starting, run DMS’s built-in assessment:</p><pre>DMS Console → Replication → Run Pre-migration Assessment</pre><p>This flags unsupported data types or missing permissions before they become a problem mid-migration.</p><h4>Step 8: Start Replication &amp; Validate</h4><ol><li>Start the Full Load — DMS copies all existing rows.</li><li>CDC kicks in automatically after Full Load completes, keeping source and target in sync.</li><li>Validate row counts per table:</li></ol><pre>-- Run on both source and target, compare counts<br>SELECT schemaname, tablename, n_live_tup<br>FROM pg_stat_user_tables<br>ORDER BY n_live_tup DESC;</pre><h4>Step 9: Cutover</h4><p>When you’re confident the target is in sync:</p><ol><li>Stop writes to the source (brief maintenance window).</li><li>Update your application’s DATABASE_URL / connection string to point to the RDS endpoint.</li><li>Stop the DMS replication task.</li></ol><h3>Part 2 — Media File Sync (GCP Disk → Amazon S3 via Rclone)</h3><h4>Step 1: Install Rclone on GCP Compute Engine</h4><p>bash</p><pre>curl https://rclone.org/install.sh | sudo bash</pre><h4>Step 2: Configure the S3 Remote</h4><p>bash</p><pre>rclone config</pre><p>Walk through the prompts:</p><p>FieldValueNames3-prodStorageAmazon S3ProviderAWSAuthAccess Key + Secret (or instance profile)Regione.g. ap-south-1Bucketyour bucket name</p><h4>Step 3: Dry Run First</h4><p>Always preview before syncing:</p><pre>rclone sync /var/www/media s3-prod:your-bucket/media --dry-run</pre><h4>Step 4: Run the Sync</h4><pre>rclone sync /var/www/media s3-prod:your-bucket/media --progress</pre><h4>Step 5: Schedule Ongoing Sync with Cron</h4><pre># /etc/cron.d/rclone-sync<br>0 * * * * root rclone sync /var/www/media s3-prod:your-bucket/media --log-file=/var/log/rclone.log</pre><h4>Step 6: Validate</h4><pre># Compare sizes<br>rclone size /var/www/media<br>rclone size s3-prod:your-bucket/media</pre><p>Spot-check a few files by downloading from S3 and comparing checksums.</p><h4>IAM Permissions for Rclone</h4><p>The IAM user/role needs:</p><pre>{<br>  &quot;Effect&quot;: &quot;Allow&quot;,<br>  &quot;Action&quot;: [<br>    &quot;s3:PutObject&quot;,<br>    &quot;s3:GetObject&quot;,<br>    &quot;s3:DeleteObject&quot;,<br>    &quot;s3:ListBucket&quot;,<br>    &quot;s3:GetBucketLocation&quot;<br>  ],<br>  &quot;Resource&quot;: [<br>    &quot;arn:aws:s3:::your-bucket&quot;,<br>    &quot;arn:aws:s3:::your-bucket/*&quot;<br>  ]<br>}</pre><blockquote><strong><em>Tip:</em></strong><em> If Rclone runs on EC2, use an </em><strong><em>instance profile</em></strong><em> instead of long-lived access keys.</em></blockquote><h3>Summary</h3><p>StepToolFrom → ToDatabase migrationAWS DMS ServerlessGCP PostgreSQL → Amazon RDSFile syncRcloneGCP disk → Amazon S3Stable egress IPNAT GatewayDMS → GCP (whitelisted)</p><p>The pg_hba.conf + NAT Gateway Elastic IP whitelisting is the step that trips most people up — once that&#39;s sorted, the rest of the DMS flow is straightforward.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7835c12727b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3-Tier Web Application Architecture on AWS]]></title>
            <link>https://medium.com/@anurajshrestha75/3-tier-web-application-architecture-on-aws-1d2cfef46eef?source=rss-bdccad9a5613------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d2cfef46eef</guid>
            <category><![CDATA[sqs]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[vpc]]></category>
            <category><![CDATA[3-tier-architecture]]></category>
            <category><![CDATA[autoscaling]]></category>
            <dc:creator><![CDATA[Anurajshrestha]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 08:00:49 GMT</pubDate>
            <atom:updated>2026-02-14T08:00:49.233Z</atom:updated>
            <content:encoded><![CDATA[<p>Building a scalable and highly available web application requires more than just writing code it demands a solid infrastructure foundation. Whether you’re deploying a PHP application, a Node.js API, or any web service, understanding how to architect your solution on AWS is crucial for success.</p><p>In this article, I’ll walk you through a production-ready 3-tier architecture on AWS that includes auto-scaling, high availability across multiple availability zones, and built-in monitoring. This isn’t just theory it’s a practical design pattern used by thousands of companies to serve millions of users.</p><p><strong>What you’ll learn:</strong></p><ul><li>How to structure a highly available 3-tier application</li><li>Setting up auto-scaling based on CloudWatch metrics</li><li>Implementing security best practices with IAM roles and Secrets Manager</li><li>Designing for fault tolerance with Multi-AZ deployment</li></ul><p>Let’s dive in! 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*85uTWn_v8nc17X9gWP6tSQ.png" /><figcaption>Complete 3-tier web application architecture on AWS with high availability and auto-scaling</figcaption></figure><p>Let’s break down this architecture step by step. While it may look complex at first glance, each component serves a specific purpose in creating a reliable, scalable, and secure application infrastructure.</p><h3>Architecture Overview</h3><p>This design follows the classic <strong>3-tier architectural pattern</strong>, which separates concerns into three distinct layers:</p><ul><li><strong>Presentation Tier</strong> — Handles incoming user requests via Internet Gateway and Application Load Balancer</li><li><strong>Application Tier</strong> — Processes business logic using auto-scaling EC2 instances</li><li><strong>Data Tier</strong> — Manages persistent storage with Multi-AZ RDS databases</li></ul><p>But we’ll be going beyond the basics by incorporating production-grade features: CloudWatch monitoring for observability, auto-scaling for dynamic capacity management, Secrets Manager for credential security, and SQS for asynchronous task processing.</p><h3>Task 1: Creating the VPC Infrastructure</h3><h4>What We’re Building:</h4><ul><li>1 VPC</li><li>2 Availability Zones (AZ1, AZ2)</li><li>6 Subnets total (3 per AZ):</li><li>2 Public subnets (for NAT Gateway)</li><li>2 Application/Private subnets (for EC2)</li><li>2 Database subnets (Isolated for RDS)</li><li>1 Internet Gateway</li><li>2 NAT Gateways (one per AZ)</li><li>Route Tables</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kzyghm0u0IxUfTP3qeTdQA.png" /></figure><h4>Step 1: Create the VPC</h4><ul><li>Go to <strong>VPC Dashboard</strong> → <strong>Your VPCs</strong> → <strong>Create VPC</strong> Select <strong>VPC and more</strong> (this is the wizard you’re using — it creates VPC + subnets + gateways + route tables automatically)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1sjShlBGnajU4mK4gae2-Q.png" /></figure><p><strong>VPC settings</strong></p><ul><li><strong>Resources to create</strong>: VPC and more</li><li><strong>Name tag auto-generation</strong>: Auto-generate → Enter base name: My Project → All resources will be named like My Project-vpc, My Project-subnet-public1-us-east-1a, etc.</li><li><strong>IPv4 CIDR block</strong>: 10.0.0.0/16 (default — good size, 65,536 IPs)</li><li><strong>IPv6 CIDR block</strong>: No IPv6 CIDR block (your choice — fine unless you need IPv6)</li><li><strong>Tency</strong>: Default</li></ul><p><strong>Availability Zones (AZs)</strong></p><ul><li>Number of Availability Zones: <strong>2</strong> (us-east-1a and us-east-1b — good for HA)</li></ul><p><strong>Customize subnets</strong></p><ul><li>Number of public subnets: <strong>2</strong> (one per AZ — needed for ALB and NAT)</li><li>Number of private subnets: <strong>2</strong> (application tier — for EC2)</li><li>Number of database subnets: <strong>2</strong> (isolated — for RDS)</li><li>→ This automatically creates 6 subnets total (3 per AZ)</li></ul><p><strong>NAT Gateways</strong></p><ul><li>Number of NAT Gateways: <strong>2</strong> (one per AZ — high availability</li><li>NAT Gateway type: <strong>Regional</strong> (newer, cheaper, multi-AZ capable)</li><li>Elastic IP allocation: <strong>Automatic</strong> (AWS allocates Elastic IPs for NAT)</li></ul><p><strong>VPC endpoints</strong></p><ul><li>Leave as <strong>None</strong> (you can add later for S3/DynamoDB private access)</li></ul><p><strong>DNS options</strong></p><ul><li>Enable DNS hostnames: Checked</li><li>Enable DNS resolution: Checked (Both recommended — allows private DNS names inside VPC)</li></ul><p><strong>Preview &amp; Create</strong></p><ul><li>Review the preview diagram:</li><li>VPC: My Project-vpc (10.0.0.0/16)</li><li>Subnets (6 total):</li><li>Public: My Project-subnet-public1-us-east-1a, public2-us-east-1b</li><li>Private/application: My Project-subnet-private3-us-east-1a, private2-us-east-1b</li><li>Database: My Project-subnet-private1-us-east-1a, private4-us-east-1b (isolated)</li><li>Route tables (5 total — one for each subnet type + main)</li><li>Internet Gateway + 2 NAT Gateways</li><li>Click <strong>Create VPC</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BfrNPXX2TDAg9ygIm1F4YA.png" /></figure><p><strong>Wait for creation</strong></p><ul><li>Takes 2–5 minutes</li><li>Progress bar shows steps: VPC creation → subnets → route tables → NAT Gateways → Elastic IP allocation → verification</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RsRuFj25xOPWrHO911Z_2A.png" /></figure><h4>Step 2: Create Dedicated Route Tables</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MvjAFKv_5ZueqZ1dCpx3Fw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cyTTWBDxdY25Y1Fj9UdLWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1pDTVSCQe1IPfZ-jaffUYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vhF_-A-iH_qdLnKz-bVGeg.png" /></figure><h4><strong>Step 2A: Merge / Consolidate Application (Private) Subnets into One</strong></h4><ul><li>Identify route tables already associated with private subnets (look at “Explicit subnet associations”):</li><li>Pick <strong>one</strong> to keep (usually the one with NAT route 0.0.0.0/0 → NAT Gateway)</li></ul><p>Edit subnet associations:</p><ul><li>Select that route table → <strong>Subnet associations</strong> tab → <strong>Edit subnet associations</strong></li><li>Check <strong>all</strong> private/application subnets:</li><li>My Project-subnet-private3-us-east-1a</li><li>My Project-subnet-private2-us-east-1b</li><li>Click <strong>Save associations</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MbpvtBZ-bwplOWk-pHsBpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ivmcICZn06EUOARbE0Qfzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xd12lXYPzYNHCL18r9DIkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tXTandWZKHCcFH_H3Z-NYw.png" /></figure><h4><strong>Step 2B: Merge / Consolidate Database (Isolated) Subnets into One</strong></h4><ul><li>Identify route tables associated with database subnets (or create new one):</li><li>Best: Create a <strong>new</strong> route table for DB</li><li>Click <strong>Create route table</strong></li><li>Name: My Project-rtb-db-isolated</li><li>VPC: My Project-vpc</li><li>Click Create</li></ul><p>Associate DB subnets:</p><ul><li>Select new route table → <strong>Subnet associations</strong> → <strong>Edit</strong></li><li>Check both database subnets:</li><li>My Project-subnet-private1-us-east-1a</li><li>My Project-subnet-private4-us-east-1b</li><li>Save</li></ul><p><strong>Important</strong>: Edit routes → <strong>Remove</strong> any 0.0.0.0/0 → NAT Gateway route</p><ul><li>Select route table → <strong>Routes</strong> tab → <strong>Edit routes</strong></li><li>Delete the line: 0.0.0.0/0 → NAT Gateway</li><li>Keep only: 10.0.0.0/16 → local</li><li>Save routes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*npwCWQQVMkj9658IDFz3pQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZF8YzV5Uaoj6Lvz-OidAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WrIrpL3E1pA3cRwek1Ibyw.png" /></figure><h4><strong>Step 3: Delete Unused / Extra Route Tables</strong></h4><ul><li>Back in Route tables list</li><li>Select any route table with <strong>0 explicit subnet associations</strong> (or redundant ones)</li><li>Click <strong>Actions</strong> → <strong>Delete route table</strong></li><li>Confirm deletion (only possible if no subnets associated)</li><li>Repeat until you have <strong>only 3–4 route tables</strong>:</li><li>Main/default</li><li>Public (with IGW)</li><li>Private/application (with NAT)</li><li>DB isolated (local only)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JVyKB-6H3plnWCP3pdZR9w.png" /></figure><h4><strong>Step 3C: Rename Subnets for Clarity and Isolate Database Subnets</strong></h4><ul><li>Go to <strong>Subnets</strong> in VPC Dashboard</li><li>Select each subnet → <strong>Actions</strong> → <strong>Edit subnet settings</strong> (or just click name to rename)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GSVDXD49PKY-0pw5k9g08Q.png" /></figure><h3>Task 2: Create the Security Groups</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDgBEvYsMUv-4JadodnNog.png" /></figure><h4>Step 1: Create ALB-SG (for Load Balancer)</h4><p><strong>Basic details</strong>:</p><ul><li><strong>Security group name</strong>: ALB-SG</li><li><strong>Description</strong>: “Public-facing SG for Application Load Balancer”</li><li><strong>VPC</strong>: Select your VPC (vpc-003df8abcb1e24942 / My Project-vpc)</li></ul><p><strong>Inbound rules</strong>:</p><p>Add rule:</p><ul><li>Type: <strong>HTTP</strong> → Protocol: TCP, Port: 80, Source: <strong>Anywhere-IPv4 (0.0.0.0/0)</strong></li><li>Add another: Type: <strong>HTTPS</strong> → TCP, Port: 443, Source: <strong>Anywhere-IPv4 (0.0.0.0/0)</strong></li><li><strong>Outbound rules</strong>: Keep default <strong>All traffic</strong> (or restrict to Application-SG if you want tighter control).</li><li>Click <strong>Create security group</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yw47YfKJvkznxA2kZ0audQ.png" /></figure><h4>Step 2: Create Application-SG (for EC2 / Application Tier)</h4><p><strong>Basic details</strong>:</p><ul><li><strong>Security group name</strong>: Application-SG</li><li><strong>Description</strong>: “SG for private EC2 instances (PHP app) allows access from ALB”</li><li><strong>VPC</strong>: Same as above.</li></ul><p><strong>Inbound rules</strong>:</p><p>Add rule:</p><ul><li>Type: <strong>HTTP</strong> (or Custom TCP if your app uses non-standard port e.g. 8080)</li><li>Protocol: TCP</li><li>Port range: 80 (or 8080/9000 for PHP-FPM)</li><li>Source: <strong>Custom</strong> → Search and select <strong>ALB-SG</strong> (sg-xxxxxxxx)</li><li>Add HTTPS (443) if needed, same source.</li><li>Click <strong>Create security group</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ayOWc0LAjuDs6-lMpc2YIQ.png" /></figure><h4>Step 3: Create RDS-SG (for Database Tier)</h4><p><strong>Basic details</strong>:</p><ul><li><strong>Security group name</strong>: RDS-SG</li><li><strong>Description</strong>: “SG for RDS MySQL — allows access only from Applicatio tier”</li><li><strong>VPC</strong>: Same VPC.</li></ul><p><strong>Inbound rules</strong>:</p><p>Add rule:</p><ul><li>Type: <strong>MySQL/Aurora</strong></li><li>Protocol: TCP</li><li>Port range: 3306</li><li>Source: <strong>Custom</strong> → Select <strong>Application-SG</strong> (sg-xxxxxxxx)</li><li>Click Create security group.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2txMyLKr38KucQzcndKffA.png" /></figure><h3>Task 3: Create IAM Role for EC2 Instances (Secrets Manager &amp; SQS Access)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B4vUcVoZwcrB_jRPt0PvuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RycEqf5wiDNYqTBwuwc8gw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8tCjUmJg69VFdZuBN132wQ.png" /></figure><h4>Step 1: Select trusted entity</h4><ul><li><strong>Trusted entity type</strong>: Select <strong>AWS service</strong></li><li><strong>Use case</strong>: Scroll down → Choose <strong>EC2</strong> (It says: “Allows EC2 instances to call AWS services on your behalf.”)</li><li>Click <strong>Next</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0vdIx7IyduoLCl4dUSdgQ.png" /></figure><h4>Step 2: Add permissions</h4><p>You will attach <strong>AWS managed policies</strong> (easiest and most secure for now).</p><p>Search and check the following policies:</p><ol><li><strong>Secrets Manager access</strong></li></ol><ul><li>Search: secretsmanager</li><li>Select: <strong>SecretsManagerReadWrite</strong> (or better: create custom later) → Gives GetSecretValue, DescribeSecret, etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KieUhDFGy4CWQbmJiExTMg.png" /></figure><p>2. <strong>SQS access</strong></p><ul><li>Search: sqs</li><li>Select: <strong>AmazonSQSFullAccess</strong> → Gives full access (SendMessage, ReceiveMessage, DeleteMessage, etc.)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Ut1IybUW0RX6yOQ4oQdQw.png" /></figure><p><strong>3. Optional but strongly recommended</strong> (for modern EC2 management):</p><ul><li>Search: ssm</li><li>Select: <strong>AmazonSSMManagedInstanceCore</strong> → Allows Session Manager (SSH-less access to private EC2), CloudWatch logs, etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-9hNro1DNsp8vX3PjtVUA.png" /></figure><h4>Step 3: Name, review, and create</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D4aBV57mV_DH93CqjwOitA.png" /></figure><h3>Task 4: Create Amazon SQS Queue for Asynchronous Decoupling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B4vUcVoZwcrB_jRPt0PvuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BT8peKui1Yl4lpvbb-Vhbw.png" /></figure><h3>Task 5: Create Amazon RDS MySQL Database</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rQBvNhbp5VmkROGe2MbSqA.png" /></figure><h4>Step 1: Choose creation method</h4><ul><li><strong>Engine type</strong>: MySQL</li><li><strong>Edition</strong>: MySQL Community</li><li><strong>Engine version</strong>: MySQL 8.0.x or 8.4.x (choose latest supported, e.g., 8.0.39 or 8.4.7)</li><li><strong>Template</strong>: Dev/Test</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*64R66AcJd07PnKL4BAWB4w.png" /></figure><h4>Step 2: Availability &amp; durability</h4><ul><li><strong>Multi-AZ deployment</strong>: <strong>Multi-AZ DB instance deployment</strong> (creates primary + standby in separate AZs)</li><li>Provides 99.95%+ uptime and automatic failover</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q5zW_IIPHKzVq5vyCS48Ng.png" /></figure><h4>Step 3: Settings</h4><ul><li><strong>DB instance identifier</strong>: database-1 (or myapp-db-prod — unique name)</li></ul><p><strong>Credentials management</strong>:</p><ul><li>Select <strong>Self managed</strong> (for simplicity in dev)</li><li><strong>Master username</strong>: admin (or custom)</li><li><strong>Master password</strong>: Create a strong password (at least 8 characters, no / * @ symbols)</li><li><strong>Confirm password</strong>: Re-enter</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tuJbH4M9XK9e48yFDDJE0Q.png" /></figure><h4>Step 4: Connectivity</h4><ul><li><strong>Virtual private cloud (VPC)</strong>: Select your VPC</li><li><strong>Subnet group</strong>: <strong>Create new DB Subnet Group</strong> (or select existing)</li><li>Name: myapp-db-subnet-group</li><li>Add your 2 isolated DB subnets (db-isolated-us-east-1a, db-isolated-us-east-1b)</li><li><strong>Public access</strong>: <strong>No</strong> (private only — correct choice)</li><li><strong>VPC security group (firewall)</strong>: Choose existing → Select <strong>RDS-SG</strong></li><li>This ensures only Application-SG (EC2) can connect on port 3306</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVqZwWFH9pW8a9BVtU-_DA.png" /></figure><h4>Step 5: Additional configuration</h4><ul><li><strong>Initial database name</strong>: levelup</li><li><strong>DB parameter group</strong>: default.mysql8.0 (or custom if needed)</li><li><strong>Option group</strong>: default:mysql-8–0</li></ul><p><strong>Backup</strong>:</p><ul><li>Enable automated backup: Checked</li><li>Backup retention period: 7 days (default good)</li><li>Backup window: No preference (or choose)</li></ul><p><strong>Monitoring</strong>:</p><ul><li>Enhanced Monitoring: Enable if needed (extra cost)</li><li>Performance Insights: Enable (very useful for dev)</li></ul><p><strong>Deletion protection</strong>: Enable (prevents accidental delete)</p><p><strong>Tags</strong> (optional): Add Project: MyProject, Environment: Dev</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SzdaDp6JhXmyo-qSsrthsA.png" /></figure><h4>Step 6: Review and launch</h4><ul><li>Review all settings (especially VPC, subnets, SG, Multi-AZ, private access)</li><li>Click <strong>Create database</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNmChqKPNOhCYWndqGtAdA.png" /></figure><h4>Step 7: Wait &amp; Verify</h4><p>Creation takes 5–15 minutes (status changes from “Creating” → “Available”)</p><p>Once available:</p><ul><li>Go to RDS → Databases → Select database-1</li><li>Copy <strong>Endpoint</strong> (e.g., database-1.xxxxx.us-east-1.rds.amazonaws.com)</li></ul><h3>Task 6: Create Secret in AWS Secrets Manager for RDS Credentials</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JOS1u9wyUXJ40vEcdKsdMA.png" /></figure><h4>Step 1: Choose secret type</h4><p>Secret type: Select Credentials for Amazon RDS database (This pre-fills the correct structure and integrates with RDS)</p><h4>Step 2: Credentials</h4><ul><li><strong>User name</strong>: admin (or whatever master username you set in RDS)</li><li><strong>Password</strong>: Enter the strong password you created for RDS (or the one RDS auto-generated if you used that option)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dMsQNEz5aIdNhhEnCAzOMA.png" /></figure><h4>Step 3: Encryption key</h4><ul><li><strong>Encryption key</strong>: Select <strong>aws/secretsmanager</strong> (default AWS-managed key)</li></ul><h4>Step 4: Database (link to RDS)</h4><ul><li>Search and select your RDS instance: database-1 (This associates the secret with your DB for easier rotation later)</li></ul><h4>Step 5: Secret name and description</h4><ul><li><strong>Secret name</strong>: prodsecretkey (or better: myapp/rds/credentials — use path-like naming) → Case-sensitive, alphanumeric + /-_@ allowed</li><li><strong>Description</strong> (optional but recommended): “RDS MySQL credentials for PHP application (EC2 role access). Username: admin”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kv9WpIxGUp0LYaYkKCe-Zw.png" /></figure><h4>Step 6: Review and store</h4><ul><li>Review all settings (type, credentials, RDS link, name, encryption)</li><li>Click <strong>Store</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xh_NB5-_iW3WCNZlxzSvyg.png" /></figure><h3>Task 7: Create EC2 Launch Template</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLVgb16U6-qHnl9fm96iIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iP-5X3p8rlbPREhO4M0eZA.png" /></figure><h4>Step 1: Launch Template Name and Description</h4><ul><li><strong>Launch template name</strong>: prodtemplate (required, unique, max 128 chars)</li><li><strong>Template version description</strong>: “Production template for PHP application EC2 instances (with IAM role, Application-SG, and user data setup)”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRiO_MU7QmZMHHohHFhvTw.png" /></figure><h4>Step 2: Application and OS Images (AMI)</h4><ul><li>Search and select: <strong>Amazon Linux 2023 AMI</strong> (recommended for PHP apps — lightweight, secure, free tier eligible)</li><li>Example AMI ID from your screenshot: ami-0c1fe2f8a7de7c7a1 (Amazon Linux 2023)</li><li>Quick Start → Amazon Linux → Select latest</li></ul><h4>Step 3: Instance Type</h4><ul><li><strong>Instance type</strong>: t3.micro (free tier eligible, good for dev/testing)</li><li>(Upgrade to t3.small or m7g.medium for production)</li></ul><h4>Step 4: Key pair (login)</h4><ul><li><strong>Key pair name</strong>: Select or create one (e.g., my-key-pair) — needed for SSH access (optional if using Session Manager)</li></ul><h4>Step 5: Network settings</h4><ul><li><strong>Firewall (security groups)</strong>: Select <strong>Application-SG</strong> (the one you created earlier for EC2)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*83d_ZxeIII4wnYMdXelzlQ.png" /></figure><h4>Step 6: Configure storage</h4><p><strong>Volumes</strong>:</p><ul><li>1 volume — 8 GiB gp3 (general purpose SSD)</li><li>Delete on termination: Checked (default)</li></ul><h4>Step 7: Advanced details</h4><ul><li><strong>IAM instance profile</strong>: Select your EC2 role → ec2role (from Task 3) → This allows instances to access Secrets Manager and SQS</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apOyv6LEHuvTFgw7Mhx2WA.png" /></figure><ul><li><strong>User data </strong>: Copy and Paste your startup script</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*ZO7ZEhpQbV-LhdroVKmTTQ.png" /></figure><pre>#!/bin/bash<br>set -e<br><br>sudo dnf update -y<br><br>sudo dnf install -y httpd php php-mysqlnd git unzip mariadb105<br><br>sudo systemctl enable --now httpd<br><br>cd /var/www/html<br>sudo rm -rf *<br>sudo git clone https://github.com/raj1552/Joystick-Store.git .<br>sudo rm -rf .git<br><br>cd /tmp<br>curl -sS https://getcomposer.org/installer -o composer-setup.php<br>sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer<br><br>cd /var/www/html<br>sudo tee /var/www/html/composer.json &gt;/dev/null &lt;&lt; &#39;EOF&#39;<br>{<br>  &quot;name&quot;: &quot;joystick-store/app&quot;,<br>  &quot;require&quot;: {<br>    &quot;php&quot;: &quot;&gt;=7.4&quot;,<br>    &quot;aws/aws-sdk-php&quot;: &quot;^3.0&quot;,<br>    &quot;vlucas/phpdotenv&quot;: &quot;^5.5&quot;<br>  }<br>}<br>EOF<br>sudo composer install --no-dev<br><br>sudo tee /var/www/html/.env &gt;/dev/null &lt;&lt; &#39;ENV_EOF&#39;<br>AWS_SECRET_NAME=&lt;SECRET_NAME&gt;<br>AWS_REGION=&lt;REGION&gt;<br>SQS_QUEUE_URL=&lt;SQS_URL&gt;<br>ENV_EOF<br><br>sudo mkdir -p /certs<br>sudo curl -L https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem \<br>-o /certs/global-bundle.pem<br><br>sudo chown -R apache:apache /var/www/html<br>sudo chmod -R 755 /var/www/html<br><br>echo &quot;Importing database...&quot;<br><br>export MYSQL_PWD=&quot;&lt;DB_PASSWORD&gt;&quot;<br><br>mysql -h &lt;DB-Endpoint&gt; \<br>  -P 3306 \<br>  -u admin \<br>  --ssl \<br>  --ssl-ca=/certs/global-bundle.pem &lt;&lt; &#39;SQL_EOF&#39;<br>CREATE DATABASE IF NOT EXISTS levelup;<br>USE levelup;<br>SOURCE /var/www/html/levelup.sql;<br>SQL_EOF<br><br>sudo systemctl restart httpd<br><br>echo &quot;Deployment completed successfully&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OrjHiuxor78c16IclAPlew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S7VCEQH2DFaflLWE_QjLVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBdLAgIpc98n39lr1RTd1A.png" /></figure><h3>Task 8: Create Application Load Balancer (ALB)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KCE1KKNXdXhR8JM-K7J7dw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwWMDMmB2AXPhLRCewe-TA.png" /></figure><h4>Step 1: Basic configuration</h4><ul><li><strong>Load balancer name</strong>: Application-LB (unique, max 32 chars, alphanumeric + hyphens)</li><li><strong>Scheme</strong>: <strong>Internet-facing</strong> (Serves public internet traffic via public IPs/DNS)</li><li><strong>IP address type</strong>: <strong>IPv4</strong> (Standard choice; Dualstack if you need IPv6)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L12m5dPnCj8nyKq8YVJkHA.png" /></figure><h4>Step 2: Network mapping</h4><ul><li><strong>VPC</strong>: Select your VPC</li></ul><p><strong>Availability Zones &amp; Subnets</strong>:</p><ul><li>Select <strong>at least two AZs</strong> (us-east-1a and us-east-1b recommended)</li><li>For each AZ, choose a <strong>public subnet</strong>:</li><li>us-east-1a → My Project-subnet-public1-us-east-1a</li><li>us-east-1b → My Project-subnet-public2-us-east-1b</li><li>ALB nodes will be placed in these public subnets for internet access</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fXrnvkZJTvntsc3eocS5zg.png" /></figure><h4>Security groups</h4><ul><li><strong>Security groups</strong>: Select <strong>ALB-SG</strong> (the public-facing SG you created earlier) → Allows inbound HTTP (80) and HTTPS (443) from anywhere (0.0.0.0/0)</li></ul><h4>Listeners and routing</h4><ul><li><strong>Listeners</strong>:</li><li>Add listener: <strong>HTTP</strong> → Port <strong>80</strong></li><li>(Optional but recommended): Add <strong>HTTPS</strong> → Port <strong>443</strong> later (requires ACM certificate)</li><li><strong>Default action</strong> for HTTP:80 listener:</li><li><strong>Forward to target groups</strong> → Click <strong>Create target group</strong> (see below)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TwaTYFqlhcQMWPmxZxM4kg.png" /></figure><h4>Create Target Group (critical step)</h4><ol><li><strong>Target type</strong>: <strong>Instances</strong> (Best for EC2 / Auto Scaling Group)</li><li><strong>Target group name</strong>: ALB-Target (unique per region)</li><li><strong>Protocol</strong>: <strong>HTTP</strong></li><li><strong>Port</strong>: <strong>80</strong> (or 8080 if your PHP app listens on non-standard port)</li><li><strong>VPC</strong>: Your VPC</li><li><strong>Health checks</strong>:</li></ol><ul><li><strong>Protocol</strong>: HTTP</li><li><strong>Path</strong>: /index.php (or /health, / — whatever endpoint returns 200 OK when healthy)</li><li><strong>Success codes</strong>: 200–399 (default good)</li><li><strong>Advanced settings</strong>: Leave defaults (interval 30s, timeout 5s, healthy threshold 5, unhealthy 2)</li></ul><p>7. Click <strong>Next</strong> → <strong>Create target group</strong></p><p>8. Back in ALB creation:</p><ul><li>Select the new target group ALB-Target</li><li>Weight: 1, Percent: 100% (default)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QIqO2JY5l2LPg5aahxoVEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tsreTqXiYa9skJ4HGeJ6WA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5Klo-DjfGvx5sRQQ0VNVQ.png" /></figure><h4>Summary &amp; Create</h4><ul><li>Review:</li><li>Internet-facing</li><li>Public subnets in 2 AZs</li><li>ALB-SG</li><li>Listener HTTP:80 → Forward to ALB-Target</li><li>Target group health check path: /index.php</li><li>Click <strong>Create load balancer</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sr9eLRPAqHWn8PlPyMnK2A.png" /></figure><h3>Task 9: Create Auto Scaling Group (ASG)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*thILYSOzyVbfdjt8mOrF0Q.png" /></figure><h4>Step 1: Choose launch template or configuration</h4><ul><li><strong>Auto Scaling group name</strong>: Productionautoscaling</li><li><strong>Launch template</strong>: Select prodtemplate</li><li><strong>Version</strong>: Default (1)</li><li>Click <strong>Next</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jLRZR7eacZB9etaZfbmEIw.png" /></figure><h4>Step 2: Choose instance launch options</h4><p><strong>Network</strong>:</p><ul><li>VPC: Your VPC</li></ul><p>Availability Zones &amp; subnets: Select your <strong>private application subnets</strong>:</p><ul><li>us-east-1a → subnet in AZ1</li><li>us-east-1b → subnet in AZ2</li><li><strong>Availability Zone distribution</strong>: <strong>Balanced best effort</strong> (default — good)</li><li>Click <strong>Next</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RrJLypoqfiMPCsx11dx4Vw.png" /></figure><h4>Step 3: Integrate with other services (Load Balancing)</h4><ul><li><strong>Load balancing</strong>: <strong>Attach to an existing load balancer</strong></li><li><strong>Choose from your load balancer target groups</strong>: Select ALB-Target (HTTP 80)</li></ul><p><strong>Health checks</strong>:</p><ul><li>EC2 health checks: <strong>Always enabled</strong></li><li>Turn on <strong>Elastic Load Balancing health checks</strong>: Checked (Recommended)</li><li><strong>Health check grace period</strong>: 300 seconds (gives instances time to boot and pass ALB health check)</li><li>Leave VPC Lattice and Zonal shift off (not needed yet)</li><li>Click <strong>Next</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJJwwQExX6VF5bSIIgFQqA.png" /></figure><h4>Step 4: Configure group size and scaling</h4><p><strong>Group size</strong>:</p><ul><li>Desired capacity: <strong>1</strong></li><li>Min desired capacity: <strong>1</strong></li><li>Max desired capacity: <strong>2</strong></li></ul><p><strong>Scaling</strong>:</p><ul><li>Select <strong>Target tracking scaling policy</strong></li><li>Scaling policy name: CPU-Target-Tracking-60</li><li>Metric type: <strong>Average CPU utilization</strong></li><li>Target value: <strong>60</strong></li><li>Instance warmup: <strong>300</strong> seconds (leave default if already set)</li><li>Disable scale-in: <strong>leave unchecked</strong></li><li>Click <strong>Next</strong> → proceed to review → <strong>Create Auto Scaling group</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iOwj105JPa5af-Aa6hdHgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2EHce9oTcLuOfNbPWvO1Zg.png" /></figure><h4>Step 5–7: Notifications, tags, review</h4><ul><li><strong>Notifications</strong>: Skip (add CloudWatch alarms later if needed)</li><li><strong>Tags</strong>: Optional — add e.g. Project: MyProject, Environment: Production</li><li>Review everything → Click <strong>Create Auto Scaling group</strong></li></ul><h4>After Creation: Verify &amp; Monitor</h4><ol><li><strong>Status check</strong>:</li></ol><ul><li>Go to <strong>Auto Scaling Groups</strong> → Select Productionautoscaling</li><li>Wait 3–10 minutes → Desired capacity = 1, Instances = 1, Status = InService</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JqIRqxeakIYgdwCGPC700A.png" /></figure><p><strong>2. Check instances</strong>:</p><ul><li>EC2 Dashboard → Instances → You should see 1 new instance launched from prodtemplate</li><li>It should be in <strong>running</strong> state and registered in target group</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2_qrOBTGrG6SwgQZoymDw.png" /></figure><p><strong>3. Target group health</strong>:</p><ul><li>EC2 → Target Groups → ALB-Target → Targets tab</li><li>Your instance should show <strong>healthy</strong> (after health check passes)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NfRSt0PCEkj3XGfKVZFkDQ.png" /></figure><p><strong>4. View CloudWatch Metrics (ASG &amp; Instance Monitoring)</strong></p><ul><li>From the ASG detail page (<strong>Productionautoscaling</strong>):</li><li>Go to <strong>Monitoring</strong> tab</li></ul><p>You’ll see built-in graphs for:</p><ul><li><strong>GroupMinSize</strong></li><li><strong>GroupMaxSize</strong></li><li><strong>GroupDesiredCapacity</strong></li><li><strong>GroupInServiceInstances</strong> (should be 1)</li><li>Click <strong>View all CloudWatch metrics</strong> (link/button in the monitoring section) → This opens CloudWatch with ASG-specific views</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qRWm0bd4n79YRyDgJ-eECg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*de_qEUFyKfNiZBRE-8QigQ.png" /></figure><p><strong>4. Test the full flow</strong>:</p><ul><li>Open browser → Go to ALB DNS name (from Task 8): Application-LB-…us-east-1.elb.amazonaws.com</li><li>You should see your PHP application (assuming code is deployed via user data or manually)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UF6JvgpZ2NckAQdEcM9OHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UF6JvgpZ2NckAQdEcM9OHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHcKBi616PvEOqzCYyNlxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8NNn93NEtDHrcKkWBjrNw.png" /></figure><h3>Task 9: Checking Logs on Launched ASG Instance</h3><p>Connect to the EC2 instance launched by your Auto Scaling Group (ASG) using AWS Systems Manager (SSM) Session Manager and inspect key logs to troubleshoot issues (e.g., user data script failures, web server errors, or application deployment problems). This is optional but essential for debugging why the application might not be responding (like the duplicate foreign key errors from your SQL import).</p><p><strong>Prerequisites</strong></p><ul><li>Instance must be running .</li><li>Your EC2 IAM role (ec2role) must include the <strong>AmazonSSMManagedInstanceCore</strong> policy (for SSM access). If not, add it via IAM → Roles → ec2role → Add permissions → Search for “SSMManagedInstanceCore” → Attach.</li><li>Your AWS user/role must have ssm:StartSession permission (usually included in admin roles).</li></ul><p>If Session Manager fails, fall back to SSH (but SSM is preferred for private instances</p><h4>Step 1: Locate the Instance in the Console</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2_qrOBTGrG6SwgQZoymDw.png" /></figure><h4>Step 2: Connect Using Session Manager</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FImJjaTec_zTmzmFsifnMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bsqXi8wkl4Gnh4NxZcATog.png" /></figure><h4>Step 3: Run Commands to Check Logs (Inside the Terminal)</h4><pre>sudo cat /var/log/cloud-init-output.log</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7y7qZ7HKPUW6246xb1dYgQ.png" /></figure><h3>Conclusion</h3><p>Congratulations! You’ve now built a complete, production-ready 3-tier web application architecture on AWS from the ground up. Starting with a secure VPC foundation, we layered in robust security groups, IAM roles for credential management, asynchronous decoupling with SQS, a highly available Multi-AZ RDS database, and dynamic scaling through Auto Scaling Groups integrated with an Application Load Balancer. Along the way, we incorporated best practices like Secrets Manager for secure credential handling and CloudWatch for monitoring ensuring your PHP (or any web) application is scalable, resilient, and cost-effective.</p><p>This setup isn’t just theoretical; it’s a blueprint that handles real-world demands: automatic scaling during traffic spikes, failover across Availability Zones, and zero hard-coded secrets. Whether you’re deploying a simple e-commerce site like our Joystick Store example or a complex enterprise app, this architecture provides the flexibility to grow without downtime.</p><p>As you deploy your own code and go live, remember to monitor costs (e.g., via AWS Cost Explorer), add HTTPS with ACM certificates, and implement CI/CD pipelines with CodePipeline for automated deployments. Experiment, iterate, and scale AWS makes it easier than ever.</p><p>If you found this guide helpful, give it a clap, share your thoughts in the comments, or follow for more AWS deep dives. Happy building!</p><p>— Anuraj Shrestha</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d2cfef46eef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[npm install vs npm ci: What’s the Real Difference?]]></title>
            <link>https://medium.com/@anurajshrestha75/npm-install-vs-npm-ci-whats-the-real-difference-b0e3d1e3c634?source=rss-bdccad9a5613------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0e3d1e3c634</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[npm]]></category>
            <dc:creator><![CDATA[Anurajshrestha]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 16:47:51 GMT</pubDate>
            <atom:updated>2026-01-21T16:47:51.586Z</atom:updated>
            <content:encoded><![CDATA[<h3>npm install vs npm ci: What’s the Real Difference?</h3><p>Node.js projects depend heavily on third‑party packages. As projects grow, the way you install those dependencies starts to matter a lot more than most people expect. Two commands that often look interchangeable are npm install and npm ci. They are not the same, and choosing the wrong one can lead to slow builds, broken pipelines, and hard‑to‑debug production issues.</p><p>This guide breaks down what each command actually does, how they differ, and when you should use one over the other, especially in CI/CD and Docker workflows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eeUkZYjwMQa_c9SoZC5PCg.png" /></figure><h4>Why This Matters</h4><p>Modern applications can pull in hundreds of dependencies. If dependency installation behaves differently across environments, you can easily run into:</p><ul><li>Inconsistent builds between local, CI, and production</li><li>Unexpected bugs caused by version drift</li><li>Failing CI/CD pipelines</li><li>Broken Docker images</li><li>Security and compliance concerns</li></ul><p>Understanding npm install vs npm ci helps you keep builds predictable and repeatable.</p><h3>What Is npm install?</h3><p>npm install is the default command most developers start with. It is designed primarily for development workflows.</p><h4>What it does</h4><ul><li>Reads package.json</li><li>Resolves compatible dependency versions</li><li>Installs dependencies into node_modules</li><li>Creates or updates package-lock.json</li><li>Adds new packages when used with flags like npm install express</li></ul><h4>Typical use cases</h4><ul><li>Local development</li><li>Adding or upgrading dependencies</li><li>Experimenting with new libraries</li><li>Early‑stage projects where strict reproducibility is not critical</li></ul><h4>Example</h4><pre>npm install</pre><p>Adding a new dependency:</p><pre>npm install express</pre><p>This updates:</p><ul><li>node_modules/</li><li>package.json</li><li>package-lock.json</li></ul><h4>The downside</h4><p>npm install does not guarantee identical dependency versions across machines. Even small version changes can introduce subtle bugs or break builds.</p><h3>What Is npm ci?</h3><p>npm ci stands for <strong>Continuous Integration</strong>. It is built specifically for automated and production‑like environments.</p><h4>What it does</h4><ul><li>Reads only package-lock.json</li><li>Verifies that package.json and the lock file are in sync</li><li>Deletes the existing node_modules directory</li><li>Installs exact dependency versions from the lock file</li></ul><p>If the lock file is missing or out of sync, the command fails on purpose.</p><h4>Key benefits</h4><ul><li>Faster installs</li><li>Fully reproducible builds</li><li>No version drift</li><li>Clean, predictable environments</li><li>Ideal for immutable infrastructure</li></ul><h4>Typical use cases</h4><ul><li>CI/CD pipelines</li><li>Docker image builds</li><li>Automated testing</li><li>Production deployments</li></ul><h4>Example</h4><pre>npm ci</pre><h4>npm install vs npm ci: Side‑by‑Side</h4><p>Featurenpm installnpm ciUses package.jsonYesNoUses package-lock.jsonYesYes (required)Updates lock fileYesNoDeletes node_modulesNoYesInstalls exact versionsNot guaranteedAlwaysSpeedSlowerFasterBest forLocal developmentCI/CD &amp; production</p><h3>Real‑World Docker Example</h3><h4>Not recommended</h4><pre>COPY package*.json ./<br>RUN npm install</pre><p>This can produce different images over time, even with the same source code.</p><h4>Best practice</h4><pre>COPY package*.json ./<br>RUN npm ci --only=production</pre><p>Benefits:</p><ul><li>Predictable Docker builds</li><li>Better layer caching</li><li>Smaller and more reliable images</li></ul><h3>CI/CD Pipeline Example</h3><h4>GitHub Actions</h4><pre>steps:<br>  - uses: actions/checkout@v4<br>  - name: Install dependencies<br>    run: npm ci</pre><p>Why this works better:</p><ul><li>Faster pipelines</li><li>Clean installs every run</li><li>No hidden dependency changes</li></ul><h4>Jenkins</h4><pre>pipeline {<br>  agent any <br><br>stages {<br>    stage(&#39;Install dependencies&#39;) {<br>      steps {<br>        sh &#39;npm ci&#39;<br>      }<br>    }<br>  }<br>}<br>```yaml<br>- script: npm ci<br>  displayName: Install dependencies</pre><h3>A Common Problem npm ci Solves</h3><p><strong>Scenario</strong></p><p>A developer runs npm install locally, which updates package-lock.json. The change is not committed. CI continues using older cached dependencies, and the app behaves differently in production.</p><p><strong>Solution</strong></p><p>Using npm ci ensures:</p><ul><li>CI always installs exactly what is committed</li><li>Local changes only apply after the lock file is updated</li><li>No surprises across environments</li></ul><h3>Understanding Version Drift</h3><p>Consider this dependency:</p><pre>&quot;dependencies&quot;: {<br>  &quot;axios&quot;: &quot;^1.6.0&quot;<br>}</pre><p>The caret (^) allows newer minor versions.</p><ul><li>Today: installs 1.6.0</li><li>Tomorrow: installs 1.7.3</li></ul><p>With npm install, you may get different versions over time.</p><p>With npm ci, the exact version from package-lock.json is always installed.</p><h3>Performance Difference</h3><p>npm ci is faster because it:</p><ul><li>Skips dependency resolution</li><li>Installs known versions directly</li><li>Avoids lock file updates</li></ul><p>This speed difference becomes very noticeable in CI pipelines and Docker builds.</p><h3>When Should You Use Each?</h3><h4>Use npm install when:</h4><ul><li>Developing locally</li><li>Adding or updating dependencies</li><li>Prototyping features</li><li>Exploring new libraries</li></ul><h4>Use npm ci when:</h4><ul><li>Running CI/CD pipelines</li><li>Building Docker images</li><li>Deploying to production</li><li>Running automated tests</li></ul><h3>Final Takeaway</h3><p>If you remember one thing:</p><ul><li>npm install is for <strong>development and change</strong></li><li>npm ci is for <strong>consistency and automation</strong></li></ul><p>Using the right command at the right time will save you hours of debugging and make your builds far more reliable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0e3d1e3c634" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Lambda Image Compressor]]></title>
            <link>https://medium.com/@anurajshrestha75/aws-lambda-image-compressor-c6722cf06ee3?source=rss-bdccad9a5613------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6722cf06ee3</guid>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[image-compressor]]></category>
            <dc:creator><![CDATA[Anurajshrestha]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 15:15:37 GMT</pubDate>
            <atom:updated>2026-01-21T15:16:21.720Z</atom:updated>
            <content:encoded><![CDATA[<p>This project implements a simple, serverless <strong>automatic image compression pipeline</strong> using <strong>AWS Lambda</strong> and <strong>Amazon S3</strong>.</p><p>The goal is to reduce storage costs, speed up website loading times, and optimize bandwidth usage by automatically compressing images as soon as they are uploaded without any manual intervention or dedicated servers.</p><h4><strong>Core Workflow</strong></h4><ol><li>A user uploads an original image to a specific folder/prefix in an S3 bucket: uploads/.</li><li>S3 detects the new object creation event and triggers the <strong>Image Compressor Lambda</strong> function via an <strong>S3 event notification</strong>.</li><li>The Lambda function:</li></ol><ul><li>Downloads the image from S3.</li><li>Processes it (resizes if too large, reduces quality/compression using Pillow library).</li><li>Uploads the smaller, optimized version to another prefix in the same bucket: compressed-image/ (or a separate bucket if preferred).</li></ul><p>The compressed image is now ready for use (e.g., in a website, app, or CDN).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*haFvWMbqT1jrMde2cULukg.png" /></figure><h3>Task 1: Setting Up S3 Bucket</h3><h4>Step 1: Create a S3 bucket</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rtXzbCGOC4UA0-wXkXmF-A.png" /></figure><h4>Task 2: Create Folder Structure in S3 Buckets</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aly3WxszaDq6Sb0VERNWQA.png" /></figure><ul><li>Click <strong>Create folder</strong> (or use the prefix directly when uploading).</li><li>Create these two folders/prefixes:</li><li>uploads/ → For all <strong>original / raw images</strong> that users upload (input location).</li><li>compressed/ → For all <strong>compressed / processed images</strong> that the Lambda function generates (output location).</li></ul><h3>Task 2: Setting up Lambda Function</h3><h4>Step 1: Create a Lambda Function</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cR7nM1JbGATM7WepDkaC-A.png" /></figure><h4>Step 2: Choose Existing role (Lambda-run-role)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QUroZKnCQoKDPtkxT4sRzg.png" /></figure><h3>Task 3: Configure S3 Trigger to Invoke Lambda on New Uploads</h3><h4>Step 1: Create a Event Notification on S3</h4><ul><li>Go to <strong>AWS S3 console</strong> → Your Bucket → Select your compressed bucket → <strong>Properties</strong> tab.</li><li>Scroll to <strong>Event notifications</strong> → Click <strong>Create event notification</strong>.</li><li>Enter a <strong>Name</strong> (e.g., CompressOnUpload).</li><li>Under <strong>Events</strong>, select <strong>Put</strong>.</li><li>Under <strong>Filter</strong>:</li><li><strong>Prefix</strong>: uploads/</li><li><strong>Suffix</strong>: (.jpg)</li><li>Under <strong>Destination</strong>, choose <strong>Lambda function</strong> → Select your function from the dropdown.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lVbCFO8CcWk73eyquGImvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C2AQFBEQhhnCCF1eoCKB2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vEPEsNm9LkCRcTVjy32kpQ.png" /></figure><h4>Step 2: Verify the S3 Trigger and Automatic Permissions on Lambda</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iKwb175RR6fDD-m44qil_A.png" /></figure><h3>Task 4: Upload the Lambda Handler Code — Handle S3 Event &amp; Compress Images</h3><h4>Task 1: Copy the Code Snippet to Lambda &amp; Deploy It</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_PfsIR97n_OMmoB-2M62CQ.png" /></figure><h4><strong><em>Code Snippet</em></strong></h4><pre>import boto3<br>import os<br>from PIL import Image<br>from io import BytesIO<br>s3 = boto3.client(&quot;s3&quot;)<br><br>MAX_SIZE_KB = 400<br>MAX_SIZE_BYTES = MAX_SIZE_KB * 1024<br>def lambda_handler(event, context):<br>    bucket = event[&quot;Records&quot;][0][&quot;s3&quot;][&quot;bucket&quot;][&quot;name&quot;]<br>    key = event[&quot;Records&quot;][0][&quot;s3&quot;][&quot;object&quot;][&quot;key&quot;]<br>    # Skip already compressed files<br>    if key.startswith(&quot;compressed-image/&quot;):<br>        return {&quot;status&quot;: &quot;skipped&quot;}<br>    # Only process JPEG files<br>    if not key.lower().endswith((&quot;.jpg&quot;, &quot;.jpeg&quot;)):<br>        return {&quot;status&quot;: &quot;not-a-jpeg&quot;}<br>    # Download image from S3<br>    response = s3.get_object(Bucket=bucket, Key=key)<br>    image_bytes = response[&quot;Body&quot;].read()<br>    image = Image.open(BytesIO(image_bytes)).convert(&quot;RGB&quot;)<br>    # Resize large images first<br>    image.thumbnail((2000, 2000))  # optional, prevents huge files<br>    # Compress iteratively to reach ≤ 400 KB<br>    quality = 85<br>    buffer = BytesIO()<br>    while quality &gt;= 30:<br>        buffer.seek(0)<br>        buffer.truncate(0)<br>        image.save(buffer, format=&quot;JPEG&quot;, quality=quality, optimize=True)<br>        if buffer.tell() &lt;= MAX_SIZE_BYTES:<br>            break<br>        quality -= 5<br>    # Create output key<br>    filename = os.path.splitext(os.path.basename(key))[0]<br>    output_key = f&quot;compressed-image/{filename}-400kb.jpg&quot;<br>    buffer.seek(0)<br>    # Upload compressed image back to S3<br>    s3.put_object(<br>        Bucket=bucket,<br>        Key=output_key,<br>        Body=buffer,<br>        ContentType=&quot;image/jpeg&quot;<br>    )<br>    return {<br>        &quot;status&quot;: &quot;success&quot;,<br>        &quot;size_kb&quot;: round(buffer.tell() / 1024, 2),<br>        &quot;output&quot;: output_key<br>    }</pre><h4>Task 2: Add a Layer to Make the Code Work (Fixes PIL Import Error)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_F_FS2HOon1dgZ2_LsTsHw.png" /></figure><h3>Task 3: Add Layer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PvA-Z1EJbkZlJDGvuog_Iw.png" /></figure><ul><li>In the <strong>Add layer</strong> screen (as shown in screenshot):</li><li>Select : <strong>Specify an ARN</strong></li><li>Paste ARN:</li><li>arn:aws:lambda:us-east-1:770693421928:layer:Klayers-p310-Pillow:13</li><li>Click <strong>Verify</strong> it should show:</li><li>Description with Pillow version (e.g. Pillow==10.x or similar)</li><li>Compatible runtimes: Python 3.10</li><li>Compatible architectures: x86_64</li><li>If Verify succeeds → Click <strong>Add</strong>.</li></ul><h3>Task 5: Testing</h3><h4>Step 1: Upload Image “.jpg” on S3 bucket upload/</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OVfQxlHOn41QH2wUc-wC7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9E2IjVYb8jEI0L78bKwIKQ.png" /></figure><h4>Step 2: Verify Composed image on S3 composed-image/</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dS-N5OAZuaSiS0ucpEICXw.png" /></figure><h4>Step 3: Verify Execution Using CloudWatch Logs</h4><h4>Why CloudWatch Logs?</h4><p>AWS Lambda automatically sends logs here for every invocation (success or failure). It may take 5–30 seconds (sometimes up to a few minutes) for logs to appear after an upload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7t9KtN7cuKr_LqLboYbyoQ.png" /></figure><ul><li>Go to <strong>AWS Lambda console</strong> → Functions → Select your function (image-compressor-function).</li><li>Click the <strong>Monitor</strong> tab (top menu).</li><li>Click <strong>View CloudWatch logs</strong> — this opens CloudWatch directly in context.</li><li>Alternatively: Scroll down to <strong>Logs</strong> section → Click <strong>View in CloudWatch</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Cdt6oBfgJIFoBMtR8WQ8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JAG6QEgtISsGMNUfTyP4SQ.png" /></figure><h3>Conclusion</h3><p>This is a classic example of <strong>event-driven serverless architecture</strong> on AWS:</p><ul><li><strong>No servers</strong> to manage or scale Lambda handles concurrency automatically (can process thousands of images in parallel if needed).</li><li><strong>Fully automated </strong>upload once, compression happens instantly and reliably.</li><li><strong>Cost-effective </strong>you pay only for actual processing time (often &lt;$0.01 per 1,000 images) + cheap S3 storage.</li><li><strong>Extensible </strong>easy to add features later, like generating thumbnails, converting formats (e.g., to WebP/AVIF), adding watermarks, or sending notifications on failure.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6722cf06ee3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>