<?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 Ali Haydar on Medium]]></title>
        <description><![CDATA[Stories by Ali Haydar on Medium]]></description>
        <link>https://medium.com/@ali-haydar?source=rss-e2ba7ca4dbad------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ulnQcY9PCLzw4Fao_LVxdA.jpeg</url>
            <title>Stories by Ali Haydar on Medium</title>
            <link>https://medium.com/@ali-haydar?source=rss-e2ba7ca4dbad------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:11:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ali-haydar/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[Exploring the Inner Workings of SST Live Lambda]]></title>
            <link>https://ali-haydar.medium.com/exploring-the-inner-workings-of-sst-live-lambda-2139dbad9390?source=rss-e2ba7ca4dbad------2</link>
            <guid isPermaLink="false">https://medium.com/p/2139dbad9390</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Ali Haydar]]></dc:creator>
            <pubDate>Sun, 25 Feb 2024 06:06:25 GMT</pubDate>
            <atom:updated>2025-09-16T22:02:13.283Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>For more content like this, subscribe to my newsletter on Substack: </em><a href="https://techroom101.substack.com/">https://techroom101.substack.com/</a></blockquote><p>In the evolving world of serverless architecture, the developer experience is a commonly debated topic. In particular, the challenges associated with testing locally and obtaining a fast feedback loop.</p><p>Nowadays, we have a few technologies that make it convenient to develop serverless applications locally, enabling a swift integration between your local environment and the cloud (e.g. <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-sync.html">SAM Sync</a>, <a href="https://aws.amazon.com/blogs/developer/increasing-development-speed-with-cdk-watch/">CDK Watch</a> and <a href="https://docs.sst.dev/live-lambda-development">SST Live Lambda</a>).</p><p>In a previous <a href="https://ali-haydar.medium.com/exploring-local-development-with-sst-for-serverless-applications-0160f32de10f">article</a>, I demonstrated how to use the SST Live Lambda with a small project that uses a deployed endpoint in AWS API Gateway to invoke a locally developed Lambda.</p><p>I wanted to know how this works. Through this post, I aim to delve into the specifics of the underlying architecture of the SST Live Lambda functionality. For the official docs, you can find them <a href="https://docs.sst.dev/live-lambda-development#how-it-works">here</a>.</p><h3>Requests are proxied to the local machine</h3><p>SST docs state that the requests are proxied to the local machine, which allows SST to run the local version of the function with the event, context and credentials of the remote Lambda function. The communication between local and remote happens using <a href="https://docs.aws.amazon.com/iot/latest/developerguide/protocols.html">AWS IoT over WebSocket</a>.</p><p>Let’s check the details!</p><ul><li>Create a new SST project:</li></ul><pre>npx create-sst@latest<br>? Project name demo-sst<br>✔ Copied template files<br>Next steps:<br>- cd demo-sst<br>- npm install (or pnpm install, or yarn)<br>- npm run dev</pre><ul><li>Run npm installto install the dependencies</li><li>Update the stacks directory with the resources you&#39;d like to provision</li><li>Run npm run devto start the project</li></ul><p>Two things happen When you run npm run dev:</p><h4>SST creates a bootstrap stack in CloudFormation</h4><p>The stack creates resources needed in the deployment process of your app (more details <a href="https://docs.sst.dev/advanced/bootstrapping">here</a>).</p><p>Note that each app needs to be bootstrapped once, so this step won’t be needed the next time we run npm run dev.</p><p>As this article is focused on the Live Lambda, we will only focus on the bootstrap script a little. In summary, the following resources were created:</p><ul><li>An S3 bucket that stores critical information about the apps (e.g. prod/dev mode, the config needed to store secrets and variables, etc.).</li><li>A Lambda function that automatically deletes the S3 bucket objects when they are no longer needed</li><li>A lambda function that handles the collection and uploading of metadata to the S3 bucket</li><li>An EventBridge rule that triggers the MetadataHandler Lambda function</li></ul><h4>SST Deploys Your Application Resources</h4><p>SST deploys the application resources as defined in the stacks directory, enabling the usage of the Live Lambda feature.</p><p>Let’s look at some details beyond what’s mentioned in the SST documentation.</p><p>I deployed a simple stack that includes API Gateway and a Lambda function:</p><pre>import { StackContext, Api } from &#39;sst/constructs&#39;;<br><br>export function API({ stack }: StackContext) {<br>  const api = new Api(stack, &#39;api&#39;, {<br>    routes: {<br>    &#39;GET /&#39;: &#39;packages/functions/src/lambda.handler&#39;,<br>    },<br>  });<br><br>  stack.addOutputs({<br>    ApiEndpoint: api.url,<br>  });<br>}</pre><p>You can see the resources in CloudFormation and verify that the API Gateway and the Lambda function were created successfully.</p><p>First, the deployment will include all the resources defined in the stacksdirectory but will stub the lambda function by one defined by SST (not the real lambda function having your code). The diagram would look as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*Toh7To6Z_CE-lxq--2emFQ.png" /><figcaption>Live Lambda Stack Deployment</figcaption></figure><ul><li>The “Deployed Stack” is what you defined but with a stub lambda function</li><li>The AWS account is configured with a default IoT endpoint in each region. SST will use that endpoint based on the region configured sst.config.ts</li><li>SST starts a local WebSocket client and connects to that IoT endpoint.</li></ul><p>Once the stack is deployed, we’re outputting the API Gateway Endpoint that we can request. Send a GET request to this endpoint (e.g. curl https://ser55ggwrf.execute-api.us-east-1.amazon.com). Below is how the flow works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*QOlMw0XSdaxJ0wUHpZbfAg.png" /></figure><p>There are still more details to be discovered, especially on how the comms happen between the IoT endpoint and the stub Lambda, and the response relayed back to that Lambda.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2139dbad9390" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lambda to S3: Better Reliability in High-Volume Scenarios]]></title>
            <link>https://ali-haydar.medium.com/lambda-to-s3-better-reliability-in-high-volume-scenarios-3ee9a74a0539?source=rss-e2ba7ca4dbad------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ee9a74a0539</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Ali Haydar]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 04:55:46 GMT</pubDate>
            <atom:updated>2025-09-16T22:02:35.028Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>For more content like this, subscribe to my newsletter on Substack: </em><a href="https://techroom101.substack.com/">https://techroom101.substack.com/</a></blockquote><p>I have an API Gateway endpoint that routes requests to a lambda function that writes data into an S3 bucket.</p><p>In high-volume scenarios, when managing a significant influx of requests, there is an increased risk of failures when writing data to S3. This could be due to various factors such as network issues, S3 service disruptions, concurrent write conflicts, or exceeding capacity limits (Amazon S3 supports request rates of up to 3500 Put requests per second to a single prefix. In some scenarios, rapid concurrent Put requests to the same key can result in a 503 response.). Therefore, addressing and mitigating these potential failure points is essential to ensure the reliability of data writes to S3 in such situations.</p><p>An example where this might occur is having a webhook that hits your endpoint when a change happens in an external system. I’ve experienced this in tools such as Slack, Github, Jira, etc. Considering the large volume of data generated by these tools, using your endpoint frequently at a larger scale could pose challenges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NWgfY9ECHqvpRxvKhEUvYQ.jpeg" /><figcaption><a href="https://www.pexels.com/photo/red-steel-pipe-2420294/">Photo by Henry &amp; Co</a></figcaption></figure><p>Settle in with your favourite beverage as we’re about to explore some details together; this post is set to be a bit lengthier than usual.</p><h3><strong>Build the project</strong></h3><p>We will start by building a project with <a href="https://sst.dev/">SST</a> that provisions an API Gateway, a Lambda, and an S3 bucket. Once implemented, we’ll look into testing for concurrent write conflicts or exceeding capacity limits.</p><p>The architecture looks as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*CNflLO-Hd4ho1eBgTndkmg.png" /><figcaption>Architecture Diagram</figcaption></figure><p>Run the following to create the project locally:</p><pre>npx create-sst@latest<br>Ok to proceed? (y) y<br>? Project name s3-writes-reliability<br>✔ Copied template files<br>Next steps:<br>- cd s3-writes-reliability<br>- npm install (or pnpm install, or yarn)<br>- npm run dev</pre><p>Delete the unnecessary infrastructure under stacks and packages. The infrastructure lives under stacks and the actual Lambda code lives under packages.</p><p>Create the following stack:</p><pre>import { StackContext, Api, Bucket, Config } from &quot;sst/constructs&quot;;<br>import * as iam from &quot;aws-cdk-lib/aws-iam&quot;;<br><br>export function API({ stack }: StackContext) {<br>  const bucket = new Bucket(stack, &quot;Uploads&quot;);<br>  const api = new Api(stack, &quot;api&quot;, {<br>    routes: {<br>      &quot;POST /todo&quot;: &quot;packages/functions/src/lambda.handler&quot;,<br>    },<br>  });<br><br>  const BUCKET_NAME = new Config.Parameter(stack, &quot;BUCKET_NAME&quot;, {<br>    value: bucket.bucketName,<br>  });<br><br>  api.attachPermissions([<br>    new iam.PolicyStatement({<br>      actions: [<br>      &quot;s3:PutObject&quot;,<br>      &quot;s3:PutObjectAcl&quot;,<br>      &quot;s3:ListBucket&quot;,<br>      &quot;s3:GetObject&quot;,<br>      ],<br>      effect: iam.Effect.ALLOW,<br>      resources: [<br>      bucket.bucketArn + &quot;/*&quot;,<br>      ],<br>    }),<br>  ]);<br><br>  api.bindToRoute(&quot;POST /todo&quot;, [BUCKET_NAME, bucket]);<br><br>  stack.addOutputs({<br>    ApiEndpoint: api.url,<br>  });<br>}</pre><p>This stack will provision the API Gateway endpoint, the lambda function and the S3 bucket to which we will write.</p><p>Now let’s update the lambda function under packages/functions/src/lambda.ts:</p><pre>import { ApiHandler } from &quot;sst/node/api&quot;;<br>import { Config } from &quot;sst/node/config&quot;;<br>import { PutObjectCommand, S3Client } from &quot;@aws-sdk/client-s3&quot;;<br><br>const client = new S3Client({});<br><br>export const handler = ApiHandler(async (_evt) =&gt; {<br>  const params = {<br>    Body: _evt.body,<br>    Bucket: Config.BUCKET_NAME,<br>    Key: Math.random().toString(),<br>  };<br>  <br>  const response = await client.send(new PutObjectCommand(params));<br>  return {<br>    statusCode: 200,<br>    body: JSON.stringify(response)<br>  };<br>});</pre><p>We built an API endpoint that invokes a Lambda, which in turn puts an object in S3.</p><h3><strong>Deliberate Error Creation</strong></h3><p>We will explore the S3 Capacity limit (3500 requests/second), looking to hit that limit. This exercise’s purpose is to mirror real-life scenarios where a Lambda function might be invoked at scale, allowing us to explore the behaviour and performance of the system under heavy load.</p><p><strong>**First attempt — lambda making lots of requests — failed**</strong></p><p>To achieve this, I first tried to modify the Lambda function to simulate the generation of this significant volume of requests. I changed the lambda function to the following:</p><pre>import { ApiHandler } from &quot;sst/node/api&quot;;<br>import { Config } from &quot;sst/node/config&quot;;<br>import { PutObjectCommand, S3Client } from &quot;@aws-sdk/client-s3&quot;;<br><br>const client = new S3Client({});<br><br>async function uploadObject(key:any, data: any) {<br>  const params = {<br>    Bucket: Config.BUCKET_NAME,<br>    Key: key,<br>    Body: data<br>  };<br><br>  try {<br>    await client.send(new PutObjectCommand(params));<br>    console.log(`Successfully uploaded: ${key}`);<br>  } catch (error) {<br>    console.error(`Error uploading ${key}: ${error}`);<br>  }<br>}<br><br>export const handler = ApiHandler(async (_evt) =&gt; {<br>  try {<br>    const promises = [];<br>    for (let i = 1; i &lt;= 5000; i++) {<br>      promises.push(uploadObject(String(i), _evt.body));<br>    }<br>    await Promise.all(promises);<br>  } catch (error) {<br>    console.error(&quot;Unhandled error in handler:&quot;, error);<br>    return {<br>    statusCode: 500,<br>    body: JSON.stringify({ error: &quot;Internal Server Error&quot;, details: error.message }),<br>    };<br>  }<br>});</pre><p>Afterwards, I used curl to invoke the function (Change the API URL to point to the endpoint that SST outputted upon starting the project):</p><pre>curl -X POST -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;key1&quot;: &quot;value1&quot;, &quot;key2&quot;: &quot;value2&quot;}&#39; https://sdfsdfsdf.execute-api.ap-southeast-2.amazonaws.com/todo</pre><p>I didn’t get any 503 — Slow Down from S3, indicating that the number of requests is high — that’s because the script above won’t run within a single second.</p><p><strong>**Second attempt — loading the API endpoint — successful**</strong></p><p>The second attempt invokes the Lambda function with lots of simultaneous requests. This would spin up multiple Lambda instances to cater for the load, and each instance would hit S3 at the same time. Let’s see if that’ll work.</p><p>I’ll use <a href="https://jmeter.apache.org/">Apache JMeter</a> to do this experiment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8eSoxHziWHWNcoeWawx88w.png" /><figcaption>Jmeter Test</figcaption></figure><p>This test resulted in many errors related to the Lambda function being throttled due to exceeding the rate limit ”errorType”:”ThrottlingException”,”errorMessage”:”Rate exceeded”.</p><p>I’ve changed the Jmeter threads to 1000 to match the limit of 1000 concurrent executions allowed by Lambda in a single region. At the same time, I kept using promise.all in the Lambda code to achieve parallel requests to S3. With this combination, I managed to get a few SlowDown: Please reduce your request rate. errors.</p><p>Using Jmeter is a better approach to simulate a real case scenario, such as having a Slack or Github webhook that is hitting the endpoint.</p><h3><strong>Build a more reliable system</strong></h3><p>We managed to get the S3 service to return an error that we’re exceeding the rate limit. How can we build a more reliable architecture that would help us avoid this kind of error?</p><p>We have a few options here:</p><ul><li>Distribute objects across multiple S3 bucket prefixes as the rate limit is set by prefix (this means changing the behaviour of the application, which might not be something you’re planning to do)</li><li>Use a retry mechanism — this could be handled on the Lambda side, where we retry submitting requests that return a 503 error. This is a great solution, but it depends on your traffic and whether postponing the request would work. It’s worth testing this solution, especially since it doesn’t require a big effort.</li><li>Alleviate the load on S3 by introducing a queue between your APIGW and Lambda function. We’ll implement this solution.</li></ul><p>The architecture looks as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJ81f7TbhMxB0h7l7Yl71g.png" /><figcaption>Architecture Diagram with SQS</figcaption></figure><p>In this diagram, SQS serves as a buffer between APIGW and Lambda. Instead of directly processing incoming requests, we enqueue them in an SQS queue. This decouples the incoming request rate from the rate at which Lambda and S3 can process the requests, which smoothes out spikes in the incoming request rate, reducing the immediate load on S3 and providing a more controlled flow of data. If there are temporary issues with S3 or Lambda, messages can be retained in the SQS queue and retried, providing a more resilient system.</p><p>Let’s create this additional infrastructure. Modify the previously created stack as follows:</p><pre>const queue = new Queue(stack, &quot;Queue&quot;, {<br>  consumer: {<br>    function: {<br>      handler: &quot;packages/functions/src/lambda.handler&quot;,<br>      timeout:10,<br>      environment:{ BUCKET_NAME: bucket.bucketName },<br>    }<br>  }<br>});<br><br>queue.attachPermissions([<br>  new iam.PolicyStatement({<br>    actions: [<br>      &quot;s3:PutObject&quot;,<br>      &quot;s3:PutObjectAcl&quot;,<br>      &quot;s3:ListBucket&quot;,<br>      &quot;s3:GetObject&quot;,<br>    ],<br>    effect: iam.Effect.ALLOW,<br>    resources: [<br>      bucket.bucketArn + &quot;/*&quot;,<br>    ],<br>  }),<br>]);</pre><p>This creates a queue and repurposes the Lambda we created to poll that queue. In addition, we attached the permission to put objects in S3 to the consumer Lambda.</p><p>Now, let’s update the API route we have to write into the queue rather than triggering the Lambda function:</p><pre>const api = new Api(stack, &quot;api&quot;, {<br>  routes: {<br>    &quot;POST /&quot;: {<br>      type: &quot;aws&quot;,<br>      cdk: {<br>        integration: {<br>          subtype: HttpIntegrationSubtype.SQS_SEND_MESSAGE,<br>          parameterMapping: ParameterMapping.fromObject({<br>            QueueUrl: MappingValue.custom(queue.queueUrl),<br>            MessageBody: MappingValue.custom(&quot;$request.body&quot;),<br>          }),<br>        }<br>      }<br>    }<br>  },<br>});</pre><p>Once done, let’s update the Lambda function. We need to update the event to be of type SQSEvent, then pass the SQS Record body to the uplaodObject function:</p><pre>const promises = _evt.Records.map(record =&gt; uploadObject(record.messageId,record.body));<br>await Promise.all(promises);</pre><p>Is that enough to alleviate the load from S3 so that we stop having request rate errors? Let’s try it again using Jmeter.</p><p>Unfortunately, I still encountered a few | + Error uploading 9: SlowDown: Please reduce your request rate. errors. Setting the eventSource batchSize to 5 seems to have fixed the issue of the rate limit on S3. It might not work where requests are being more aggressively sent. In this case, we can still set a deliveryDelay parameter on the queue, which postpones the delivery of new messages for some time.</p><h3><strong>Conclusion</strong></h3><p>In addressing challenges related to high-volume data writes on S3, we’ve proposed a more reliable architecture involving queues. However, this solution isn’t one-size-fits-all. The queue solution has its own problems to consider — how to handle failed uploads, and should a dead letter queue be considered? Is the message size limit in SQS a problem?</p><p>Building a more reliable system is an iterative process, and this article provides a foundation for enhancing the robustness of serverless architectures in handling substantial data loads. Ultimately, developers are encouraged to adapt and refine these solutions based on their specific use cases.</p><p>Finally, I wouldn’t recommend rushing into building this kind of solution from the first day, unless you’re dealing with some serious data traffic. As with all software development, it’s important to be pragmatic and iteratively build your system blocks as you need.</p><p>How do you enhance the resilience of your system? Share your thoughts in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ee9a74a0539" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Local Development with SST for Serverless Applications]]></title>
            <link>https://ali-haydar.medium.com/exploring-local-development-with-sst-for-serverless-applications-0160f32de10f?source=rss-e2ba7ca4dbad------2</link>
            <guid isPermaLink="false">https://medium.com/p/0160f32de10f</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[dev]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Ali Haydar]]></dc:creator>
            <pubDate>Fri, 29 Dec 2023 06:39:28 GMT</pubDate>
            <atom:updated>2025-09-16T22:03:22.385Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>For more content like this, subscribe to my newsletter on Substack: </em><a href="https://techroom101.substack.com/">https://techroom101.substack.com/</a></blockquote><p>1A couple of years ago, I wrote an <a href="https://www.freecodecamp.org/news/how-to-test-serverless-applications-in-aws/">article on freeCodeCamp</a> about testing serverless applications in AWS. In that article, I explained the technical aspects of testing a serverless application formed of an API Gateway, a Lambda function and a DynamoDB table. I talk about how to test the function using unit tests, the DB with a bash script, and the overall app (i.e. the API endpoint) with e2e tests. However, there’s an important piece that I missed in that article. Where does all of the testing happen? I assumed that testing occurs on the cloud, except for unit tests.</p><p>A compelling question frequently arises in my enthusiastic discussions about serverless technology: How can we conduct local testing?</p><p>I typically encourage the usage of mocks, but I think it’s more suitable for testing in isolation (e.g. testing a single component of your app, mocking external services it integrates with). I am not a fan of Emulators; my experience with these tools that mimic a cloud service has been brittle, mainly due to setup complexity and parity with the real service used.</p><p>A few years ago, I failed a technical interview because I did not offer a way to start and test a serverless app in a local environment. There’s a need for a mindset change when working with serverless resources; some might disagree. That is going to be a discussion for a different day. For this post, I wanted to explore how to bridge the gap between cloud-based testing and the convenience of local development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Nnmchb7fqz_RnL--fIHGA.jpeg" /><figcaption><a href="https://www.pexels.com/photo/modern-through-arch-bridge-under-cloudy-sky-5707614/">Photo by Ben Mack</a></figcaption></figure><p>I read about SST (Serverless Stack) and the <a href="https://docs.sst.dev/live-lambda-development">live Lambda</a> feature it offers. The SST Docs mention:</p><pre>Live Lambda Development or Live Lambda is feature of SST that allows you to debug and test your Lambda functions locally while being invoked remotely by resources in AWS. It works by proxying requests from your AWS account to your local machine.</pre><p>Let’s explore the Live Lambda feature of SST. This will be an opportunity to set up an app with SST and evaluate the developer experience.</p><h3><strong>Building an app with SST</strong></h3><p>SST relies on <a href="https://aws.amazon.com/cdk/">AWS CDK</a> to write the infrastructure code using a set of programming languages (We’ll use TypeScript in our example). The CDK converts that code into CloudFormation templates behind the scenes.</p><p>SST offers a few constructs built on top of AWS CDK:</p><p>- `sst build` runs `cdk synth` internally. This converts the code to CloudFormation templates</p><p>- `pnpm sst dev` or `pnpm sst deploy` runs `cdk deploy`. This submits the templates to CloudFormation, which creates the stacks and their defined resources.</p><p>Let’s create an SST project:</p><pre>npx create-sst@latest<br>? Project name demo-sst<br>✔ Copied template files<br>Next steps:<br>- cd demo-sst<br>- npm install (or pnpm install, or yarn)<br>- npm run dev</pre><p>The infrastructure code is listed under `/stacks`, and the application code is listed under `/packages`. Notice that under `MyStack.ts`, an event bus and a few API routes are defined. Feel free to remove these, keeping the following only:</p><pre>import { StackContext, Api } from &#39;sst/constructs&#39;;<br>export function API({ stack }: StackContext) {<br><br>const api = new Api(stack, &#39;api&#39;, {<br>  routes: {<br>    &#39;GET /&#39;: &#39;packages/functions/src/lambda.handler&#39;,<br>    },<br>  });<br><br>stack.addOutputs({<br>  ApiEndpoint: api.url,<br>  });<br>}</pre><p>This code defines a GET API endpoint that will invoke the lambda function.</p><p>Feel free to delete the folders and files that aren’t needed under `packages`.</p><p>Once the app is started and deployed, you will get the API URL, which we specified as an output in the `/stacks/MyStack.ts` file. Requesting this API will return the value define in the `/packages/functions/src.lambda.ts` file. Change the returned value there and submit a new request to the API endpoint. Notice how you got the new value.</p><p>This is the SST Live Lambda. Without the long loop of deploying your changes to AWS, you get to execute your local Lambda function from the API Gateway already deployed in AWS.</p><p>SST mainly creates a WebSocket and proxies requests from Lambda functions to your local machine. You can find more details in the <a href="https://docs.sst.dev/live-lambda-development#how-it-works">SST docs</a>. Here is how it looks like</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FhnTSTm5n11g%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DhnTSTm5n11g&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FhnTSTm5n11g%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube-nocookie" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9de09728c499f4035f1bbae11d821a36/href">https://medium.com/media/9de09728c499f4035f1bbae11d821a36/href</a></iframe><h4><strong>How is this different from running your Lambda using a NodeJS worker?</strong></h4><p>Even though the functional behaviour of your Lambda code might be similar (i.e. experiencing similar behaviour of the Lambda function), running a Live Lambda offers a fully integrated environment where the Lambda configuration is as close to production since the whole environment is already running in the cloud. That provides better confidence over a local setup where you rely on AWS creds to do the execution. The integration allows you to test integrations with other AWS services such as API Gateway, Event Bridge, S3, etc. This offers a great win over setting up emulators on your local.</p><p>The next step would be to build a larger-scale project that integrates with services from AWS, such as S3, SQS, Event-Bridge, etc. How do you build a serverless app? and what’s your dev experience like?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0160f32de10f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoiding Data Overwrites in DynamoDB]]></title>
            <link>https://ali-haydar.medium.com/avoiding-data-overwrites-in-dynamodb-fe3fa681c931?source=rss-e2ba7ca4dbad------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe3fa681c931</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[dynamodb]]></category>
            <dc:creator><![CDATA[Ali Haydar]]></dc:creator>
            <pubDate>Mon, 18 Dec 2023 21:31:34 GMT</pubDate>
            <atom:updated>2025-09-16T22:03:34.904Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>For more content like this, subscribe to my newsletter on Substack: </em><a href="https://techroom101.substack.com/">https://techroom101.substack.com/</a></blockquote><p>In traditional database management systems, such as MySQL, there is a separation between the “INSERT” and the “UPDATE” operations. The “INSERT” statement is used to add records to a table, and the “UPDATE” statement is used to update existing records. If, for example, you try to insert a new record with an existing primary key, you would get an error.</p><p>On the other hand, DynamoDB uses a single operation `PutItem` to both insert or update existing records. When the `PutItem` operation is used with an existing primary key on the DynamoDB table, it will overwrite the data on that record.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ssnuq4YyE5LZV3Z7z-7hBg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@alex-green/">Alex Green</a> on <a href="https://www.pexels.com/photo/set-of-chess-pieces-on-board-5691866/">Pexels</a></figcaption></figure><p>If you’re not familiar with it, <a href="https://aws.amazon.com/pm/dynamodb/">DynamoDB</a> is a NoSQL database service provided by AWS, known for its seamless scalability, high performance, and simplified data model.</p><h3><strong>Is PutItem a risky operation?</strong></h3><p>The `PutItem` behaviour, where it overwrites existing data, might be considered risky in some instances if the developers aren’t careful about how to update existing records. That might be simply a bug or an oversight of a certain scenario, but could as well be a result of an incorrect DynamoDB table design to start with.</p><p>Of course, DynamoDB offers conditional expression to help mitigate the data overwrite risk. Without conditional expression, we’d need to add the logic in our code to check whether an item exists or not, and that’s costly. This also comes with the risk of race conditions if other requests are trying to update the same item.</p><h4><strong>Example where data is overwritten</strong></h4><p>Let’s see this as an example. Assume we have an “Employees” table designed as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s1RNXUKw0E2Ie57g0Fk3XA.png" /></figure><p>When creating a new employee, we’d want to ensure we don’t overwrite an existing user. Below we write the code using Terraform and JavaScript.</p><p>For simplicity, I’ll post the Terraform code in a single file `main.tf`:</p><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.0&quot;<br>    }<br>  }<br>}<br>variable &quot;aws_region&quot; {<br>  type    = string<br>  default = &quot;ap-southeast-2&quot;<br>}<br><br>provider &quot;aws&quot; {<br>  region = var.aws_region<br>}<br><br>resource &quot;aws_dynamodb_table&quot; &quot;employees_table&quot; {<br>  name         = &quot;employees&quot;<br>  billing_mode = &quot;PAY_PER_REQUEST&quot;<br>  hash_key     = &quot;username&quot;<br>  attribute {<br>    name = &quot;username&quot;<br>    type = &quot;S&quot;<br>  }<br>}<br><br># IAM Role<br>resource &quot;aws_iam_role&quot; &quot;add_employee_lambda_role&quot; {<br>  name               = &quot;add_employee_lambda_role&quot;<br>  assume_role_policy = &lt;&lt;EOF<br>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Action&quot;: &quot;sts:AssumeRole&quot;,<br>      &quot;Principal&quot;: {<br>        &quot;Service&quot;: &quot;lambda.amazonaws.com&quot;<br>      },<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Sid&quot;: &quot;&quot;<br>    }<br>  ]<br>}<br>EOF<br>}<br><br># IAM Policy that allows interaction with DynamoDB<br>resource &quot;aws_iam_policy&quot; &quot;add_employee_lambda_policy&quot; {<br>  name        = &quot;add_employee_lambda_policy&quot;<br>  description = &quot;Allow lambda to access dynamodb&quot;<br>  policy      = &lt;&lt;EOF<br>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Action&quot;: [<br>        &quot;dynamodb:PutItem&quot;,<br>        &quot;dynamodb:DeleteItem&quot;,<br>        &quot;dynamodb:GetItem&quot;,<br>        &quot;dynamodb:Scan&quot;,<br>        &quot;dynamodb:Query&quot;,<br>        &quot;dynamodb:UpdateItem&quot;<br>      ],<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Resource&quot;: &quot;*&quot;<br>    }<br>  ]<br>}<br>EOF<br>}<br><br># Attach IAM Policy to IAM Role<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;add_employee_lambda_role_policy_attachment&quot; {<br>  role       = aws_iam_role.add_employee_lambda_role.name<br>  policy_arn = aws_iam_policy.add_employee_lambda_policy.arn<br>}<br><br># data archive for lambda function<br>data &quot;archive_file&quot; &quot;add_employee_lambda_zip&quot; {<br>  type        = &quot;zip&quot;<br>  source_dir  = &quot;${path.module}/../src&quot;<br>  output_path = &quot;${path.module}/add_employee.zip&quot;<br>}<br><br># Add employee lambda function<br>resource &quot;aws_lambda_function&quot; &quot;add_employee_lambda&quot; {<br>  filename         = data.archive_file.add_employee_lambda_zip.output_path<br>  function_name    = &quot;add_employee_lambda&quot;<br>  role             = aws_iam_role.add_employee_lambda_role.arn<br>  handler          = &quot;add_employee.handler&quot;<br>  source_code_hash = data.archive_file.add_employee_lambda_zip.output_base64sha256<br>  runtime          = &quot;nodejs18.x&quot;<br>  publish          = true<br>  environment {<br>    variables = {<br>      DYNAMODB_TABLE = aws_dynamodb_table.employees_table.name<br>    }<br>  }<br>}</pre><p>Next, we’ll write a simple JS Lambda function to put items into DynamoDB:</p><pre>import {<br>  DynamoDBClient,<br>  PutItemCommand,<br>} from &#39;@aws-sdk/client-dynamodb&#39;;<br>import { marshall } from &#39;@aws-sdk/util-dynamodb&#39;;<br><br>const tableName = process.env.DYNAMODB_TABLE;<br>const client = new DynamoDBClient({});<br><br>export const handler = async (event) =&gt; {<br>  const { username, name, department, jobTitle } = event;<br><br>  const params = {<br>    TableName: tableName,<br>    Item: marshall({<br>      username,<br>      name,<br>      department,<br>      jobTitle,<br>    }),<br>  };<br>  const command = new PutItemCommand(params);<br>  const response = await client.send(command);<br>  console.log(response);<br>  return response;<br>};</pre><p>Deploy this infrastructure (`terraform apply`), then navigate to the Lambda function in AWS Console and test the lambda with the following event object:</p><pre>{<br>  &quot;username&quot;: &quot;ali&quot;,<br>  &quot;name&quot;: &quot;Ali Haydar&quot;,<br>  &quot;department&quot;: &quot;Engineering&quot;,<br>  &quot;jobTitle&quot;: &quot;Platform Lead&quot;<br>}</pre><p>Verify the item got added to DynamoDB.</p><p>Assume a new employee with the same first name joined the company, and the admin just went ahead with the following employee data (let’s use the Lambda test functionality to add the new employee — of course, in a real-life scenario there would be a UI for that):</p><pre>{<br>  &quot;username&quot;: &quot;ali&quot;,<br>  &quot;name&quot;: &quot;Ali Wong&quot;,<br>  &quot;department&quot;: &quot;Acting&quot;,<br>  &quot;jobTitle&quot;: &quot;Stand-up comedian and acress&quot;<br>}</pre><p>A few days later, the first employee “ali” got promoted to Chief Finance Officer, so it’s time to update this info in the system. When searching for “ali”, only “Ali Wong” was found. Where’s our intended user?</p><p>That was an example where an oversight and a poor design of the table caused a bug leading to data loss.</p><h4><strong>Example with conditional expression</strong></h4><p>To protect against this kind of mistake, we modify our code slightly, adding a conditional expression to the params:</p><pre>ConditionExpression: &#39;attribute_not_exists(username)&#39;</pre><p>Deploy the change.</p><p>Try to update the existing “Ali Wong” record with the following data:</p><pre>{<br>  &quot;username&quot;: &quot;ali&quot;,<br>  &quot;name&quot;: &quot;Ali Haydar&quot;,<br>  &quot;department&quot;: &quot;Engineering&quot;,<br>  &quot;jobTitle&quot;: &quot;Platform Lead&quot;<br>}</pre><p>Notice the error:</p><pre>&quot;errorType&quot;: &quot;ConditionalCheckFailedException&quot;,<br>&quot;errorMessage&quot;: &quot;The conditional request failed&quot;,</pre><p>The conditional expression checks for the non-existence of the username before allowing the update.</p><p>The conditional expressions can be useful in multiple other use cases. Have a look at the <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html">docs</a>.</p><p>I’ve seen patterns in relational databases where an operation behaves similarly to PutItem in DynamoDB. Mostly, these were code-built functions that handle the logic of “Insert” or “Update”. In some cases, we referred to them as “upsert” operations. The concept is often implemented using statements like `INSERT ON DUPLICATE KEY UPDATE` in MySQL.</p><p>In the example above, even though there is no direct impact of the table design; using a username as a primary key makes it more prone to data overwrite, especially if that’s a manually entered username. In addition, it does limit the access patterns to the table, but that’s a discussion for another day. One way to improve this might be to use a composite key of username and department for example. What do you think?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe3fa681c931" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to enhance your Lambda function performance with memory configuration?]]></title>
            <link>https://ali-haydar.medium.com/how-to-enhance-your-lambda-function-performance-with-memory-configuration-3455c5af6fd4?source=rss-e2ba7ca4dbad------2</link>
            <guid isPermaLink="false">https://medium.com/p/3455c5af6fd4</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Ali Haydar]]></dc:creator>
            <pubDate>Mon, 21 Aug 2023 22:32:24 GMT</pubDate>
            <atom:updated>2025-09-16T22:03:48.914Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>For more content like this, subscribe to my newsletter on Substack: </em><a href="https://techroom101.substack.com/">https://techroom101.substack.com/</a></blockquote><p>I have a lambda function that’s taking a few seconds to execute, and that’s not related to a cold start. It’s the code in the handler function that’s taking time, and that’s because it’s CPU and memory-intensive.</p><p>Performance problems related to cold start can be enhanced through provisioned concurrency and managing the “Init” code. You can read about this in my previous articles:</p><ul><li><a href="https://www.freecodecamp.org/news/how-to-speed-up-lambda-functions/">How to speed up your Lambda function</a></li><li><a href="https://ali-haydar.medium.com/effortlessly-juggling-multiple-concurrent-requests-in-aws-lambda-10f1ffdb20dd">Effortlessly Juggling Multiple Concurrent Requests in AWS Lambda</a></li></ul><p>We know the performance is related to CPU and Memory, so the solution might be as simple as increasing the memory. Isn’t it?</p><p>Let’s do a small demonstration comparing the execution of the Lambda with different memory configurations. It’s worth noting that we cannot explicitly control the Lambda CPU; it’s automatically increased as we increase the memory. From the AWS docs:</p><blockquote>The amount of memory also determines the amount of virtual CPU available to a function. Adding more memory proportionally increases the amount of CPU, increasing the overall computational power available. If a function is CPU-, network- or memory-bound, then changing the memory setting can dramatically improve its performance.</blockquote><h3><strong>Testing the performance of a Lambda function</strong></h3><p>For this demo let’s use the following Lambda function that I generated with the help of ChatGPT:</p><pre>export const handler = async (event) =&gt; {<br>  const matrixSize = 100; // Size of the square matrix<br>  const matrix = generateMatrix(matrixSize);<br>  const result = performMatrixMultiplication(matrix);<br>  return result;<br>};<br><br>function generateMatrix(size) {<br>  const matrix = [];<br>  for (let i = 0; i &lt; size; i++) {<br>    const row = [];<br>    for (let j = 0; j &lt; size; j++) {<br>      row.push(Math.random());<br>    }<br>    matrix.push(row);<br>  }<br>  return matrix;<br>}<br><br>function performMatrixMultiplication(matrix) {<br>  const size = matrix.length;<br>  const result = new Array(size);<br>  for (let i = 0; i &lt; size; i++) {<br>    result[i] = new Array(size);<br>    for (let j = 0; j &lt; size; j++) {<br>      let sum = 0;<br>      for (let k = 0; k &lt; size; k++) {<br>        sum += matrix[i][k] * matrix[k][j];<br>      }<br>      result[i][j] = sum;<br>    }<br>  }<br>  return result;<br>}</pre><p>The Lambda function generates a large square matrix, performs matrix multiplication, and returns the resulting matrix. That’s an example of a CPU and memory-intensive function.</p><h4><strong>Lambda with 128 MB memory</strong></h4><ul><li>Create this function manually in the AWS console, selecting NodeJs as the runtime, and keep the rest of the configuration to the default. This will create the Lambda with a `128 MB` memory.</li><li>Execute the function by navigating to the “Test” tab and clicking the “Test” button.</li></ul><p>Notice the results:</p><pre>Duration: 298.55 ms Billed Duration: 299 ms Memory Size: 128 MB Max Memory Used: 72 MB Init Duration: 160.36 ms</pre><p>We got a duration of 298.55 ms.</p><h4><strong>Lambda with 256 MB memory</strong></h4><ul><li>In the configuration tab, update the Lambda memory to `256 MB`</li><li>Test the lambda function</li></ul><p>Notice the results:</p><pre>Duration: 133.94 ms Billed Duration: 134 ms Memory Size: 255 MB Max Memory Used: 73 MB Init Duration: 162.88 ms</pre><p>We got a duration of 133.94 ms by doubling the memory.</p><h4>Lambda with 512 MB memory</h4><ul><li>In the configuration tab, update the Lambda memory to `512 MB`</li><li>Test the lambda function</li></ul><p>Notice the results:</p><pre>Duration: 51.12 ms Billed Duration: 52 ms Memory Size: 512 MB Max Memory Used: 73 MB Init Duration: 144.95 ms</pre><p>We got a duration of 51.12 ms by doubling the memory.</p><h4><strong>Lambda with 1024 MB memory</strong></h4><ul><li>In the configuration tab, update the Lambda memory to `1024 MB`</li><li>Test the lambda function</li></ul><p>Notice the results:</p><pre>Duration: 30.42 ms Billed Duration: 31 ms Memory Size: 1024 MB Max Memory Used: 73 MB Init Duration: 163.51 ms</pre><p>We got a duration of 30.42 ms by doubling the memory</p><h4><strong>Shall we continue to increase the memory?</strong></h4><p>We have demonstrated that more memory means faster execution.</p><p>At some point, the increased memory, which comes with an increased CPU won’t cause better performance. But for now, let’s accept that a 30.42 ms execution time is reasonable. It is worth noting that the Memory used in all execution was 73MB, so it’s the CPU that was improving with the memory upgrades.</p><h3><strong>How to choose a memory config?</strong></h3><p>As with any software configuration, there are some trade-offs. In this case, it’s the cost of Execution.</p><p>Lambda is priced based on number of requests and the duration of requests. In addition to that, the price of request duration is dependent on the memory associated with the Lambda function. From the <a href="https://aws.amazon.com/lambda/pricing/">AWS Docs</a>:</p><pre>Memory (MB) Price per 1ms<br>128         $0.0000000021<br>512         $0.0000000083<br>1024        $0.0000000167<br>1536        $0.0000000250<br>2048        $0.0000000333<br>3072        $0.0000000500<br>4096        $0.0000000667<br>5120        $0.0000000833<br>6144        $0.0000001000<br>7168        $0.0000001167<br>8192        $0.0000001333<br>9216        $0.0000001500<br>10240       $0.0000001667</pre><p>So how can we find a good balance between memory and cost?</p><p>The <a href="https://github.com/alexcasalboni/aws-lambda-power-tuning">aws lambda power tuning tool</a> helps optimise the Lambda performance and cost in a data-driven manner. Let’s try it out:</p><ul><li>There are multiple ways to deploy the application into the AWS account. We’ll deploy it from the <a href="https://serverlessrepo.aws.amazon.com/applications/arn:aws:serverlessrepo:us-east-1:451282441545:applications~aws-lambda-power-tuning">AWS Serverless Application Repository</a> as that’s the simplest option.</li><li>The deployment of this serverless application will create a step function starting with the name `powerTuningStateMachine`</li><li>Start the execution of the step function and pass the following JSON:</li></ul><pre>{<br>  &quot;lambdaARN&quot;: &quot;your-lambda-function-arn&quot;,<br>  &quot;powerValues&quot;: [128, 256, 512, 1024, 1536, 2048, 3008],<br>  &quot;num&quot;: 50,<br>  &quot;payload&quot;: {},<br>  &quot;parallelInvocation&quot;: true,<br>  &quot;strategy&quot;: &quot;cost&quot;<br>}</pre><ul><li>Once executed this will generate the following output in the “Execution input and output” tab of the step function:</li></ul><pre>{<br>  &quot;power&quot;: 512,<br>  &quot;cost&quot;: 1.428e-7,<br>  &quot;duration&quot;: 16.566666666666666,<br>  &quot;stateMachine&quot;: {<br>    &quot;executionCost&quot;: 0.00033,<br>    &quot;lambdaCost&quot;: 0.00011801685000000001,<br>    &quot;visualization&quot;: &quot;https://lambda-power-tuning.show/XXXX&quot;<br>  }<br>}</pre><p>The visualisation looks as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jvxeRWJHsjd1_w8eyvwGFw.png" /></figure><p>This graph shows that memory of 512 MB would offer a good balance of cost and performance.</p><p>Thanks for reading this far. Did you like this article, do you have feedback or would like to further discuss the topic? Please reach out on <a href="https://twitter.com/Alee_Haydar">Twitter</a> or <a href="https://www.linkedin.com/in/ahaydar/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3455c5af6fd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effortlessly Juggling Multiple Concurrent Requests in AWS Lambda]]></title>
            <link>https://ali-haydar.medium.com/effortlessly-juggling-multiple-concurrent-requests-in-aws-lambda-10f1ffdb20dd?source=rss-e2ba7ca4dbad------2</link>
            <guid isPermaLink="false">https://medium.com/p/10f1ffdb20dd</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ali Haydar]]></dc:creator>
            <pubDate>Mon, 26 Jun 2023 16:40:28 GMT</pubDate>
            <atom:updated>2023-06-26T16:55:01.130Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever tried to handle a ton of requests at once with AWS Lambda? What if you had a critical operation that required speed, scaling the performance of a request down to single-digit milliseconds?</p><p>In a previous article, I discussed how to <a href="https://www.freecodecamp.org/news/how-to-speed-up-lambda-functions">speed up your Lambda function</a>, touching on the concept of a ‘cold start’ and how to minimize it by moving some non-critical code outside the Lambda handler, such as establishing a DB connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhEYVymmK4dwL0yl3jIkPg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@rccbtn/">Basitan Riccardi</a> on <a href="https://www.pexels.com/photo/cars-driving-on-highway-at-night-6058278/">Pexels</a></figcaption></figure><p>When we send a request to execute a Lambda function, the service initialises an execution environment. That’s a virtual machine (MicroVM) dedicated to each concurrent invocation of a Lambda function. Within this VM, there’s a kernel, a runtime (e.g. Node.js), function code, and extensions code. The cold start period includes creating this environment, initialising the runtime and extensions, and downloading the code. It also includes the execution of the ‘Init’ code (the code you write before the handler function).</p><p>With multiple consecutive executions, the Lambda service would reuse a previously created execution environment, and only execute the code within the handler function (that’s what we call warm start). That’s fascinating and would be sufficient in lots of cases. However, in some instances, we need to execute a single Lambda function concurrently. That would cause the creation of a new execution environment for each execution, which means that we cannot leverage the warm Lambda, and would need to experience the cold start for each invocation.</p><p>The solution in this case is to set up provisioned concurrency. Let’s test it.</p><h3><strong>Set up the project</strong></h3><p>We will build a simple project consisting of 2 Lambda functions, one orchestrator and one worker that will be invoked concurrently from the orchestrator Lambda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*X10CKla5Z5pKYUNlRbQxNA.gif" /></figure><p>Let’s create the infrastructure in Terraform:</p><ul><li>Create the IAM policies and roles that will be used by the Lambda functions</li></ul><pre>locals {<br>  policy_document_cloudwatch = {<br>    Version = &quot;2012–10–17&quot;<br>    Statement = [<br>      {<br>        Effect = &quot;Allow&quot;<br>        Action = [<br>        &quot;logs:CreateLogGroup&quot;,<br>        &quot;logs:CreateLogStream&quot;,<br>        &quot;logs:PutLogEvents&quot;<br>        ]<br>        Resource = &quot;arn:aws:logs:*:*:*&quot;<br>      }<br>    ]<br>  }<br><br>  policy_document_lambda_invoke = {<br>    Version = &quot;2012–10–17&quot;<br>    Statement = [<br>      {<br>      Effect = &quot;Allow&quot;<br>      Action = [&quot;lambda:InvokeFunction&quot;]<br>      Resource = [&quot;arn:aws:lambda:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:function:*&quot;]<br>      }<br>    ]<br>  }<br>}<br><br>data &quot;aws_iam_policy_document&quot; &quot;lambda_assume_role&quot; {<br>  statement {<br>    actions = [&quot;sts:AssumeRole&quot;]<br>    principals {<br>    type = &quot;Service&quot;<br>    identifiers = [&quot;lambda.amazonaws.com&quot;]<br>    }<br>  }<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;worker_lambda_execution_role&quot; {<br>  name = &quot;worker_lambda-exec-role&quot;<br>  assume_role_policy = data.aws_iam_policy_document.lambda_assume_role.json<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;lambda_policies_attachment_cloudwatch&quot; {<br>  role = aws_iam_role.worker_lambda_execution_role.name<br>  policy_arn = aws_iam_policy.lambda_policies_cloudwatch.arn<br>}<br><br>resource &quot;aws_iam_policy&quot; &quot;lambda_policies_cloudwatch&quot; {<br>  name = &quot;lambda_logging_cloudwatch_access&quot;<br>  description = &quot;lambda logs in CloudWatch&quot;<br>  policy = jsonencode({<br>  Version = &quot;2012–10–17&quot;<br>  Statement = local.policy_document_cloudwatch.Statement<br>  })<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;orchestrator_lambda_execution_role&quot; {<br>  name = &quot;orchestrator-lambda-exec-role&quot;<br>  assume_role_policy = data.aws_iam_policy_document.lambda_assume_role.json<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;lambda_policies_attachment_cloudwatch_and_lambda_invocation&quot; {<br>  role = aws_iam_role.orchestrator_lambda_execution_role.name<br>  policy_arn = aws_iam_policy.lambda_policies_cloudwatch_and_lambda_invocation.arn<br>}<br><br>resource &quot;aws_iam_policy&quot; &quot;lambda_policies_cloudwatch_and_lambda_invocation&quot; {<br>  name = &quot;lambda_logging_cloudwatch_access_and_lambda_invocation&quot;<br>  description = &quot;lambda logs in CloudWatch and worker lambda invocation&quot;<br>  policy = jsonencode({<br>    Version = &quot;2012–10–17&quot;<br>    Statement = concat(<br>      local.policy_document_cloudwatch.Statement,<br>      local.policy_document_lambda_invoke.Statement<br>    )<br>  })<br>}</pre><ul><li>Create a lambda.tffile configuring the lambda functions</li></ul><pre>resource &quot;aws_lambda_function&quot; &quot;orchestrator_lambda&quot; {<br>    function_name = &quot;orchestrator_lambda&quot;<br><br>    handler = &quot;orchestrator_lambda.handler&quot;<br>    runtime = &quot;nodejs18.x&quot;<br><br>    filename = &quot;orchestrator_lambda_function.zip&quot;<br><br>    source_code_hash = filebase64sha256(&quot;orchestrator_lambda_function.zip&quot;)<br><br>    role = aws_iam_role.orchestrator_lambda_execution_role.arn<br><br>    depends_on = [<br>      aws_iam_role_policy_attachment.lambda_policies_attachment_cloudwatch_and_lambda_invocation<br>    ]<br><br>    environment {<br>      variables = {<br>        FUNCTION_NAME = aws_lambda_function.worker_lambda.function_name<br>      }<br>    }<br>  }<br><br><br>  resource &quot;aws_lambda_function&quot; &quot;worker_lambda&quot; {<br>    function_name = &quot;worker_lambda&quot;<br><br>    handler = &quot;worker_lambda.handler&quot;<br>    runtime = &quot;nodejs18.x&quot;<br><br>    filename = &quot;worker_lambda_function.zip&quot;<br><br>    source_code_hash = filebase64sha256(&quot;worker_lambda_function.zip&quot;)<br><br>    role = aws_iam_role.worker_lambda_execution_role.arn<br><br>    depends_on = [<br>      aws_iam_role_policy_attachment.lambda_policies_attachment_cloudwatch<br>    ]<br>  }</pre><p>We have yet to define any concurrency. We will get to this later.</p><p>Now let’s implement our Lambda functions:</p><ul><li>Create a new orchestrator_lambda file</li></ul><pre>  import { InvokeCommand, LambdaClient, LogType } from &quot;@aws-sdk/client-lambda&quot;;<br><br>  const invokeLambda = async (payload) =&gt; {<br>    const client = new LambdaClient();<br>    const command = new InvokeCommand({<br>      FunctionName: process.env.FUNCTION_NAME,<br>      LogType: LogType.Tail,<br>      Payload: JSON.stringify(payload),<br>    });<br>    await client.send(command);<br><br>    console.log(&quot;Lambda function invoked!&quot;);<br>  };<br><br>  export const handler = async (event, context) =&gt; {<br>    const promises = [];<br><br>    for (let i = 0; i &lt; 10; i++) {<br>      const payload = { invocation: i + 1 };<br>      promises.push(invokeLambda(payload));<br>    }<br><br>    await Promise.all(promises);<br>  };</pre><ul><li>Create a new worker_lambda.js file</li></ul><pre>  export const handler = async (event, context) =&gt; {<br>    console.log(&quot;here is the event received: &quot;, event);<br>  };</pre><p><strong>## Test the concurrent Lambda execution before and after setting up the provisioned concurrency</strong></p><p><strong>### Before Provisioned Concurrency</strong></p><p>In the AWS Console, navigate to the “Orchestrator Lambda” and click the “Test” button. This will invoke the “Worker Lambda” 10 times.</p><p>Have a look at the CloudWatch logs of the “Worker Lambda”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-nnof-fPsdadI3TJXvReaw.png" /></figure><p>Notice the “Worker Lambda” got invoked 10 times concurrently. Each time starting a new execution environment and initialising it. That “cold start” duration shows as the “Init Duration” in the previous screenshot; there are ~ 160ms used for “Init” in every invocation. What if we can save this time?</p><p><strong>### After Provisioned Concurrency</strong></p><p>Let’s set up provisioned concurrency for the “Worker Lambda”. This will allocate a specified number of execution environments for the Lambda function, which would ensure rapid function start-up, skipping the “Init” part. The Provisioned concurrency works only with a Lambda alias (a pointer to a specific Lambda version) or Lambda version, so we’ll set this up as well.</p><ul><li>In your lambda.tf file, under the worker_lambda resource, add the publish property, which will create a Lambda version:</li></ul><pre>publish = true</pre><ul><li>Add the Lambda alias, which will point to the created version of the Lambda</li></ul><pre>resource &quot;aws_lambda_alias&quot; &quot;worker_lambda_alias&quot; {<br>  name = &quot;worker_lambda_alias&quot;<br>  function_name = aws_lambda_function.worker_lambda.function_name<br>  function_version = aws_lambda_function.worker_lambda.version // This is the latest published version<br>}</pre><ul><li>Add the provisioned concurrency configuration</li></ul><pre>resource &quot;aws_lambda_provisioned_concurrency_config&quot; &quot;worker_lambda_provisioned_concurrency&quot; {<br>  function_name = aws_lambda_alias.worker_lambda_alias.function_name<br>  provisioned_concurrent_executions = 10<br>  qualifier = aws_lambda_alias.worker_lambda_alias.name<br>}</pre><ul><li>On the “Orchestrator Lambda” config, pass the alias as an environment variable. So the environment tag would look as follows:</li></ul><pre>environment {<br>  variables = {<br>    WORKER_FUNCTION_NAME = aws_lambda_function.worker_lambda.function_name<br>    WORLER_ALIAS = aws_lambda_alias.worker_lambda_alias.name<br>  }<br>}</pre><ul><li>Update the Lambda “Orchestrator Lambda” code to hit the alias, in the orchestrator_lambda.js:</li></ul><pre>const command = new InvokeCommand({<br>  FunctionName: `${process.env.WORKER_FUNCTION_NAME}:${process.env.WORKER_ALIAS}`,<br>  LogType: LogType.Tail,<br>  Payload: JSON.stringify(payload),<br>});</pre><p>After you deploy these changes, navigate to the AWS Console and click the “Test” button in the “Orchestrator” Lambda. This will invoke the “Worker Lambda” 10 times.</p><p>Have a look at the CloudWatch logs of the “Worker Lambda”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OTOhnIrfJaASFKTrSzs5tg.png" /></figure><p>Notice that we no longer have an “Init” duration, as we have 10 provisioned Worker Lambda functions. If we submitted 11 concurrent requests, then one worker lambda will have an “Init” duration.</p><p>It’s worth noting that, even with provisioned concurrency, you might still experience some instances having “Init” duration if you invoke the function immediately after deployment.</p><p>Provisioned concurrency comes with a cost as we have Lambda instances running all the time. One thing to think of is how would you balance the cost and performance benefits of using provisioned concurrency. I’d love to hear your thoughts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10f1ffdb20dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prevent API overload with rate limiting in AWS]]></title>
            <link>https://ali-haydar.medium.com/prevent-api-overload-with-rate-limiting-in-aws-94bf34a43b79?source=rss-e2ba7ca4dbad------2</link>
            <guid isPermaLink="false">https://medium.com/p/94bf34a43b79</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Ali Haydar]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 20:41:41 GMT</pubDate>
            <atom:updated>2025-09-16T22:05:02.789Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>For more content like this, subscribe to my newsletter on Substack: </em><a href="https://techroom101.substack.com/">https://techroom101.substack.com/</a></blockquote><p>In the early days of the COVID-19 pandemic, and for a significant period, when we went to the supermarket, we had to wait in a queue for our turn to enter the supermarket. Only a certain number of customers could shop together at a particular time. The intention was to keep a physical distance between individuals to limit the spread of the virus, hence keeping people safe and limiting the load on the health system.</p><p>That’s similar to what we do in Software when we rate limit our APIs. We do it for multiple reasons, including preventing abuse (e.g. malicious user overwhelming the system with too many requests), managing downstream services and resources (e.g. database) or simply using rate limit as a way to monetize the APIs (e.g. enabling free users to use the APIs less frequently than paid users).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*USMpwdQSyFmcjyB-GdXd3g.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@enriquezafra/">Enrique Zafra</a> on <a href="https://www.pexels.com/photo/clear-glass-hour-glass-3570733/">Pexels</a></figcaption></figure><p>This post will build an API using <a href="https://aws.amazon.com/api-gateway/">AWS API Gateway</a> and explore how to rate-limit calls to our endpoints. API Gateway is a managed service from AWS that helps you publish, manage and monitor your APIs. We will use Terraform to set up our infrastructure.</p><p>We deploy APIs to stages in API Gateway, where each stage has a single deployment. You could have one stage for development, one for testing and one for production. Each stage has its URL and settings.</p><p>We will build an endpoint that returns the number of people in the supermarket. It will be of this shape: GET /…/prod/customers.</p><h3>Build the API</h3><p>In Terraform:</p><ul><li>Create the REST API</li></ul><pre>resource &quot;aws_api_gateway_rest_api&quot; &quot;api&quot; {<br>  name = &quot;SupermarketCustomers&quot;<br>  description = &quot;Tracks the number of customers that enter the supermarket&quot;<br>  endpoint_configuration {<br>    types = [&quot;REGIONAL&quot;]<br>  }<br>}</pre><ul><li>Create the “Customers” resource. That will be the first endpoint:</li></ul><pre>resource &quot;aws_api_gateway_resource&quot; &quot;customers_resource&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.api.id<br>  parent_id = aws_api_gateway_rest_api.api.root_resource_id<br>  path_part = &quot;customers&quot;<br>}</pre><ul><li>Create the method for this resource — GET in this case:</li></ul><pre>resource &quot;aws_api_gateway_method&quot; &quot;get_method&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.api.id<br>  resource_id = aws_api_gateway_resource.customers_resource.id<br>  http_method = &quot;GET&quot;<br>  authorization = &quot;NONE&quot;<br>}</pre><p>Notice the http_method in this case, and the authorization set to NONE, as we’d want this API to be accessible to everyone (some people would like to check the number of customers in the supermarket from home)</p><ul><li>Until now, we have configured the API and method. Now we must move to the integration part, which covers interacting with the backend. Specifying an AWS service, HTTP Backend, or MOCK is possible. In this example, we will use MOCK to mock the backend and hardcode the response to return on the API Gateway.</li></ul><pre>resource &quot;aws_api_gateway_integration&quot; &quot;mock_backend&quot; {<br>  http_method = aws_api_gateway_method.get_method.http_method<br>  resource_id = aws_api_gateway_resource.customers_resource.id<br>  rest_api_id = aws_api_gateway_rest_api.api.id<br>  type = &quot;MOCK&quot;<br>  request_templates = {<br>    &quot;application/json&quot; = jsonencode(<br>      {<br>        statusCode = 200<br>      })<br>  }<br>}</pre><ul><li>Define the integration response and method response:</li></ul><pre>resource &quot;aws_api_gateway_method_response&quot; &quot;response_200&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.api.id<br>  resource_id = aws_api_gateway_resource.customers_resource.id<br>  http_method = aws_api_gateway_method.get_method.http_method<br>  status_code = 200<br>}</pre><pre>resource “aws_api_gateway_integration_response” “mock_backend_response” {<br>  rest_api_id = aws_api_gateway_rest_api.api.id<br>  resource_id = aws_api_gateway_resource.customers_resource.id<br>  http_method = aws_api_gateway_method.get_method.http_method<br>  status_code = aws_api_gateway_method_response.response_200.status_code<br><br># Transforms the backend JSON response to XML<br>  response_templates = {<br>    &quot;application/json&quot; = &lt;&lt;EOF<br>    {<br>      &quot;message&quot;: &quot;hello from the mocked backend&quot;<br>    }<br>    EOF<br>  }<br>}</pre><ul><li>As mentioned above, changes in API Gateway won’t apply without a deployment, which needs to happen to a Stage:</li></ul><pre>resource &quot;aws_api_gateway_deployment&quot; &quot;api_deployment&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.api.id<br>  lifecycle {<br>    create_before_destroy = true<br>  }<br>}<br><br>resource &quot;aws_api_gateway_stage&quot; &quot;prod&quot; {<br>  deployment_id = aws_api_gateway_deployment.api_deployment.id<br>  rest_api_id = aws_api_gateway_rest_api.api.id<br>  stage_name = &quot;prod&quot;<br>}</pre><p>Deploy this configuration to your AWS account. You should be able to see your API, resource and method as per the following screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*64g9dT_-DGH761jUO34V5A.png" /></figure><p>Click the “Test” button to get a response like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FdhtVqr6uhixAVHy_SR_Lg.png" /></figure><h3><strong>Rate &amp; Burst Limits</strong></h3><p>AWS API Gateway has a default set of 10,000 requests per second limit per region within an AWS account, with a burst of 5000 requests. That’s across all APIs of different types (e.g. REST, WebSocket).</p><p>AWS uses the <a href="https://en.wikipedia.org/wiki/Token_bucket#:~:text=The%20token%20bucket%20is%20an,variations%20in%20the%20traffic%20flow">Token Bucket Algorithm</a> to throttle requests. Each request is a token in the bucket. The burst limit is the maximum number of concurrent tokens consumed simultaneously. The rate limit is the speed at which the bucket is refilled with new tokens. You can also look at the rate limit as the maximum number of tokens that can be used within one second (or a period).</p><p>Assume we set a rate limit of 10 requests per second and a burst rate of 15 requests. That means that ten requests are added to the bucket every second up to the maximum of 15 requests. If we consume 15 requests per minute, the usage rate will be bigger than the refill rate, which means we’ll consume the requests in our bucket faster. So in 2 seconds, we will start throttling requests returning 429: Too Many Requests errors. Here are some details:</p><ul><li>In 1 second, we have 15 requests in the bucket; we consumed 15 requests and refilled 10. That leaves ten requests in the bucket</li><li>In 2 seconds, we have ten requests in the bucket; we consumed 15 requests and refilled 10. 5 of the requests consumed will return an error, as there are no more available requests in the bucket.</li></ul><p>However, suppose we’re consuming requests at the same speed as the refill rate (rate limit of 10 requests per second). In that case, we will always be able to serve these requests without a problem, as the burst rate (maximum number of requests simultaneously) will never be reached.</p><p>Setting the rate and burst limits properly based on the expected traffic levels and available resources is essential to ensure reliable service.</p><p>This is how we set the rates in Terraform at the stage and route level:</p><pre>resource &quot;aws_api_gateway_method_settings&quot; &quot;get_method_settings&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.api.id<br>  stage_name = aws_api_gateway_stage.prod.stage_name<br>  method_path = &quot;*/*&quot;<br>  settings {<br>    throttling_burst_limit = 1<br>    throttling_rate_limit = 2<br>  }<br>}</pre><p>After you deploy this change, Invoke the endpoint URL (You can find the URL under stages → prod → / → /customers → GET). Notice the “Too many requests” error when invoked more than a single time per second.</p><p>With this approach, a single customer might overuse the API, which would cause throttling for other customers. It is possible to control this with <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-usage-plans.html#api-gateway-api-usage-plans-overview">usage plans</a>. This requires that each customer has an API key, which we haven’t set up in our example.</p><p>Have you implemented rate limiting in the past? What would you do differently?</p><p>Thanks for reading this far. Did you like this article, and do you think others might find it helpful? Feel free to share it on <a href="http://twitter.com/share?text=Check%20this%20article%20by%20@Alee_Haydar%20on%20how%20to%20build%20rate%20limiting%20on%20your%20APIs:%20&amp;url=https://ali-haydar.medium.com/prevent-api-overload-with-rate-limiting-in-aws-94bf34a43b79&amp;hashtags=aws,apigateway,awscommunity,awscommunitybuilders,softwaredevelopment">Twitter</a> or <a href="https://www.linkedin.com/sharing/share-offsite/?url=https://ali-haydar.medium.com/prevent-api-overload-with-rate-limiting-in-aws-94bf34a43b79">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94bf34a43b79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to securely expose your local app to the internet using EC2?]]></title>
            <link>https://ali-haydar.medium.com/how-to-securely-expose-your-local-app-to-the-internet-using-ec2-eda750569e?source=rss-e2ba7ca4dbad------2</link>
            <guid isPermaLink="false">https://medium.com/p/eda750569e</guid>
            <category><![CDATA[reverse-proxy]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Ali Haydar]]></dc:creator>
            <pubDate>Tue, 31 Jan 2023 21:32:27 GMT</pubDate>
            <atom:updated>2025-09-16T22:05:16.026Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>For more content like this, subscribe to my newsletter on Substack: </em><a href="https://techroom101.substack.com/">https://techroom101.substack.com/</a></blockquote><p>Are you developing an app and want others to access it before it’s available in the cloud? Or are you integrating with a third-party tool and wish to enable access to your local app for a better development experience? This article is for you.</p><p>There are many use cases where you might need to expose your local app (the app you are developing on your local machine) to the internet. That could be a site, an API or a chatbot. I’ve worked on a few of these cases, most recently a side project developing a Slack application.</p><p>When integrating with Slack, you need to provide Slack with a redirection URL so that the user goes back to your site after granting the necessary permissions (this is common when using [OAuth](https://en.wikipedia.org/wiki/OAuth)).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMic6EIyFrSIK3-0k_hXrw.png" /></figure><p>As you are working on a local machine, the URL should point to your localhost, which has a private IP. Your home/office router will have a public IP assigned by the internet provider, but any device behind that router will be given a private IP. So how can we expose our app to the internet?</p><h3>How to expose your app to the internet?</h3><blockquote>Note that this setup might incur some costs.</blockquote><p>First, I used <a href="https://ngrok.com/">ngrok</a>, which creates a tunnel between my local machine and servers that are already exposed to the internet — So your requests to the ngrok server get forwarded to your local app. That’s convenient and useful. However, the URL of that server changes every time you connect, which means I need to update my app config every time I connect.</p><p>I wanted something more permanent and maintainable, where I start my app, add my changes and test. One option was to subscribe to the ngrok paid services, where you can get a permanent URL. I need this for a side project and want it to be cost-effective, so I decided to implement a basic solution myself.</p><p>To achieve this, we’ll create an <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Instances.html">EC2 instance</a> that allows ingress access from the internet, and install an nginx server that acts as a reverse proxy to forward requests to this server to my app running on my local machine, using SSH tunnelling.</p><p>Let’s build it with Terraform.</p><p><strong>## Create an EC2 instance</strong></p><p>We will use the t2.micro instance as it’s covered in the <a href="https://aws.amazon.com/free/?all-free-tier.sort-by=item.additionalFields.SortRank&amp;all-free-tier.sort-order=asc&amp;awsf.Free%20Tier%20Types=*all&amp;awsf.Free%20Tier%20Categories=categories%23compute&amp;all-free-tier.q=ec2&amp;all-free-tier.q_operator=AND">Free Tier for 12 months</a>.</p><p>First, we will create a Security Group, which will be attached to the EC2 instance, to allow ingress HTTP and ssh access to the machine:</p><pre>resource &quot;aws_security_group&quot; &quot;allow_http_ssh_and_http_on_80&quot; {<br>  name = &quot;allow_http&quot;<br>  description = &quot;Allow http inbound traffic&quot;<br>  ingress {<br>    description = &quot;http&quot;<br>    from_port = 80<br>    to_port = 80<br>    protocol = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  ingress {<br>    description = &quot;ssh&quot;<br>    from_port = 22<br>    to_port = 22<br>    protocol = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  egress {<br>    from_port = 0<br>    to_port = 0<br>    protocol = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>   }<br>  tags = {<br>    Name = &quot;allow_http_ssh&quot;<br>  }<br>}</pre><p>We need a key pair to SSH in the EC2 instance, so I used one that I had already created using the Terraform data source:</p><pre>data &quot;aws_key_pair&quot; &quot;ec2_instance_key_pair&quot; {<br>  key_name = &quot;ec2-instances&quot;<br>}</pre><p>You could create a new key pair using the <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/key_pair">aws_key_pair resource</a>.</p><p>Next, we will create an EC2 instance — I’ll install and set up nginx on this instance as user data. That’s the script that runs after the instance starts.</p><pre>resource &quot;aws_instance&quot; &quot;port_forwarding_server&quot; {<br>  ami = &quot;ami-06bb074d1e196d0d4&quot;<br>  instance_type = &quot;t2.micro&quot;<br>  key_name = data.aws_key_pair.ec2_instance_key_pair.key_name<br>  vpc_security_group_ids = [aws_security_group.allow_http_ssh_and_http_on_80.id]<br>  user_data = &lt;&lt;EOF<br>    #!/bin/bash<br>    echo &quot;installing nginx&quot;<br>    sudo amazon-linux-extras install nginx1 -y<br>    echo &quot;updating nginx config for reverse proxy&quot;<br>    echo &quot;<br>      user nginx;<br>      worker_processes auto;<br>      include /usr/share/nginx/modules/*.conf;<br>      events {<br>        worker_connections 1024;<br>      }<br>      http {<br>        sendfile on;<br>        tcp_nopush on;<br>        tcp_nodelay on;<br>        keepalive_timeout 65;<br>        types_hash_max_size 2048;<br>        error_log /dev/null;<br>        access_log /dev/null;<br>        include /etc/nginx/mime.types;<br>        default_type application/octet-stream;<br>        upstream express_server {<br>          server 127.0.0.1:8080;<br>          keepalive 64;<br>        }<br>        server {<br>          listen 80 default_server;<br>          listen [::]:80 default_server;<br>          server_name _;<br>          location / {<br>          proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;<br>          proxy_set_header X-Real-IP \$remote_addr;<br>          proxy_set_header Host \$http_host;<br>          proxy_set_header Upgrade \$http_upgrade;<br>          proxy_set_header Connection &quot;upgrade&quot;;<br>          proxy_http_version 1.1;<br>          proxy_pass http://express_server/;<br>          proxy_redirect off;<br>          proxy_read_timeout 240s;<br>        }<br>      }<br>    }&quot; | sudo tee /etc/nginx/nginx.conf<br>  <br>  ## Starting Nginx Services<br>  sudo chkconfig nginx on<br>  sudo service nginx start<br>  sudo service nginx restart<br>EOF<br><br>tags = {<br>  Name = &quot;local-dev-tunneling-server&quot;<br>  }<br>}</pre><p>This server will receive requests on port 80 and forwards them to the localhost server on port 8080.</p><p>The only thing that’s left to do is to start your local app and start a remote ssh port forwarding session by running the following command:</p><pre>ssh -i ~/.ssh/ec2-instances.pem -R 8080:localhost:8080 ec2-user@&lt;public-ipv4-dns&gt;</pre><p>You can copy the instance Public IPv4 DNS from the AWS console.</p><p>Now we need to have the site secure with SSL/TLS. So we can either add a load balancer and associate it with a certificate from <a href="https://aws.amazon.com/certificate-manager">AWS ACM</a> or directly create a certificate on the instance. Let’s do the latter using OpenSSL.</p><ul><li>First, enable ingress access of HTTPS on port 443 on the security group</li></ul><pre>ingress {<br>  description = &quot;https&quot;<br>  from_port = 443<br>  to_port = 443<br>  protocol = &quot;tcp&quot;<br>  cidr_blocks = [<br>    &quot;0.0.0.0/0&quot;<br>  ]<br>}</pre><ul><li>Update the startup script to create the certificate and use it in the nginx config. Update the user_data tag in Terraform to:</li></ul><pre>user_data = &lt;&lt;EOF<br>  #!/bin/bash<br>  echo &quot;installing nginx&quot;<br>  sudo amazon-linux-extras install nginx1 -y<br>  echo &quot;create a cert&quot;<br>  sudo mkdir /etc/ssl/private<br>  sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/nginx-selfsigned.key -out /etc/ssl/certs/nginx-selfsigned.crt<br>  echo &quot;updating nginx config for reverse proxy&quot;<br>  echo &quot;<br>    user nginx;<br>    worker_processes auto;<br>    include /usr/share/nginx/modules/*.conf;<br>    events {<br>      worker_connections 1024;<br>    }<br>    http {<br>      sendfile on;<br>      tcp_nopush on;<br>      tcp_nodelay on;<br>      keepalive_timeout 65;<br>      types_hash_max_size 2048;<br>      error_log /dev/null;<br>      access_log /dev/null;<br>      include /etc/nginx/mime.types;<br>      default_type application/octet-stream;<br>      upstream express_server {<br>      server 127.0.0.1:8080;<br>      keepalive 64;<br>    }<br>    server {<br>      listen 80 default_server;<br>      listen [::]:80 default_server;<br>      listen 443 ssl;<br>      ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt;<br>      ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key;<br>      server_name _;<br>      location / {<br>        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;<br>        proxy_set_header X-Real-IP \$remote_addr;<br>        proxy_set_header Host \$http_host;<br>        proxy_set_header Upgrade \$http_upgrade;<br>        proxy_set_header Connection &quot;upgrade&quot;;<br>        proxy_http_version 1.1;<br>        proxy_pass http://express_server/;<br>        proxy_redirect off;<br>        proxy_read_timeout 240s;<br>      }<br>    }<br>  }&quot; | sudo tee /etc/nginx/nginx.conf<br><br>  ## Starting Nginx Services<br>  sudo chkconfig nginx on<br>  sudo service nginx start<br>  sudo service nginx restart<br>EOF</pre><p>Now navigate to the Public IPv4 DNS provided by EC2 in your browser, which should direct the user to your local app on HTTPS.</p><p>How could you further improve the experience? I’d like to hear your thoughts.</p><p>Thanks for reading this far. Did you like this article, and do you think others might find it useful? Feel free to share it on <a href="https://medium.com/twitter.com/intent/tweet?url=https%3A%2F%2Fmedium.com%2Fp%2Feda750569e&amp;text=Check%20this%20article%20by%20%40Alee_Haydar%20on%20how%20to%20securely%20expose%20your%20local%20app%20to%20the%20internet%20with%20AWS%20EC2%3A%20%F0%9F%91%89%20">Twitter</a> or <a href="https://www.linkedin.com/sharing/share-offsite/?url=https://medium.com/p/eda750569e">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eda750569e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to manage your AWS accounts?]]></title>
            <link>https://ali-haydar.medium.com/how-to-manage-your-aws-accounts-3e783668c0ce?source=rss-e2ba7ca4dbad------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e783668c0ce</guid>
            <dc:creator><![CDATA[Ali Haydar]]></dc:creator>
            <pubDate>Mon, 08 Aug 2022 23:29:49 GMT</pubDate>
            <atom:updated>2025-09-16T22:05:33.338Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>For more content like this, subscribe to my newsletter on Substack: </em><a href="https://techroom101.substack.com/">https://techroom101.substack.com/</a></blockquote><p>It is common to use multiple accounts in AWS to split up environments, group workloads based on the business function, or apply tighter security measures…</p><p>That’s a correct way to do it, but it comes with the pain and overhead of managing multiple AWS accounts. Should we create a user per account for each of our users? Should we set up a different payment method by account?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RuByJBhBHlfdMB7EqUmIFw.jpeg" /><figcaption>Photo by <a href="https://pixabay.com/users/qimono-1962238/">qimono</a> on <a href="https://pixabay.com/photos/doors-choices-choose-open-decision-1767563/">Pixabay</a></figcaption></figure><p>AWS solves this problem for us through “Organisations”. AWS organisations help govern and manage multiple AWS accounts from a centralised place, simplifying billing and configurations and making scaling your business effortless.</p><h3>How to create and configure your org?</h3><p>From one of your standard AWS accounts, you can create an “Organisation”. This makes that standard account the Organisation Management Account. You can only have a single Management Account in an organisation.</p><p>What about the rest of the accounts? You can invite them from the management account into the created organisation. This makes them “member” accounts (Note that these accounts need to accept the invitation).</p><p>The AWS organisation is hierarchical and is formed of an Administrative Root and one or more Organisational units. The Administrative root is the highest level container of the organisation (it contains AWS accounts and other containers). An Organisational Unit is a group of one or more AWS Accounts within your organisation. For example, you might choose to have 2 Prod accounts to separate the infrastructure of 2 entities within your product but would want to only keep one for Staging and one for Dev. One way to go about it is by creating 3 Organisational Units, one for Dev, one for Staging, and one for Prod. The latter contains 2 AWS accounts.</p><p>Below is one way to visualise the previous example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h5xP7mdID6By5OtH3mFiRg.png" /></figure><p>For our example, I will work with two existing accounts only, one the management account and the other the member account.</p><p>The terraform configuration would look as follows:</p><pre>resource &quot;aws_organizations_organization&quot; &quot;org&quot; {<br>  feature_set = &quot;ALL&quot;<br>}</pre><pre>resource &quot;aws_organizations_organizational_unit&quot; &quot;prod&quot; {<br>  name      = &quot;prod&quot;<br>  parent_id = aws_organizations_organization.org.roots[0].id<br>}</pre><p>Once you apply this Terraform, you would need to verify the root email of the management account.</p><p>Unfortunately, I did not find a way to invite an existing account to an organisational unit using Terraform. So I’ve done this manually from the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8savPoFA1E8hQX9SNLt3yA.png" /></figure><p>Once the invitation is accepted, select the account, click “Actions”, and move it under the “Prod” organisational unit.</p><p>Also, it is possible to create a new account from within an organisation. This would skip the invitation process.</p><p>We have an organisation, an organisational unit, and two accounts. What can we do next?</p><p>It’s time to solve the two problems we mentioned: setting up billing for each account, creating users and assigning roles per account.</p><h3>Consolidated Billing</h3><p>As simple as it sounds, the “consolidated billing” feature removes the billing from the member accounts and keeps only the billing on the management account. You will get a single bill covering the management and member accounts. Another benefit of using consolidated billing is that of possible discounts offered on the usage of certain services. This discount would now apply to the combination of the usage of these services within the accounts of the organisation.</p><p>Looking at the terraform code above, notice the feature_set key set to ALL. This includes the consolidated billing features. More information can be found at: <a href="https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_support-all-features.html">https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_support-all-features.html</a></p><h3>Users Creation</h3><p>With organisations in place, there is no need to create users in every account. Instead, we create a new AWS account to handle identity. Users access this account and switch roles to the other accounts as needed — assuming a role in the accessed account. This is especially great as it helps apply the <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege">Least Privilege</a> principle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c0hXUF7R_LOOfW7HdB7-sQ.png" /></figure><p>This involves more work than the consolidated billing, so here we go.</p><p>Apply the following config to create a new AWS account:</p><pre>resource &quot;aws_organizations_account&quot; &quot;identity_account&quot; {<br>  name  = &quot;identity&quot;<br>  email = &quot;yourEmail@email.com&quot;<br>}</pre><p>In the AWS console, under Organisations, note the ID of the newly created Identity account.</p><p><em>Prod Account</em></p><p>Now we need to log in to the Prod account we added to the organisation and create a role that the Identity account can assume. In the AWS Console in a new browser session:</p><ul><li>Navigate to IAM and create a new role as follows:</li><li>Enter the Identity account Id noted earlier.</li><li>In the second screen, select the policy we’d need to attach to this role. Select the Administrator Access policy</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vvJ53oiv8r7iG_IOACDAuQ.png" /></figure><ul><li>On the third screen, enter the role name and click Create Role (Note that the account created by AWS from within the organisation will automatically have this role created with the following name: OrganizationAccountAccessRole. Feel free to use that same name for the role we just created)</li></ul><p><em>Identity Account</em></p><p>Now you might wonder how I will log in to the Identity Account. We just created it from within the organisation, so there is no email and password to use 🤔</p><p>From within the management account we’re already logged in to, select the account name on the top right corner, and click “Switch role”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TRwhnHiMZm-lSeEDU2yIxQ.png" /></figure><p>Fill in the details, and you’re now inside the Identity Account — The Identity Account users will use this same method to navigate to the Prod Account. But there are a few tiny steps to finish.</p><p>In the Identity Account, create a User Group called Developers and assign to it this inline policy:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: {<br>        &quot;Effect&quot;: &quot;Allow&quot;,<br>        &quot;Action&quot;: &quot;sts:AssumeRole&quot;,<br>        &quot;Resource&quot;: &quot;arn:aws:iam::PROD_ACCOUNT_ID:role/OrganizationAccountAccessRole&quot;<br>    }<br>}</pre><p>Create a user and add it to that User Group. Users can switch roles to access the PROD account when they log in. Isn’t that fascinating?</p><p>All that’s left to do is tighten the permission given on the prod account role that is assumed to match the least privilege principle.</p><p>Of course, there are many improvements to add and many questions to answer. How can we create and apply my infrastructure as code? Would it still go directly to each account, or would it also go through role assumption? How would we switch roles when we log in from the command line?</p><p>I’d be keen to hear your thoughts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e783668c0ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do you keep a tidy Git commit history?]]></title>
            <link>https://ali-haydar.medium.com/do-you-keep-a-tidy-git-commit-history-26d4b669a83?source=rss-e2ba7ca4dbad------2</link>
            <guid isPermaLink="false">https://medium.com/p/26d4b669a83</guid>
            <category><![CDATA[releases]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ali Haydar]]></dc:creator>
            <pubDate>Thu, 23 Sep 2021 20:33:14 GMT</pubDate>
            <atom:updated>2021-09-23T21:47:19.499Z</atom:updated>
            <content:encoded><![CDATA[<p>Commits form one of the core concepts in git. They are snapshots of your branch at a certain point, recording your code changes. When you create a new commit, you usually add a message that describes your code changes. The commit messages are the logs of your changes.</p><p>In multiple instances, I have encountered unclear commit messages. This was frustrating, not just because of my slight obsession with quality and tidiness but also because I needed to urgently understand what was going on in this change to fix a production bug. Has this change caused the bug? Should I revert the change?</p><p>I just needed to review the project changes on other occasions, and I would appreciate clear, concise commit messages. Some of the messages I didn’t enjoy much included:</p><ul><li>Update</li><li>Problem</li><li>fixing Issue</li><li>Adding code</li><li>bug fixes</li></ul><p>Going through this type of commit message doesn’t help with anything. It might be better to allow empty commit messages instead (don’t do that).</p><p>As you can see, writing clean and tidy commit messages has lots of benefits, from enabling troubleshooting issues, reading the history, and potentially generating changelogs (I worked in teams that use the commit history to create release notes).</p><p>How can we maintain a tidy git commit history?</p><p>In this post, we will explore <a href="https://www.conventionalcommits.org/en/v1.0.0/">conventional commits</a> and <a href="https://github.com/commitizen/cz-cli">commitizen</a>, which would help create better commit messages that communicate the intention of the code changes to anyone reading them.</p><p>I’d like to note that even with these kinds of tools and conventions, it is still possible to write unclear messages (e.g. feat: add some code to the repo). However, these tools help in the formatting and constitute a gentle reminder that commits messages are important.</p><p><strong>Setup conventional commits</strong></p><p>According to the documentation, the conventional commit specification is a lightweight convention on top of the commit message that provides an easy set of rules for creating an explicit commit history, making it easier to write automated tools on top of it.</p><p>The convention suggests writing the commit message in the following format:</p><pre>&lt;type&gt;[optional scope]: &lt;description&gt;</pre><pre>[optional body]</pre><pre>[optional footer(s)]</pre><p>The type could be anything of your choice, depending on your project. For example, the type could be fix, feat, docs, test, ci.</p><p>In addition to the messages that show the intention of the commit, conventional commits relate directly to releases and [sematic versionning](https://semver.org/). The “fix” type commits should be translated to PATCH releases, “feat” type commits should be translated to MINOR releases, commits with BREAKING CHANGE in the commits, regardless of type, should be translated to MAJOR releases.</p><p>Let’s try these out on an actual project.</p><ul><li>Create a GitHub repository and clone it to your local</li><li>Create a single js file that we will use to make changes. Create a main.js file and enter: console.log(‘first line’)</li></ul><p>We will install [Commitizen](https://github.com/commitizen/cz-cli), a node.js tool, to create commit messages following the conventional commits specs.</p><ul><li>Run npm i commitizen -g</li><li>Initialize your project to use cz-conventional-changelog adapter: commitizen init cz-conventional-changelog ——save-dev ——save-exact. Notice a config section got added to your package.json file.</li><li>Now, let’s stage our changes and create our first commit: git add, then git cz (notice we are not using git commit here, git cz will handle the commit under the hood). We will get prompted as follows:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EKJch_Tec4UCASeItwG6Sg.png" /></figure><p>* The second question asks about the scope of the change (depending on your project, the scope could be a file or module). Skip by pressing enter</p><p>* The third step would ask to enter a short description. For example: create a blog post about conventional commits</p><p>* The next question asked to enter a longer description optionally. Press enter to skip</p><p>* Afterwards, there is a question if that’s a breaking change. Enter N</p><p>* If you use a system like Jira and have an issue ID you’d want, the following questions supports this</p><p>After you press enter, the new commit will be created. Type git log to check how this commit message looks like:</p><pre>feat: create a blog post about conventional commits</pre><p>Add another change to your main.js file, then try to commit it in the traditional manner: git commit -m ‘some updates. Notice the error: error: pathspec ‘some updates&#39; did not match any file(s) known to git.</p><p>Without using commitizen, try to enter a commit according to the convention: git commit -m ‘feat: add a new line to test conventional commits. The commit works well in this case, but as you’ve already noticed, commitizen makes it easier for us to enter the right message with the necessary details.</p><p>In our example, we used the cz-conventional-changelog library default rules. However, these can be updated according to your team’s needs.</p><p>Would this process enforce writing clean commit messages? Of course not, but it’s a first step towards writing a tidy commit history.</p><p>I hope this was helpful. Let me know your thoughts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26d4b669a83" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>