<?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 Shubham Pokhrel on Medium]]></title>
        <description><![CDATA[Stories by Shubham Pokhrel on Medium]]></description>
        <link>https://medium.com/@shubham-pokhrel?source=rss-e55c0fe11673------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_WkYT60beRsqETirvYT6-g.png</url>
            <title>Stories by Shubham Pokhrel on Medium</title>
            <link>https://medium.com/@shubham-pokhrel?source=rss-e55c0fe11673------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 00:39:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shubham-pokhrel/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[Container Engineering: Multi-Service Apps to AWS]]></title>
            <link>https://shubham-pokhrel.medium.com/container-engineering-multi-service-apps-to-aws-07629270235f?source=rss-e55c0fe11673------2</link>
            <guid isPermaLink="false">https://medium.com/p/07629270235f</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-ecs]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Shubham Pokhrel]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 05:13:33 GMT</pubDate>
            <atom:updated>2026-06-03T05:13:33.029Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A technical walkthrough of taking a real multi-service app: React + Express + Postgres from your laptop to a public, auto-scaling endpoint on Amazon ECS Express Mode.</em></p><p><strong>&gt; The full, copy-pasteable step-by-step guide lives in the repo:</strong></p><p>&gt; 👉 <a href="https://github.com/shubham-pokhrel/container-engineering"><strong>github.com/shubham-pokhrel/container-engineering</strong></a></p><p>We’ve all said it: <strong>”It works on my machine.”</strong> The interesting engineering question isn’t <em>how to run my app: it’s how to run my app, plus its three friends, in a way that survives being left on my machine.</em> That’s the whole job: a frontend, an API, and a database that have to find each other, start in the right order, keep their data, and end up behind a public URL without me hand-wiring a load balancer.</p><p>This post spends most of our time on the part people actually get stuck on: <strong>getting a containerized multi-service app onto AWS, behind HTTPS, with health checks and zero hand-built infrastructure.</strong></p><p>The demo app is a ride service: a <strong>React (Vite) frontend</strong>, an <strong>Express API</strong>, and <strong>Postgres</strong>. Small enough to read in one sitting, realistic enough to hit every problem that matters.</p><h3><strong>1. One container is easy. Three is where it gets real.</strong></h3><p>A single service is a solved problem. A Dockerfile freezes your app <em>and its environment</em> into an image; a container is that image running.</p><pre># dockerfile<br>FROM node:20-alpine<br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm install<br>COPY . .<br>EXPOSE 4000<br>CMD [&quot;node&quot;, &quot;server.js&quot;]</pre><pre>docker build -t rides-api ./api<br>docker run -p 4000:4000 rides-api</pre><p>Each instruction is a cached layer, -p maps host → container ports, and the same image runs identically on your Mac, a CI runner, or a Fargate task. Done.</p><p>The trouble starts at service #2. Run Postgres and the API as separate docker run commands and point the API atDB_HOST=localhost, and it fails instantly:</p><blockquote>DB not ready (attempt 1/8) host=localhost: ECONNREFUSED</blockquote><p>Inside the API container, localhost means <strong>the container itself</strong> — not your machine, not the database container. They’re isolated. The “<strong>fix</strong>” people reach for is grabbing the DB’s container IP by hand:</p><pre>docker inspect db | grep IPAddress<br># 172.17.0.2 … until the next restart</pre><blockquote>That IP changes every restart. Multiply this by env vars, restart policies, log rotation, startup ordering, and a third service, and you’ve built a fragile shell script that only you can run. The honest takeaway from the live demo: <strong>look how much you typed for just two services.</strong> There has to be a better way.</blockquote><h3><strong>2. Compose is the contract</strong></h3><p>Docker Compose turns that pile of flags into one declarative file. The four things in it that matter for production are the four things that make the AWS step trivial later.</p><pre>services:<br>frontend:<br>build: ./frontend<br>ports: [&quot;3000:3000&quot;]<br>depends_on: [api]<br>networks: [frontend-net]<br>api:<br>build: ./api<br>ports: [&quot;4000:4000&quot;]<br>environment:<br>DB_HOST: db # ← a service NAME, not localhost, not an IP<br>DB_USER: postgres<br>DB_PASSWORD: secret<br>DB_NAME: rides<br>depends_on:<br>db:<br>condition: service_healthy # ← wait until DB is READY, not just started<br>networks: [frontend-net, backend-net]<br>db:<br>image: postgres:15<br>environment:<br>POSTGRES_PASSWORD: secret<br>POSTGRES_DB: rides<br>volumes:<br>- pgdata:/var/lib/postgresql/data # named volume -&gt; data survives restarts<br>healthcheck:<br>test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U postgres&quot;]<br>interval: 5s<br>timeout: 5s<br>retries: 5<br>networks: [backend-net] # db is ONLY on backend-net -&gt; frontend can&#39;t reach it<br>volumes:<br>pgdata:<br>networks:<br>frontend-net:<br>backend-net:</pre><pre>docker compose up # all three, wired together, one command</pre><p><strong>1. Service discovery. </strong>Compose creates a network and registers each service by name. DB_HOST:db Just works: no IPs, no inspect. This is the single biggest reason Compose exists, and it’s the same idea AWS gives you with internal DNS later.</p><p><strong>2. </strong><strong>depends_on + health checks — the technique to internalize.</strong> depends_on <em>without</em> a condition simply waits for the container to start, not for it to be ready. Postgres starts in a second but takes a few seconds to accept connections; thus the API begins, attempts to connect, and dies in a fail-fast app. The fix is a genuine health check (pg_ready) additional condition: service_healthy</p><p><strong>Hold onto this idea “<em>ready, not started</em>” is exactly how AWS decides whether your deploy succeeded.</strong></p><p><strong>3. Named volumes.</strong> pgdata: is Docker-managed storage that outlives the container. docker compose down keeps your data; down -v deletes it. Code goes in the image; “<em>state”</em> goes in a volume.</p><p><strong>4. Network isolation. </strong>Putting db only on backend-net means the frontend physically cannot reach the database, it has to go through the API. Defense in depth, and the same mental model as private subnets in a VPC.</p><p>That’s the foundation. Everything from here is moving these exact concepts to AWS.</p><h3><strong>3. The bridge to AWS: image → registry → managed runtime</strong></h3><p>The whole cloud step is three moves:</p><p>1. <strong>Build</strong> an image for the cloud’s CPU architecture.</p><p>2. <strong>Push</strong> it to a registry AWS can pull from (ECR).</p><p>3. <strong>Run</strong> it on a managed runtime that hands you a URL: here, <strong>Amazon ECS Express Mode</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*98uILx0p-eYZqJ6GlrHaLA.png" /><figcaption>Amazon Elastic Container Service: Clusters</figcaption></figure><p>No load balancer to configure, no VPC to draw, no Kubernetes manifests. Let’s do each move and, more importantly, understand what each one is actually doing.</p><p><strong>3.1 Build for the right CPU — the #1 silent failure</strong></p><p>Most laptops today are ARM (Apple Silicon). AWS Fargate runs <strong>linux/amd64</strong>. Build on ARM, push, and your task crash-loops with an exec-format error that <em>looks</em> like a code bug and isn’t. Always build explicitly for the target:</p><pre>docker build - platform linux/amd64 -t rides-api ./api</pre><p>Every build script in the repo pins -platform linux/amd64for exactly this reason. If you remember one operational detail from this whole post, make it this one.</p><p><strong>3.2 ECR: Docker Hub with IAM</strong></p><p>Elastic Container Registry is a private image registry with AWS IAM as its auth layer. You log Docker into it with a short-lived token, then push like any other registry:</p><pre># create the repo (one-time)<br>aws ecr create-repository - repository-name rides-api - region us-east-1<br># authenticate Docker to ECR (token is valid ~12h)<br>aws ecr get-login-password - region us-east-1 \<br>| docker login - username AWS - password-stdin &lt;account&gt;.dkr.ecr.us-east-1.amazonaws.com<br># tag with the full ECR URI, then push<br>docker tag rides-api:latest &lt;account&gt;.dkr.ecr.us-east-1.amazonaws.com/rides-api:latest<br>docker push &lt;account&gt;.dkr.ecr.us-east-1.amazonaws.com/rides-api:latest</pre><p>In the repo, this is two scripts: aws/01-create-infra.sh (creates the repo) and aws/02-first-push.sh(builds for amd64, tags, pushes the first image so the runtime has something to point at).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DqQ0yv65tsEeULnEOEE_6A.png" /><figcaption>ECR Repositories</figcaption></figure><p><strong>3.3 ECS Express Mode: a container in, a URL out</strong></p><p>This is the part that used to mean a day of YAML. <strong>ECS Express Mode</strong> takes a single move: “here’s an image and a port” and provisions the boring-but-critical infrastructure <em>for</em> you:</p><ul><li>an Application Load Balancer + target group,</li><li>security groups,</li><li>auto-scaling,</li><li>CloudWatch logs, and</li><li>a <strong>public HTTPS URL</strong> https://&lt;id&gt;.ecs.&lt;region&gt;.on.aws</li></ul><p>Your container runs on <strong>Fargate: </strong>no EC2 instances to patch or scale. The one-time setup creates two IAM roles (a task <strong>execution role</strong> so ECS can pull from ECR and write logs, and an <strong>infrastructure role</strong> so Express can manage the ALB/networking on your behalf), the ECS service-linked role, and the Express service itself:</p><pre>aws ecs create-express-gateway-service \<br> - service-name rides-api-express \<br> - execution-role-arn &lt;execRoleArn&gt; \<br> - infrastructure-role-arn &lt;infraRoleArn&gt; \<br> - health-check-path /health \<br> - primary-container &#39;{&quot;image&quot;:&quot;&lt;ecr-uri&gt;/rides-api:latest&quot;,&quot;containerPort&quot;:4000}&#39; \<br> - cpu 256 - memory 512 \<br> - region us-east-1</pre><p>In the repo, that’s one idempotent script, aws/05-ecs-express-setup.sh(it even retries while the new IAM roles propagate, roles are eventually consistent, and a fresh role often can’t be assumed for a few seconds). A couple of minutes later the ALB is up, the first task is healthy, and you have a live URL.</p><p><strong>3.4 The deploy model: immutable tags, explicit rollout</strong></p><p>Here’s a subtlety worth internalizing, because it’s different from “push and it magically redeploys.” <strong>ECS Express does not redeploy on an ECR push.</strong> A deploy is two explicit steps:</p><p>1. Push the image under a <strong>unique, immutable tag</strong> (a timestamp works great).</p><p>2. <strong>Update the service</strong> to point at that tag, which triggers a fresh rollout.</p><pre>TAG=&quot;v$(date +%Y%m%d-%H%M%S)&quot; # unique tag -&gt; guaranteed new rollout<br>docker build - platform linux/amd64 -t rides-api:$TAG ./api<br>docker tag rides-api:$TAG &lt;ecr-uri&gt;/rides-api:$TAG<br>docker push &lt;ecr-uri&gt;/rides-api:$TAG<br># re-use the running container&#39;s config, swap ONLY the image tag<br>aws ecs update-express-gateway-service \<br> - service-arn &lt;serviceArn&gt; \<br> - primary-container &#39;{… &quot;image&quot;:&quot;&lt;ecr-uri&gt;/rides-api:&#39;$TAG&#39;&quot; …}&#39; \<br> - region us-east-1</pre><p>Why unique tags instead of reusing :latest? Three reasons, all of which matter the day something breaks:</p><ul><li><strong>Determinism: </strong>the service points at one specific, content-addressable build. No “which latest is actually running right now?”</li><li><strong>Guaranteed rollout</strong>: a new tag is unambiguously a new revision, so the rollout always happens.</li><li><strong>Rollback: </strong>every previous build is still in ECR under its own tag; rolling back is just pointing the service at an older one.</li></ul><p>This is exactly what aws/03-deploy.sh does: it builds, pushes a timestamped tag (and :latestfor convenience), reads the service’s current container config, swaps in only the new image, and updates the service.</p><p><strong>3.5 Health checks decide whether your deploy succeeded</strong></p><p>Remember “ready, not started” from Compose? AWS makes the same decision, with money on the line. Route traffic to a new task only after it passes the health check at/health, and don’t tear down the old task until the new one is healthy. That’s a rolling, <strong>zero-downtime</strong> deploy you didn’t have to design.</p><p>This is also why the API exposes lightweight routes that don’t depend on the database:</p><pre>app.get(&#39;/&#39;, (req, res) =&gt; res.json({ service: &#39;rides-api&#39;, version: VERSION, status: &#39;ok&#39; }));<br>app.get(&#39;/health&#39;, (req, res) =&gt; res.json({ status: &#39;healthy&#39; }));<br>app.get(&#39;/rides&#39;, async (req, res) =&gt; { /* needs Postgres */ });</pre><p>/ and /health answer instantly with no DB, so the service stays healthy on AWS even though we didn’t deploy Postgres there. /rides returns a 503 until a database is attached, which is the honest, expected state for a demo (attach an <strong>RDS Postgres</strong> and set DB_HOST/ DB_PASSWORDand /rides lights up too). <strong>Lesson: your health-check endpoint must not depend on things that can legitimately be down.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*4RDE5BdtPVv5of4EG7d6PQ.png" /><figcaption>Health Endpoint Verification</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*0WL1Np0cS8exlrkFSPzoiA.png" /><figcaption>Database connection unavailable</figcaption></figure><p><strong>3.6 The proof: a live deploy you can watch</strong></p><p>The most convincing moment is the smallest one. The API carries a visible marker:</p><pre>const VERSION = &#39;v1&#39;; // bump to &#39;v2&#39; and ship</pre><p>Bump it, run ./aws/03-deploy.sh, watch the ECS console roll the new task out (~1–2 min), then refresh the URL version flips from v1 to v2. Same image that ran on your laptop ten minutes ago, now behind HTTPS with auto-scaling, and you configured none of the plumbing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*Ol29TTnoU8TD6iShIKCaJQ.png" /><figcaption>Version Update to v2</figcaption></figure><p><strong>3.7 It bills while it runs: tear it down</strong></p><p>The ALB and Fargate task cost money idle. When you’re done, delete the Express service, the ECR repo (with images), and the two IAM roles from the ECS/ECR/IAM consoles or via the CLI. The repo’s guide has the exact commands.</p><h3><strong>4. What transfers, and where to go next</strong></h3><p>Notice what <em>didn’t</em> change between your laptop and AWS: the Dockerfile, the image, the health-check endpoint, the env-var contract, the “ready, not started” discipline. <strong>Only the last hop changed.</strong> That’s the real point of the talk; the hard, transferable skills are the container ones; the cloud runtime is the easy part you can swap.</p><p>From here, the same skills scale up:</p><ul><li><strong>Full multi-service stack in the cloud:</strong> keep the API on ECS, add <strong>RDS Postgres</strong> for state, and /ridesworks end-to-end.</li><li><strong>More control: g</strong>raduate to a standard <strong>ECS on Fargate</strong> service for fine-grained networking, sidecars, and multiple containers per service.</li><li><strong>Clusters: EKS (Kubernetes) </strong>when you genuinely need multi-host orchestration. Most teams get 80% of the value from ECS for 20% of the complexity.</li></ul><h3><strong>Try it yourself</strong></h3><p>Everything here is runnable. The repo has the app, the Compose files, and one script per step:</p><p>👉<a href="https://github.com/shubham-pokhrel/container-engineering"><strong>github.com/shubham-pokhrel/container-engineering</strong></a></p><p>Start with the <a href="https://github.com/shubham-pokhrel/container-engineering/blob/main/STEP-BY-STEP.md"><strong>step-by-step guide</strong></a><strong>: </strong>run the local demos ( demos/01… 06), then the AWS scripts in order (aws/01 → 02 → 05 → 03) to put your own container behind a public URL.</p><p>If this was useful, I’d love to connect; Questions and corrections welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07629270235f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Time-Series Forecasting Workflow on AWS]]></title>
            <link>https://shubham-pokhrel.medium.com/building-a-time-series-forecasting-workflow-on-aws-8a925fcb3cf8?source=rss-e55c0fe11673------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a925fcb3cf8</guid>
            <category><![CDATA[aws-forecast]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Shubham Pokhrel]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 13:10:47 GMT</pubDate>
            <atom:updated>2026-01-21T18:03:03.862Z</atom:updated>
            <content:encoded><![CDATA[<p>In Amazon Forecast, the first thing I noticed was how much heavy lifting it removes from time-series forecasting. Before, teams had to build servers and train models by themselves. Now, most of the work is just cleaning and preparing past data. AWS does the hard machine-learning part for you. When demand is easy to predict, people can plan instead of panicking when usage suddenly goes up. This helps teams avoid last-minute problems and work in a calmer, smarter way.</p><p>My project was a learning experiment in a simple retail scenario: forecasting the daily sales of a single product. I used a single time series (sales per day) without extra related features, primarily to see how well Forecast would perform on <em>real sales data</em> as a first pass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*rD_HTlmUOxoQ9GnQ42SJzQ.png" /><figcaption>“actual vs. predicted” time-series chart</figcaption></figure><p><strong>Preparing My Time-Series Data</strong></p><p>The first big step was data preparation. Forecast needs the data in a strict format, so I had to clean and reshape my history carefully. My raw file was a CSV with dates and sales numbers. I fixed it in Python using pandas: filled in missing days, fixed bad date formats, and removed weird spikes.</p><p>One small mistake can break everything. For example, I found a bad date like 2019010 instead of 2019–01–01. If that slips through, Forecast will reject the whole file.</p><p>The final CSV had to follow Forecast’s exact rules:<br>• one column for time<br>• one column for item ID<br>• one column for the value you want to predict (sales)</p><p>Since I had only one product, I used the same item ID for every row (e.g., SKU123). Then I uploaded the clean file to S3 so Forecast could read it.</p><pre>{ &quot;DataFrequency&quot;: &quot;D&quot;, <br>  &quot;Domain&quot;: &quot;CUSTOM&quot;, <br>  &quot;DatasetType&quot;: &quot;TARGET_TIME_SERIES&quot;, <br>  &quot;Schema&quot;: { <br>    &quot;Attributes&quot;: [<br>      {&quot;AttributeName&quot;: &quot;timestamp&quot;, &quot;AttributeType&quot;: &quot;timestamp&quot;},<br>      {&quot;AttributeName&quot;: &quot;target_value&quot;, &quot;AttributeType&quot;: &quot;float&quot;},<br>      {&quot;AttributeName&quot;: &quot;item_id&quot;, &quot;AttributeType&quot;: &quot;string&quot;}<br>    ]<br>  }<br>}</pre><p>Next, I created a Forecast <strong>dataset group</strong> and a <strong>target time-series dataset</strong> inside it. I defined the dataset with frequency “D” (daily) and the necessary schema. Then, I kicked off a dataset import job to load the CSV from S3 into Forecast. I quickly learned about Forecast’s asynchronous behavior — the import takes time, and you must wait or poll the job status. A frequent issue I encountered was that Forecast expects the CSV to be sorted by timestamp; fixing this was essential to complete the import and make the data ready for modeling.</p><p><strong>Training Predictors and Generating Forecasts</strong></p><p>With data in place, the next step was <strong>training a predictor</strong> (the forecasting model) and using it to produce forecasts. Amazon Forecast offers both automated model selection and the option to choose specific algorithms. I experimented with both. I first used <strong>AutoML</strong> (the default), which parallel-runs multiple algorithms (DeepAR+, CNN-QR, Prophet, ARIMA, etc.) to select the most accurate one. Separately, I manually ran experiments with built-in models like ARIMA and a Prophet-like model for comparison.</p><p>Training is compute-intensive and costly. Forecast runs multiple instances in parallel to train candidates, with AWS charging about <strong>$0.24 per training-hour</strong> (per instance-hour). The billed hours can exceed the wall-clock time due to this parallelism. For my small dataset, training was quick, but for a larger, longer-horizon project, costs would need careful monitoring. AWS prices are per GB of data imported and per training hour, with no minimum fees.</p><p>After monitoring the predictor training (which splits the data into training and validation windows for evaluation), I created a forecast. I set the <strong>forecast horizon</strong> (e.g., 14 days ahead). The output consisted of two main components:</p><ul><li><strong>Backtest metrics:</strong> Accuracy metrics like RMSE and MAPE, testing the model against historical data. My overall MAPE was around 20%, indicating non-trivial data noise and variability.</li><li><strong>Forecast file:</strong> Predicted values for each future day. Crucially, Forecast provides <strong>quantiles</strong> (default 10%, 50%, 90%) to gauge uncertainty. The median (50%) is the point forecast, while the intervals signal the range of probable outcomes. I observed that my model was sometimes overconfident, with actual sales falling outside the 10–90% band.</li></ul><p>A visual comparison of the actual vs. predicted values confirmed that the general trend was captured, but sudden spikes were often underpredicted. This manual check served as a good sanity test; however, in a production environment, this check would need to be automated.</p><h3><strong>What I learned from doing this by hand:</strong></h3><p>Going through the full process showed me what really matters for good forecasts:</p><ul><li>Data quality is king. The cleanliness of the input data significantly impacts accuracy. Mistakes, gaps, or outliers (like a day recorded twice) lead to poor forecasts. Before modeling, good plots and statistical checks (mean, variance, null counts) are essential to ensure the time series is sound.</li><li>Feature engineering helps, but I kept it simple. I intentionally excluded additional related time series (price, weather, holidays) in this learning test. Forecast supports adding such categorical or related data, which would likely improve accuracy in a real-world demand planning project.</li><li>Automation vs. clicking in the console. Initially, I used the Forecast console, but the manual process of starting import jobs, waiting, and then starting training quickly became tedious. I realized the critical value of automating the workflow. AWS guides orchestration via Step Functions or scripts. I ended up scripting the sequence using the AWS SDK (boto3) to make the pipeline reproducible.</li><li>Interpreting results takes judgment. The forecast output is not a silver bullet. I had to interpret the results, especially checking the 10% and 90% prediction bands to understand risk and uncertainty. A wide band (e.g., 90% forecast 30% higher than 50%) suggested high uncertainty, prompting a need for more data or features. Deciding which error metric (like RMSE vs. MAPE) to trust also required domain judgment.</li></ul><p><strong>Architecture of My Forecasting Pipeline</strong></p><p>The final workflow resembled a mini data pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9SFoRHZrL6ZVEmxBMfSog.png" /></figure><ul><li><strong>Storage (S3):</strong> All raw and intermediate data was stored in Amazon S3. Forecast ingests data from S3, and the resulting forecast CSVs are exported back to S3. S3 acts as the central storage layer.</li><li><strong>Dataset Management (Forecast APIs):</strong> I used the AWS CLI or SDK to call Forecast APIs to create the dataset group, define the schema, and import data from S3. This aligns with AWS guidance, where an S3 event can trigger a workflow using <em>CreateDataset</em>, <em>CreateDatasetImportJob</em>, and <em>CreatePredictor</em> APIs.</li><li><strong>Model Training (Forecast):</strong> Training runs in the cloud, fully managed by Forecast. I used either the console or CreatePredictor API calls. After training, CreateForecast generated the future predictions, which produced forecast files and backtest metrics in S3.</li><li><strong>Orchestration (Step Functions / Automation):</strong> To keep everything running without me constantly babysitting it, I used AWS Step Functions to tie the steps together. Basically, whenever a new file lands in S3, an EventBridge rule kicks off the workflow. Step Functions handles each step in order, including waiting or checking until Forecast finishes its work. I could have done it all in a single Python script, but Step Functions makes it easier to track and fix things if something goes wrong.</li><li><strong>Outputs:</strong> The forecast results land in an S3 bucket. From there, anyone can open them in QuickSight or Athena to see the numbers. Sometimes we push the data to DynamoDB using Lambda. In real life, these numbers usually feed dashboards or alert systems so teams can quickly spot problems or surprises without waiting for a report.</li><li><strong>In Production:</strong> In a real setup, this runs on a schedule — maybe every night or weekly. EventBridge triggers the jobs automatically. The model gets retrained every month or sooner if the data changes a lot; otherwise, it slowly becomes useless. CloudWatch monitors errors and tracks whether forecasts are drifting. The key idea is simple: automate it, retrain often, and constantly check so it doesn’t silently break.</li></ul><p><strong>Challenges, Surprises, and What I’d Do Differently</strong></p><p>My hands-on experiment involved a few bumps:</p><ul><li><strong>Tricky Errors at First:</strong> Initial errors often stemmed from misconfigured dataset schemas, such as forgetting the item_id column or mixing up date formats. These were frustrating to debug. The lesson was to carefully read error logs and validate the CSV against the exact schema before importing.</li><li><strong>Asynchronous Waits:</strong> Forecast’s API calls (createDatasetImportJob, createPredictor) are asynchronous. I learned that inserting Wait states, polling, or using Step Functions is necessary to manage the sequential flow, as calling the next step too soon leads to failure.</li><li><strong>Model Performance:</strong> The AutoML-selected model was decent, but a surprising issue was seasonality. My data had a clear weekly cycle (higher on weekends) that was not explicitly flagged. While the model picked it up, a custom Prophet setting showed the weekly pattern more cleanly. I learned that picking the right frequency and forecast horizon is as important as the algorithm. Predicting too far out with little data led to obviously worse errors.</li><li><strong>Cost vs. Speed:</strong> Training was resource-intensive. Accidental duplicate predictor launches added to the bill, emphasizing the need to clean up unused predictors and track training hours. For large-scale forecasts, starting small and using the AWS Pricing Calculator is advised.</li></ul><p><strong>Recommendations</strong></p><p>For engineers or analysts building a similar workflow on AWS, here are my practical takeaways:</p><ul><li><strong>Start Small and Clean:</strong> Begin with a single, high-quality time series to master the process. A simple chart can quickly highlight data issues like gaps or incorrect timestamps.</li><li><strong>Use the AWS Console Then Automate:</strong> Use the console for the initial learning experiment, but quickly move to automation. AWS Step Functions or a simple script should orchestrate the CreateDataset, CreatePredictor, and CreateForecast steps to ensure repeatability and reduce manual errors.</li><li><strong>Mind the Horizon and Frequency:</strong> Carefully choose the data frequency (daily or hourly) and the forecast horizon, ensuring they are logically aligned.</li><li><strong>Use AutoML, but don’t trust it blindly:</strong> AutoML is a good starting point. It gets you something decent fast. But I still tested ARIMA and Prophet-style models to see how they behave. And I always checked the upper/lower ranges, not just the main line, because that’s where the risk lives.</li><li><strong>Productionize Carefully:</strong> Implement a schedule (e.g., nightly via EventBridge) for regular forecast updates. Schedule retraining cycles for when new data is available or model accuracy begins to drift. Use least-privilege IAM roles and automate monitoring of accuracy versus actuals.</li><li><strong>Watch Your Costs:</strong> Track training hours and data volume, as Forecast charges per GB ingested and per training-hour. Batching multiple time series into a single predictor (up to 100k items) can help manage costs.</li></ul><p>My experience with AWS Forecast was a valuable engineering learning experiment. It showed that a full ML forecasting solution is powerful and accessible with focused data preparation and AWS API calls. For any team considering it, <strong>getting your hands dirty</strong> with a small dataset is the best way to quickly understand what works in your specific context. Forecasting capability is essential for planning, and tools like AWS Forecast democratize it for small teams.</p><p>My experience with AWS Forecast was a valuable engineering learning experiment. It showed that a full ML forecasting solution is powerful and accessible with focused data preparation and AWS API calls. For any team considering it, <strong>getting your hands dirty</strong> with a small dataset is the best way to quickly understand what works in your specific context. Forecasting capability is essential for planning, and tools like AWS Forecast democratize it for small teams.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a925fcb3cf8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless Image Moderation System with Amazon Rekognition]]></title>
            <link>https://shubham-pokhrel.medium.com/serverless-image-moderation-system-with-amazon-rekognition-cded795710e1?source=rss-e55c0fe11673------2</link>
            <guid isPermaLink="false">https://medium.com/p/cded795710e1</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[amazon-rekognition]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Shubham Pokhrel]]></dc:creator>
            <pubDate>Sat, 09 Aug 2025 22:43:35 GMT</pubDate>
            <atom:updated>2025-12-28T20:07:22.940Z</atom:updated>
            <content:encoded><![CDATA[<p>User-generated content is a liability before it’s an asset. The moment you allow image uploads, you inherit legal risk, moderation cost, and trust issues. Manual review doesn’t scale. Client-side validation can be bypassed in seconds. You need server-side, automated moderation that runs before content goes live.</p><p>In this post, I’ll show you how to build a production-ready, fully serverless image moderation pipeline using AWS services. No servers to manage, no infrastructure to maintain and costs that scale with usage.</p><h3>What We’re Building</h3><p>By the end of this guide, you’ll have a system that:</p><ul><li>Automatically analyzes every uploaded image</li><li>Blocks NSFW or unsafe content</li><li>Approves safe, relevant content</li><li>Blurs edge cases that need human review</li><li>Scales effortlessly with demand</li><li>Low costs for thousands of images</li></ul><h3>The Architecture</h3><p>We’re keeping the stack intentionally minimal.</p><p><strong>Amazon S3</strong> — Stores uploaded images and triggers the moderation workflow</p><p><strong>AWS Lambda</strong> — Runs moderation logic without managing infrastructure</p><p><strong>Amazon Rekognition</strong> — AI-powered content analysis with confidence scores</p><p><strong>Amazon SNS</strong> — Event-driven notifications to update the frontend in real-time</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9vFY9sEo8xfU0xphiDKKyg.png" /></figure><h3>The Flow</h3><ol><li>User uploads an image to your application</li><li>Image lands in a private S3 bucket (never public by default)</li><li>S3 event automatically triggers a Lambda function</li><li>Lambda sends the image to Amazon Rekognition for analysis</li><li>Rekognition returns moderation labels with confidence scores</li><li>Lambda applies decision logic: Block, Approve, or Blur</li><li>The result is tagged on the S3 object</li><li>Lambda publishes the result to an SNS topic</li><li>Web App receives the event via SNS subscription</li><li>UI fetches and displays the processed image</li></ol><p><strong>Key principle:</strong> Upload is decoupled from display. Event-driven architecture ensures zero polling, instant updates, and clean separation of concerns.</p><h3>Implementation Guide</h3><h3>Step 1: Create Your S3 Bucket</h3><p>Start with a single S3 bucket for image uploads:</p><pre>Bucket name: momo-verification<br>Block all public access: ✓ Enabled<br>Versioning: Optional</pre><h3>Step 2: Configure S3 Event Notifications</h3><p>Set up automatic triggering on upload:</p><ul><li>Event type: ObjectCreated (All)</li><li>Destination: Lambda function (we’ll create this next)</li><li>Optional suffix filter: .jpg, .png, .jpeg</li></ul><p>This ensures every upload is automatically routed to moderation.</p><h3>Step 3: Build the Lambda Function</h3><p>Create a new Lambda function with these settings:</p><ul><li><strong>Runtime:</strong> Python 3.11 or later</li><li><strong>Trigger:</strong> S3 bucket (momo-verification)</li><li><strong>Timeout:</strong> 30 seconds (Rekognition can take a few seconds)</li><li><strong>Memory:</strong> 512 MB (adequate for most images)</li></ul><p><strong>IAM Permissions Required:</strong></p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;rekognition:DetectModerationLabels&quot;,<br>        &quot;rekognition:DetectFaces&quot;,<br>        &quot;rekognition:DetectLabels&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;*&quot;<br>    },<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;s3:GetObject&quot;,<br>        &quot;s3:PutObjectTagging&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;arn:aws:s3:::momo-verification-*/*&quot;<br>    }<br>  ]<br>}</pre><h3>The Moderation Logic</h3><p>Here’s the complete Lambda function. It performs three layers of analysis:</p><pre>import boto3<br>import urllib.parse</pre><pre>s3 = boto3.client(&#39;s3&#39;)<br>rekognition = boto3.client(&#39;rekognition&#39;)</pre><pre>def lambda_handler(event, context):<br>    bucket = event[&#39;Records&#39;][0][&#39;s3&#39;][&#39;bucket&#39;][&#39;name&#39;]<br>    key = urllib.parse.unquote_plus(event[&#39;Records&#39;][0][&#39;s3&#39;][&#39;object&#39;][&#39;key&#39;])</pre><pre>    status = &quot;BLOCKED&quot;<br>    reason = &quot;UNKNOWN&quot;</pre><pre>    try:<br>        # 1. SAFETY CHECK (Adult / Unsafe)<br>        mod_res = rekognition.detect_moderation_labels(<br>            Image={&#39;S3Object&#39;: {&#39;Bucket&#39;: bucket, &#39;Name&#39;: key}}<br>        )</pre><pre>        if mod_res[&#39;ModerationLabels&#39;]:<br>            status = &quot;BLOCKED&quot;<br>            reason = &quot;UNSAFE_CONTENT&quot;</pre><pre>        else:<br>            # 2. HUMAN CHECK<br>            face_res = rekognition.detect_faces(<br>                Image={&#39;S3Object&#39;: {&#39;Bucket&#39;: bucket, &#39;Name&#39;: key}},<br>                Attributes=[&#39;DEFAULT&#39;]<br>            )</pre><pre>            if face_res[&#39;FaceDetails&#39;]:<br>                status = &quot;BLOCKED&quot;<br>                reason = &quot;HUMAN_DETECTED&quot;</pre><pre>            else:<br>                # 3. LABEL DETECTION<br>                lbl_res = rekognition.detect_labels(<br>                    Image={&#39;S3Object&#39;: {&#39;Bucket&#39;: bucket, &#39;Name&#39;: key}},<br>                    MaxLabels=20<br>                )</pre><pre>                labels = lbl_res[&#39;Labels&#39;]</pre><pre>                is_food = any(<br>                    l[&#39;Name&#39;] == &#39;Food&#39; and l[&#39;Confidence&#39;] &gt;= 80<br>                    for l in labels<br>                )</pre><pre>                is_momo = any(<br>                    l[&#39;Name&#39;] == &#39;Dumpling&#39; and l[&#39;Confidence&#39;] &gt;= 80<br>                    for l in labels<br>                )</pre><pre>                if not is_food:<br>                    status = &quot;BLOCKED&quot;<br>                    reason = &quot;NOT_FOOD&quot;</pre><pre>                elif is_momo:<br>                    status = &quot;APPROVED&quot;<br>                    reason = &quot;MOMO_DETECTED&quot;</pre><pre>                else:<br>                    status = &quot;BLURRED&quot;<br>                    reason = &quot;OTHER_FOOD&quot;</pre><pre>        # 4. TAG RESULT<br>        s3.put_object_tagging(<br>            Bucket=bucket,<br>            Key=key,<br>            Tagging={<br>                &#39;TagSet&#39;: [<br>                    {&#39;Key&#39;: &#39;status&#39;, &#39;Value&#39;: status},<br>                    {&#39;Key&#39;: &#39;reason&#39;, &#39;Value&#39;: reason}<br>                ]<br>            }<br>        )</pre><pre>        print(f&quot;{key} → {status} ({reason})&quot;)<br>        return {&quot;status&quot;: status, &quot;reason&quot;: reason}</pre><pre>    except Exception as e:<br>        print(e)<br>        return {&quot;status&quot;: &quot;ERROR&quot;, &quot;reason&quot;: &quot;LAMBDA_FAILURE&quot;}</pre><h3>How It Works</h3><p>The function performs three sequential checks:</p><p><strong>Safety Screening</strong> — Rekognition detect_moderation_labels catches NSFW content, violence, and other unsafe material. If anything is flagged, the image is immediately blocked.</p><p><strong>Human Detection</strong> — Using detect_faces, we identify if people appear in the image. Depending on your use case, you might want to block images with faces for privacy reasons.</p><p><strong>Content Classification</strong> — Finally, detect_labels returns detailed labels with confidence scores. You can customize this logic for your specific domain (e.g., only allowing food images, blocking weapons, filtering for products).</p><h3>Web App Integration</h3><p>Your web application should handle moderation gracefully:</p><h3>Upload Flow</h3><pre>// 1. Request presigned URL from your backend<br>const uploadUrl = await fetch(&#39;/api/get-upload-url&#39;).then(r =&gt; r.json());</pre><pre>// 2. Upload directly to S3<br>await fetch(uploadUrl, {<br>  method: &#39;PUT&#39;,<br>  body: imageFile,<br>  headers: { &#39;Content-Type&#39;: imageFile.type }<br>});</pre><pre>// 3. Show &quot;Processing...&quot; state<br>setStatus(&#39;processing&#39;);</pre><pre>// 4. Listen for SNS notification (via WebSocket/polling/SSE)<br>// When moderation completes, fetch the result</pre><h3>Display Logic</h3><pre>// Fetch image with status tags<br>const imageData = await fetch(`/api/images/${imageId}`);</pre><pre>switch(imageData.status) {<br>  case &#39;APPROVED&#39;:<br>    // Display image normally<br>    showImage(imageData.url);<br>    break;<br>  <br>  case &#39;BLURRED&#39;:<br>    // Apply CSS blur filter<br>    showImage(imageData.url, { filter: &#39;blur(20px)&#39; });<br>    // Optionally allow unblur after warning<br>    break;<br>  <br>  case &#39;BLOCKED&#39;:<br>    // Blocked content increased by 1<br>    break;<br>}</pre><p><strong>Principle:</strong> No moderation logic lives on the client side. The frontend is purely presentational.</p><h3>Demo Results</h3><p>Here’s what the system looks like in action:</p><ol><li>Approved Case:</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZLl_YgkApCM&amp;type=text%2Fhtml&amp;schema=google&amp;display_name=YouTube&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZLl_YgkApCM" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6348bad28695f6fe1c4de56ff947a5e/href">https://medium.com/media/e6348bad28695f6fe1c4de56ff947a5e/href</a></iframe><p>2. Blurred Case:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FRWYema7upAU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DRWYema7upAU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FRWYema7upAU%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b52391c0ce8590646afe7f5e07cabb4e/href">https://medium.com/media/b52391c0ce8590646afe7f5e07cabb4e/href</a></iframe><p>3. Blocked Case:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FnH9_uEzRWmA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DnH9_uEzRWmA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FnH9_uEzRWmA%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0741d38e6d1cb2e515a2347799cdaa2/href">https://medium.com/media/e0741d38e6d1cb2e515a2347799cdaa2/href</a></iframe><h3>Cost Analysis</h3><p>This architecture is remarkably cost-effective:</p><ul><li><strong>S3 Storage:</strong> $0.023 per GB/month</li><li><strong>Lambda:</strong> First 1M requests free, then $0.20 per 1M</li><li><strong>Rekognition:</strong> $1.00 per 1,000 images analyzed</li><li><strong>SNS:</strong> First 1M notifications free</li></ul><p><strong>Example:</strong> Processing 10,000 images per month costs approximately $10–15.</p><h3>Next Steps and Improvements</h3><p>Once you have the basic system running, consider these enhancements:</p><p><strong>Momo-Specific Custom Dataset: </strong>Create and train a dedicated Rekognition Custom Labels dataset for momo (instead of aliasing it as “dumpling”) to reduce false positives and ensure only authentic momo images are approved.</p><p><strong>Confidence Threshold Tuning: </strong>Adjust the confidence scores (currently set at 80%) based on your tolerance for false positives and negatives.</p><p><strong>Multi-Region Deployment: </strong>Deploy Lambda and S3 in multiple regions for global users.</p><p><strong>Human Review Queue: </strong>Route “BLURRED AND BLOCKED” images to a dashboard for manual review.</p><p><strong>Audit Logging: </strong>Send all moderation decisions to CloudWatch or a database for compliance tracking.</p><p><strong>Batch Processing: </strong>Add support for bulk uploads with SQS queues to handle traffic spikes.</p><h3>Conclusion</h3><p>We get automatic scaling, pay-per-use pricing, and zero infrastructure management. The system we built processes images in under 5 seconds, costs pennies per thousand images, and handles everything from a few uploads per day to millions per month.</p><h3>Built &amp; Presented By</h3><p><a href="https://www.linkedin.com/in/shubham-pokhrel/"><strong>Shubham Pokhrel</strong><br></a> DevOps Engineer | AWS Cloud Club Captain Cohort 3</p><p><a href="https://medium.com/@rishikeshgautam"><strong>Rishikesh Gautam</strong><br></a> AWS Community Builder (AI/ML Engineering)</p><p><em>Want to see the complete code? Check out the </em><a href="https://github.com/shubham-pokhrel/momoapproved"><em>GitHub repository</em></a><em> for the full implementation.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cded795710e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>