<?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 Connor Butch on Medium]]></title>
        <description><![CDATA[Stories by Connor Butch on Medium]]></description>
        <link>https://medium.com/@connorbutch?source=rss-efbfc5b6ca1f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Jfe-t80NDjo9ZkmD4X4DzA@2x.jpeg</url>
            <title>Stories by Connor Butch on Medium</title>
            <link>https://medium.com/@connorbutch?source=rss-efbfc5b6ca1f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:24:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@connorbutch/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[Avoid this incredibly common aws sqs mistake]]></title>
            <link>https://medium.com/@connorbutch/avoid-this-incredibly-common-aws-sqs-mistake-f5b9e0311e59?source=rss-efbfc5b6ca1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5b9e0311e59</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws-sqs]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Connor Butch]]></dc:creator>
            <pubDate>Mon, 24 Oct 2022 12:31:42 GMT</pubDate>
            <atom:updated>2022-10-24T12:31:42.418Z</atom:updated>
            <content:encoded><![CDATA[<p>How to help lower costs, save engineer time, and speed up processing time by using this easy to implement sqs technique</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*5jMwwIRWRtzaOsIc.jpg" /><figcaption>avoid stumbling with your lambda + sqs implementation (<a href="https://thumbs.dreamstime.com/b/boy-was-stumbling-rock-cartoon-character-man-women-girl-164821851.jpg">src</a>)</figcaption></figure><p>As always, you can skip to the code used in the example, found <a href="https://gitlab.com/connorbutch/proper-sqs-error-handling">here</a></p><h3>Overview</h3><p>Amazon Simple Queue Service (commonly referred to as sqs) is one of AWS’s first services, launched in 2004. It provides a managed queuing service that frees users from needing to provision, scale, and patch hardware/os for a queuing solution. It can handle, “<a href="https://aws.amazon.com/sqs/features/">a nearly unlimited number of transactions per second</a>” number of messages sent and received per second, and it will durably persist them for processing <a href="https://aws.amazon.com/sqs/faqs/">for a configurable period (up to 14 days</a>). Because of these features, it is used by <a href="https://medium.com/theleanprogrammer/aws-sqs-service-6f1ecea50af3">hundreds of large companies</a>, and Amazon acknowledges it is a fundamental building block of many of it’s own critical business functions. Yet in spite of this wide adoption and usage, many teams do not entirely understand how sqs works (especially when paired with aws lambda) and often times write their code in a way that wastes money, decreases the effectiveness of metrics, and causes delays in processing time for end users.</p><p>This article will help users to improve on these problems. In order to do this, it starts by giving some background on how lambda and sqs work together under the hood. Then it shows two approaches to error handling in sqs, one that is common, and one that is less well-known, sends the same traffic to each queue, and concludes with a report on the associated metrics (cost, CPU time, number of messages sent to dlq, etc), which prove the second approach is more cost effective, requires less manual intervention, and fulfills customer promises quicker than the more commonly used technique.</p><h3>SQS + Lambda Internal Workings</h3><h4>Poller Fleet</h4><p>When sqs is used as an event source for aws lambda (usually done via an <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-eventsourcemapping.html">event source mapping in cloudformation</a>, or <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-function-sqs.html">an event in a sam template</a>), an AWS managed pool of compute, called a a “<a href="https://aws.amazon.com/blogs/compute/understanding-how-aws-lambda-scales-when-subscribed-to-amazon-sqs-queues/">poller fleet</a>” takes care of reading messages from the queue. This fleet constantly makes <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html">receiveMessage</a> api calls to the queue (passing the configured parameters such as MaxNumberOfMessages in the request), usually keeping the connection open until messages are received (in a technique called <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html#sqs-long-polling">long-polling</a>), however, the poller fleet can be configured to to use short-polling instead.</p><p>When the poller fleet receives a response containing messages to be processed (at which point, the sqs system will make the messages unable to be received again until the <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html">visibility timeout</a> expires), it synchronously invokes the lambda, using the messages received from the queue as the payload . This invocation sends the messages as a batch in a single invocation of the lambda function (where the batch size is configurable as well). While it is possible to set the batch size to one, which makes the rest of this article irrelevant,<em> I would not recommend it</em>, as batching has many benefits:</p><ul><li>reducing cost by reducing the number of lambda invocations</li><li>reducing cost by reducing the number of receiveMessage calls to the queue</li><li>running less lambda instances concurrently (keep in mind there is a limit on the max number of lambda instances that can be running across an account at once — the default being 1000)</li></ul><h4>Potential Outcomes For Processing Lambda</h4><p>Broadly speaking there are three outcomes for lambda executions, the last two of which are treated the same by the poller fleet</p><ul><li>it can succeed (return without throwing an exception)</li><li>it can fail (throw an exception),</li><li>it can timeout (not return or throw an exception within the configured timeout)</li></ul><p>If an sqs-triggered lambda returns a value (without the configuration options specified in the improved solution below), the poller fleet takes care of deleting the entire batch of messages sent to the lambda from the sqs queue. However, if an exception is thrown or the lambda times out, the poller fleet does nothing, and <strong>all of the messages</strong> <strong>in that batch </strong>remain in the queue. This means once their visibility timeout has expired, they are eligible to be received by subsequent receiveMessage calls.</p><p>The next time these messages are received by the poller fleet, there are a couple of different ways they can be treated. If there is no dead letter queue (dlq) configured (which is a bad idea except for very few scenarios which I outline in <em>special considerations</em> section), the messages will remain in the queue, and will keep being received and waste processing power until their <a href="https://aws.amazon.com/sqs/faqs/">retention period expires</a> and they are deleted.</p><p>Assuming this queue has a <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html">dead letter queue</a> (dlq) configured (you should pretty much always have a dlq configured), upon receiving a message, the message’s <em>ApproximateReceiveCount</em> attribute is checked. If the value is less than the specified <em>MaxReceiveCount</em> specified for the queue’s <a href="https://awslabs.github.io/serverless-rules/rules/sqs/redrive_policy/">redrive policy</a>, then this message is again sent to the lambda for processing. (Note that this means messages can, and often are, received more than once, so lambda processing logic<a href="https://aws.amazon.com/blogs/compute/handling-lambda-functions-idempotency-with-aws-lambda-powertools/"> <strong>must be idempotent</strong></a><strong>)</strong>. If this message has been received more than the maximum allowed amount of times, then the items are routed to the dlq without being used to invoke the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wkzVM8qFZ4rGf26-HHek6Q.png" /><figcaption>You can see this message has been received three times (Receive count column on far right)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s3VV66VWByc0LsoclILNXA.png" /><figcaption>You can see here this queue will allow messages to be received five times before routing them to its dlq</figcaption></figure><h3>Why to minimize items sent to dlq</h3><p>Sending items to a dlq has negative consequences, and hence you should try to only send messages that cannot be processed at all (after a few retries) to a dlq. Some of these negative impacts include:</p><ul><li>raises cost, as it requires additional api calls to sqs and additional storage/retention.</li><li>It also inconveniences the customer, as it adds delays to processing time.</li><li>It also takes time away from your engineers, as they must now spend time redriving messages, which raises cost (as engineers cost hundreds of dollars per hour)</li></ul><p><strong>Because of the above-listed consequences, you should try to reduce the number of messages sent to the dlq and only route messages that cannot be processed due to code errors to the dlq.</strong></p><h3>The Problematic Design</h3><p>Often times I see lambdas that process sqs messages that throw an exception the first time they cannot process a message. An example of this poor design is included below, as well as <a href="https://gitlab.com/connorbutch/proper-sqs-error-handling/-/blob/main/BadExampleSqsProcessorLambda/src/main/java/com/connor/sqs/example/BadExampleRequestHandlerSqsImpl.java">here</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/606a4bd8c69ac0f493814e680503723b/href">https://medium.com/media/606a4bd8c69ac0f493814e680503723b/href</a></iframe><p>Why is this a poor design? Let’s consider a real world example where this lambda receives a batch of 50 valid messages (sqs can batch up to 10,000 messages at a time), the first 49 of which could be processed successfully, but our code has a bug and throws an exception when processing the final message (let’s pretend our code handles dates, but forgets to take into account that February 29 is a valid date during leap years). In this case, how many messages will the sqs poller fleet view as “successfully processed”? <strong>Zero</strong>. The consequence of this is that all 50 messages will remain in the queue, and will be reprocessed. <strong>We wasted 95% of our compute cost by not deleting the messages we successfully processed</strong>.</p><p>Even worse, the next time a batch is received, it is likely that at least a few of the messages we successfully processed are received in a group with the message that results in a runtime error, which will result in us wasting processing time again. If this happens enough, all of the messages, even the 95% of them that we successfully processed (and in fact, processed multiple times) will be routed to our dlq.</p><p>This also wreaks havoc on our cloudwatch metrics. Our lambda error rate will show 100%, even though in reality, we could successfully process 95% of the messages. The age of the oldest message in the queue will continue to increase, as we believe we could not process any messages (even though we actually did successfully process a message); and the number of messages sent to our dlq will be much higher than the number of messages we actually couldn’t process. Then redriving will take much longer, as we need to reprocess items that actually succeeded the first time. Overall, a pretty messy scenario that we should try to avoid. The metrics from a deployed solution containing this erroneous processing technique can be found in the <em>Comparison Of Approaches</em> section below.</p><h3>The Solution</h3><p>Essentially, we need a way to delete successfully processed messages from sqs while leaving the errored messages in the queue. In the past, the lambda used to have to do this inside the function code (keep track of messages which were successfully processed, then make a batch delete call at the end — using batch delete preferred over individual deletions as it saves money at scale by reducing api calls). This required extra code, or the adoption of a framework, such as <a href="https://awslabs.github.io/aws-lambda-powertools-python/latest/">aws powertools for lambda</a>.</p><p>However, in late 2021 aws released a feature called <a href="https://aws.amazon.com/about-aws/whats-new/2021/11/aws-lambda-partial-batch-response-sqs-event-source/">partialBatchResponse</a>. This feature allows us to return the ids of failed messages from our lambda to the invoking poller fleet, which then takes care of deleting the successfully processed messages, while leaving the messages that errored out on the queue to be received again (and potentially routed to the dlq after a given number of failed processing attempts). Find a simple example of this below as well as <a href="https://gitlab.com/connorbutch/proper-sqs-error-handling/-/blob/main/SqsProcessorLambda/src/main/java/com/connor/sqs/example/RequestHandlerSqsImpl.java">here</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b68934c61da7d55ea5fc0c5e6451ae7/href">https://medium.com/media/5b68934c61da7d55ea5fc0c5e6451ae7/href</a></iframe><h4>Nuanced Implementation Details</h4><p>There are a few nuances I’d like to make with this approach:</p><ul><li>when code catches an exception, <strong>it MUST log it to get the stack trace</strong> (and add it to x-ray if desired) — if it does not do this, when you go to diagnose why a particular message failed, you will have zero context on what went wrong</li><li>you could always include a client-side retry (assuming operation is idempotent) before to mitigate transient failures</li><li>while you could emit metrics for number of messages processed vs failed — you can always get close to this based on number of messages received vs deleted which comes with sqs (along with dlq messages sent)</li></ul><h3>Deploying The Stack</h3><p>You can deploy the stack and execute tests for yourself as well</p><p>clone the repo</p><pre>git clone <a href="mailto:git@gitlab.com">git@gitlab.com</a>:connorbutch/proper-sqs-error-handling.git</pre><p>deploy the stack</p><pre>sam build &amp;&amp; sam deploy --guided</pre><p>Then simply click the url output by the sam deploy command to send the same ten messages to each sqs queue (this is also shown in a below video as well).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*380E4mX17X5ObSWxmtW7uQ.png" /><figcaption>here is an example url output — note that this is unique to my stack and yours will be different</figcaption></figure><h3>Comparison of Approaches</h3><p>To provide numeric data on these varying approaches, I’ve created a simple <a href="https://aws.amazon.com/cloudformation/">cloudformation</a> stack with one lambda using the “incorrect” processing technique (throwing an exception whenever it errors without catching them) and one lambda using the improved approach (try/catch the processing for each individual message, recording failed message ids and the stack trace, then at the end returning the failed message ids). To keep the example simple, I throw an exception when the message body is the number “1”. However, in your code this could occur from any number of application code errors, such as a a <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html">NullPointerException</a>, or not handling February 29th on a leap year.</p><p>To generate the same messages in both sqs queues at around the same time, I’ve included a lambda fronted by a simple get request to api gateway. This lambda generates the same ten sqs messages, where the body of each message is an integer from 1–10 (inclusive). It then sends this batch of messages to both queues mentioned above (which results in both queues getting the same messages) and returns a 200.</p><p>To trigger this workflow, I then make five <a href="https://www.w3schools.com/tags/ref_httpmethods.asp">GET requests</a> to the lambda by simply clicking the output url, which will send fifty messages to each queue. We let the messages be processed (and reprocessed) until there are no messages left in either source queue. We then we inspect the number of messages in each dlq.</p><p>Keep in mind that there are only five messages (out of fifty total) that cannot be processed, so any messages beyond those five in the dlqs represent additional cost and poor customer experience. You can see this process in the below video. In the video I click the url five times, and then go to sqs page to see the messages being processed. Note that for the “good” queue the messages in flight quickly drops to five with no messages going to the dlq; while there are 33 messages still “in flight” for the bad queue. I cut off the end of the video for brevity, but I waited until all messages had been deleted from both of the original queues (either being successfully processed, or ending up in the respective dlq), and <em>you can see those stats in the results section right below.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*bAlu4cDBBq2x6e1kvWt3_A.gif" /><figcaption>this shows generating traffic in the queues, as well as shows the progress of processing between both queues</figcaption></figure><h3>Results</h3><p>Let’s take a look at the results below, keeping in mind there were only 5 messages that result in application code errors. The lambda that handled sqs messages improperly had 17 messages end up in the dlq, as opposed to the proper handling, which only had 5 messages end in the dlq. That means we had 240% increase in the number of successfully processed messages that ended up in the dlq.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dwqTRWxV7sQ6iQ0cl4oSpA.png" /><figcaption>In the end, the bad handling dlq ended up with ~71% of the messages in the dlq being messages we successfully processed (or could successfully process)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3OlmQETmTsElHZPaCuIkjQ.png" /><figcaption>The bad handling queue ended up with many more messages being received — driving up costs and causing more lambda invocations</figcaption></figure><h4>Metric Summary</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*ZhfJzZxLAlmG4nlvIH1m3A.png" /></figure><ul><li>less messages in dlq → less cost for messages sent, less cost for messages stored, more customer requests get processed successfully in a quicker manner</li><li>less messages received from original lambdas → less cost for lambda invocations, less cost for lambda runtime, etc (potentially less cost for data transfer as well)</li><li>less lambda invocations → less cost for lambda invokes</li></ul><h4>Important Caveat</h4><p>As mentioned earlier, proper sqs message handling causes your lambda error rate to be zero, so you can no longer alarm on it. Instead, alarm on any messages entering the dlq, or if the age of oldest message gets too high (that means the lambda is not processing messages quickly enough). In contrast, the improper handling lambda (shown below) does emit error metrics to cloudwatch</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*3gGrYi_i5sN1DcESkuwEGA.png" /><figcaption>The error rate for the improper handling lambda will be non-zero, unlike the proper handling lambda</figcaption></figure><h3>Conclusion</h3><p>In summary, we’ve seen that although aws sqs is a widely adopted technology, there are many systems that pair it incorrectly with aws lambda. Many of these (I believe) result from not understanding how lambda works with sqs, which we detail in the first part of this paper. The paper then progresses to present an improved solution that surrounds the processing of each sqs message in the batch with a try/catch block. Inside the try, we attempt to process the message, and inside the catch block we catch the exception, log the stack trace, and add the sqs message id to the list of failed message identifiers. At the end of the function, we return this list of failed message ids. This change, along with specifying the function return types in our cloudformation template signifies to the poller fleet to delete the messages we successfully processed. This decreased the number of messages in our dlq (exact stats can be seen above), saving us time and money, even at a small scale (and the savings will be greater the larger the number of messages your system processes). Hope this helps you improve your processing of sqs messages inside of aws lambda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*3Nkl7xhci6_usfdz.png" /></figure><h3>Special Considerations</h3><h4>Time sensitive messages which durability is not a concern</h4><p>There are a few special situations which merit an addendum. The first is where processing messages is time sensitive, and there is no point processing messages after a certain time frame; you would rather just discard them when they expire. While this is usually time-sensitive processing better fit for <a href="https://aws.amazon.com/kinesis/">kinesis</a> as a streaming solution as opposed to sqs, sometimes systems might use sqs. In this case, I would configure a very small retentionPeriod on my queue (say maybe 90 seconds), which would cause messages to only remain in the queue for around a minute and a half before being deleted. For these types of situations, a dlq is not needed.</p><h4>When ordering matters</h4><p>The second special consideration here (as mentioned previously) is around in order processing, implemented using a <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html">FIFO (First In First Out) sqs queue</a>. If you require messages to be processed in a certain order, you should not continue processing after an error is encountered, as this can lead to messages being processed out of order. Instead, you should throw an exception immediately. While I have not worked with FIFO queues enough personally to know if message processing pauses when an item enters a dlq, I know that this is an aws recommend best practice (if you have more information about FIFO queue error handling, please do let me know in the comments 😉)</p><h3>Related Links</h3><p><a href="https://gitlab.com/connorbutch/proper-sqs-error-handling">Connor Butch / proper-sqs-error-handling · GitLab</a></p><h3>Further Reading</h3><ul><li><a href="https://aws.amazon.com/blogs/compute/understanding-how-aws-lambda-scales-when-subscribed-to-amazon-sqs-queues/">Understanding how AWS Lambda scales with Amazon SQS standard queues | Amazon Web Services</a></li><li><a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html">ReceiveMessage</a></li><li><a href="https://aws.amazon.com/sqs/faqs/">Amazon SQS FAQs | Message Queuing Service | AWS</a></li></ul><h3>Cost Evaluation</h3><p>All of the technologies used within this project fall well <strong>within the free tier</strong>, so no need to worry about paying a dime for them. As always, you can delete the resources to clean up the look and feel of your aws account as specified above.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5b9e0311e59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Api Gateway Service Integrations Are Cool, But Should You Really Use Them?]]></title>
            <link>https://medium.com/@connorbutch/api-gateway-service-integrations-are-cool-but-should-you-really-use-them-f6f565ffcf84?source=rss-efbfc5b6ca1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6f565ffcf84</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[sns]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Connor Butch]]></dc:creator>
            <pubDate>Tue, 14 Jun 2022 11:03:26 GMT</pubDate>
            <atom:updated>2022-06-14T11:03:26.020Z</atom:updated>
            <content:encoded><![CDATA[<p>Comparing <em>Api gateway -&gt; lambda -&gt; sns</em> with <em>Api gateway -&gt; sns</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*OV3lHvvHbZxFLqLK.png" /><figcaption>service integrations are powerful, but that doesn’t mean you should always use them (<a href="https://static.tvtropes.org/pmwiki/pub/images/the_dumb_hulk_by_gauntnoir-d302bot_887.png">src</a>)</figcaption></figure><p><em>As always, you can jump to the code for this article by going </em><a href="https://gitlab.com/connorbutch/profile-service">here</a></p><h3>The Power of Api Gateway</h3><p><a href="https://aws.amazon.com/api-gateway/">AWS Api Gateway</a> is extremely powerful. You don’t have to manage any infrastructure (i.e. no purchasing, scaling, patching), it is capable of <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html">handling tens of thousands of requests per second,</a> and you only pay a very small price based on the number of requests served . In addition, it also provides many other functionalities, such as <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api.html">managed websocket support</a>.</p><p>One of these lesser-known, but potentially very useful, functionalities of API Gateway is its <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-aws-services.html">service integrations</a>, which give you the ability to connect api gateway directly to other AWS services, such as dynamodb, sqs, step functions or sns (not just lambda). While this seemed like a cool feature, there are a few nuances you must be aware of before you choose to use these techniques. This article seeks to make you aware of these nuances by showing code examples of the same functionality implemented with api gateway -&gt; sns and api gateway -&gt; lambda -&gt; sns, and by offering my perceived pros and cons of each approach. Finally, this article will conclude with specific recommendations on when to utilize each architecture.</p><p><em>NOTE: the ideas shown here for sns apply to integrating api gateway directly with other non-compute services as well, such as s3, dynamodb, sqs, etc</em></p><h3>Business Use Case: Update Profile Information (name)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*km4ozqASfWZ-cGnuOeylXA.png" /><figcaption>Here is what a medium profile looks like, for thise of you without an account</figcaption></figure><p>Let’s pretend we are running a profile service for a site like medium. For the sake of our simple demo, we will say a profile will be defined by the following fields (pictured using <a href="https://gitlab.com/connorbutch/profile-service/-/blob/main/apigw-lambda-sns/openapi-spec.yaml">this particular open api spec</a> on <a href="https://editor.swagger.io/">swagger editor</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ombOLu2STk8PcPhqLpEkFQ.png" /></figure><h3>Design Choices</h3><p>We could choose to implement this functionality many different ways. Two of the possible designs are described below</p><h4>Design One: Api gateway (with request validator) -&gt; sns</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*sSO22OJhvQa_kGV4S94BQA.png" /><figcaption>Note that there is no lambda present in this architecture</figcaption></figure><p>With this approach, we specify that we want api gateway to perform validation for us, which uses the information available in the open api specification to validate the incoming request. If the request meets these requirements, then it goes directly from api gateway to the sns topic (without invoking a lambda).</p><p>The folder containing all of the project code including the sam template that provisions this architecture can be found <a href="https://gitlab.com/connorbutch/profile-service/-/blob/main/apigw-sns/template.yaml">here</a>, and the sam template content is shown below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4038a34c93dff9f37f6d9ee7bf04bfe9/href">https://medium.com/media/4038a34c93dff9f37f6d9ee7bf04bfe9/href</a></iframe><p>I’ve evaluated this design using the most relevant parts of the six pillars of the <a href="https://aws.amazon.com/blogs/apn/the-6-pillars-of-the-aws-well-architected-framework/">aws well-architected framework</a>, and I’ve listed the perceived benefits of this approach (when compared to using a lambda integration)</p><p>reliability</p><ul><li>if this is an extremely high volume service, removing lambda as the middle man can keep some concurrency for other functions in your account</li></ul><p>cost optimization</p><ul><li>you no longer pay for lambda to execute</li></ul><p>performance efficiency</p><ul><li>this can be ever so slightly faster at p50 and p90 latency (but p99 can be higher)</li></ul><p>However, there are a lot of negatives/nuances to be aware of with this approach</p><ul><li>request/response mapping now has an aws/iac specific code —this means the learning curve is higher, fixing issues is harder, and finding talent that has this skillset is harder when compared to “regular” code (say javascript, python, java, etc)</li><li>you are limited to simple validation based on open api spec— some validation is not possible to be declared in the open api spec(consider if you must ensure username does not contain profanity)</li><li>this might tempt you to use enums in open api spec, however, this will break strongly-typed generated clients if they must handle a type they don’t recognize</li><li>you are now mixing open api spec in with your template — in my personal opinion, this violates SOLID engineering principles; if you don’t include the open api definition in the template, the stack won’t launch (as it won’t pick up any routes)</li><li>you can’t use values from the request body in the response body — this makes it harder to return a “standard” response (where response body is essentially the same as the request body)</li><li>can’t generate correlation id for tracking in cloudwatch logs insights, x-ray, etc (yes, you could return sns message id as correlation id, but downstream components won’t treat it as correlation id)</li><li>the error messages from the api gateway validation are not user-friendly; they don’t specify which field is invalid and why it is rejected (for a comparison, see the Contrasting Error Responses section)</li></ul><h4>Design Two: Api gateway -&gt; lambda -&gt; middleware (i.e. sns)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*GD-ueHpytM2s8mhdla7Dlw.png" /><figcaption>Here is our architecture, this time using a lambda to validate</figcaption></figure><p>With this approach, api gateway triggers a (nodejs) lambda, which performs validation, and if the request is valid, it publishes an event to the sns topic.</p><p>The folder containing all of the project code including the sam template that provisions this architecture can be found <a href="https://gitlab.com/connorbutch/profile-service/-/blob/main/apigw-lambda-sns/template.yaml">here</a>, and the contents can content is shown below (note, you should also look at the open api spec, which is in a separate file for this approach)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e8c3be530ab8a5223c9fb2a51266ec8/href">https://medium.com/media/0e8c3be530ab8a5223c9fb2a51266ec8/href</a></iframe><p>Here is the evaluation of this design using the six pillars</p><p><strong>reliability</strong></p><ul><li>we can do more complex validation in lambda — this means we can do more validation before publishing an event</li></ul><p>cost optimization</p><ul><li>less repeatedly failed requests—since api gateway validation does not give indicative error messages, as well as it short-circuits on the first error, users will often end up making multiple requests before sending a valid request (see Contrasting Error Responses section)</li></ul><p><em>NOTE: this could accrue negligibly more cost than api gateway directly to lambda, but this is likely only a few cents per month. You refer to the Cost Evaluation section for more analysis.</em></p><p><em>NOTE: this could end up having negligibly more latency, but both architectures have a p99 latency of under 300ms, so this shouldn’t be a concern. For more information, refer to the Latency Comparison section.</em></p><h3>Recommendations</h3><p>Now that we’ve seen a simple example of both architectures, I’ll proceed to give my recommendations.</p><p><strong>My default is to use api gateway -&gt; lambda -&gt; middleware </strong>(i.e. sns). While this architecture might incur slightly more cost, I believe a few cents per month is negligible to most companies, and similarly, while it might incur slightly more overhead, the p99 latency is still under 300ms, and the benefits given by this solution outweigh these slight drawbacks. Some of these benefits include the flexibility of doing custom (or more complex) validation, the saving of engineer’s time, as they can use whatever language they like within aws lambda instead of learning how to transform requests using apache templates in cloudformation, as well as the ability to provide clients with more helpful error messages, as well as all error messages at once (this saves them from getting frustrated and leaving our site, or at least saves us from them making multiple calls). The one drawback to watch out for is if this lambda is called frequently and it ends up consuming a lot of concurrency in my account, there are various solutions we can use to mitigate the impact of this:</p><ol><li>make sure most functions are triggered asynchronously, so that they can be retried when throttled</li><li>request an increase on the concurrency limit on your account</li><li>if needed, you can play around with reserved concurrency for lambdas, but I prefer to avoid this where I can</li></ol><p><em>The only time I recommend using an api gateway direct service integration is if I this api is extremely high traffic and I am super concerned about saving a few dollars, or I am constantly seeing throttles on synchronously invoked functions which I cannot make asynchronous and I cannot request a concurrency increase, while having only simple validation required on the input.</em></p><h3>Related Links</h3><p><a href="https://gitlab.com/connorbutch/profile-service">Connor Butch / profile-service · GitLab</a></p><h3>Further Reading</h3><ul><li><a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-aws-services.html">Working with AWS service integrations for HTTP APIs</a></li><li><a href="https://aws.amazon.com/serverless/sam/">Simplify Serverless - AWS Serverless Application Model - AWS</a></li><li><a href="https://editor.swagger.io/">SwaggerEditor</a></li><li><a href="https://www.artillery.io/">Artillery · The Complete Load Testing Platform</a></li></ul><h3>Contrasting Error Responses</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cDzzy8V_ptMKMwCRD541PA.png" /><figcaption>This is the error from the api gateway validation. Note that it does not specify which fields are incorrect, and how to fix them. It also does not indicate I actually made two mistakes (FirstName should be firstName and the username is too long)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s43l2nZteYc_ujLwvJ9DuQ.png" /><figcaption>This is the error response from our lambda. Notice it provides multiple errors in one response, and it specifies the exact field in error and why it is incorrect.</figcaption></figure><p>The first image shows the error response from the api gateway. While it returns a 400, it doesn’t tell you what field is invalid, and why it is not accepted. Is my body supposed to be xml instead of json? Is the firstName field supposed to be FirstName? Did I put an extra quote somewhere? Is my lastName field too short? There are all sorts of possibilities, and this error does not help me much.</p><p>Contrast this with the second error message (the one we generate from our lambda). This tells us exactly what went wrong and how to fix it (note that here it provides the min and max, not just that it is outside of the range). This can be easily displayed on our front end to help users fix their request and resubmit the form. Note that if there are</p><h3>Latency Comparison</h3><p>I always like to have some metrics when making a design decision (before I release a system to even a small percentage of customers), and we then continue to monitor these metrics via weekly operations meetings in which we review our dashboards, as well as via alarms.</p><p>In order to get a cursory glance into performance, I set up some quick artillery load tests that run against each endpoint, the apigateway -&gt; lambda -&gt; sns and the apigateway -&gt; sns. In order to execute the load tests, run either of the following commands (depending on which endpoint you want to drive traffic against). You need to run each command at least once</p><p>To drive traffic against apigateway -&gt; lambda -&gt; sns, use the following (after cd into the load-test directory):</p><pre>npm run lambdaArtillery</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k6f0nCf1YP6F1hX3x2efFQ.png" /><figcaption>this is the response times for my quick load test using a lambda between api gateway and sns — shows the max response time was still under 700ms and p99 was at 507 ms (and the median was 110ms)</figcaption></figure><p>To drive traffic against apigateway -&gt; sns, use the following:</p><pre>npm run directToSnsArtillery</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WwW4_Fj4p8KITFxMwTtOCA.png" /><figcaption>Notice the max latency for api gateway -&gt; sns (898ms) is actually higher than the max latency of apigatewateway -&gt; lambda sns (647ms) and the p99 was slightly less at 285ms</figcaption></figure><p>For both the api gateway and direct to lambda, the p99 latency was below 510ms, which is perfectly acceptable. Hence, I don’t believe introducing a lambda between api gateway and sns adds anything but negligible latency increases.</p><p><em>NOTE: you can look at the cloudwatch metrics yourself, I feel the artillery metrics give a good representation and didn’t want to make this lengthier than it already is</em></p><h3>Cost Evaluation</h3><p>The extra costs for implementing a lambda in between api gateway and sns can be calculated using the following costs:</p><p>NOTE: this doesn’t take into costs that are the same between the two designs</p><ul><li>lambda invoke costs (total requests — 1,000,000*.2/1,000,000) — say someone updates their profile every five minutes — that is 8761 per month — well within free tier</li><li>lambda runtime costs ($0.0000000017/ms * 175 ms mean runtime * 8761 invocations per month) —this would cost more than $.01 per month ($0.0026063975) to be exact — and this is likely an overestimate, as this uses latency measured from response time, which includes network latency and api gateway latency as well</li></ul><p>The extra costs for not implementing a lambda can be calculated based on the additional time taken for an engineer and the engineer’s hourly cost:</p><ul><li>engineer hourly rate (midwest) = 125,000 base + 25,000 bonus + 50,000 extra costs (healthcare, unemployment, etc) = 200,000 / (40 hours/week * 50 weeks per year) = $100/hr</li><li>say it takes an engineer an extra four hours to hook up api gateway -&gt; sns instead of lambda and three hours anytime they need to make a change = $400</li></ul><p>So realistically, I would argue that not using lambda for most applications is actually more expensive, since it likely consumes a few extra hours of engineer time versus using sam/cdk, which make creating an extra lambda minimal work. Doing the math on how many times your function could be invoked before equaling a few hours of an engineer’s time (and assuming lambda mean execution time at 128mb is 175ms), we see:</p><p>$400 = $0.0000000017/ms * 175ms/execution * numExecutions + (numExecutions — 1000000) * 0.2/1000000</p><p>400 = .0000002975 * numExecutions + .00000002*numExecutions — 1</p><p>401 = .0000002977 * numExecutions</p><p>1346993617 = numExecutions</p><p><strong><em>This lambda could get invoked every minute for 2562 years before equaling a few hours of engineer time</em></strong> (even if I’m off by a few decimal places, it’s still way cheaper to run a lambda than to pay an engineer for a few hours)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6f565ffcf84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Structured Logging In AWS]]></title>
            <link>https://medium.com/@connorbutch/how-to-implement-structured-logging-in-aws-fc3f80929750?source=rss-efbfc5b6ca1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc3f80929750</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Connor Butch]]></dc:creator>
            <pubDate>Mon, 06 Jun 2022 11:34:04 GMT</pubDate>
            <atom:updated>2022-06-06T11:34:04.377Z</atom:updated>
            <content:encoded><![CDATA[<p>Using lambda, cloudwatch, java, lambda layers, lo4j2 and middleware to maximize the usefulness of your logs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dMKWko1crIeuhBRM.png" /><figcaption><a href="https://miro.medium.com/proxy/0*3lkihqOzUHg4wn7H.png">src</a></figcaption></figure><p><em>As always, you can jump to the code for this article by going</em> <a href="https://gitlab.com/connorbutch/cloudwatch-logs">here</a>.</p><p>This is a continuation of <a href="https://medium.com/@connorbutch/the-importance-of-structured-logging-in-aws-and-anywhere-else-52a4534c53aa">a previous article</a> where I demonstrated the utility of structured logging in AWS. In that article, I showed how to run various queries to gain insights into our “google search” application. These queries included: a search to find logs for a single request, a query to find logs for all failed requests, a query to find the minimum length of failed search requests (which we used to confirm our hypothesis that longer queries fail more frequently), and finally, a search to confirm the git commit hash of searches that ended in error, so we could match the stack trace to the exact line of code causing the error.</p><p>This article will show how to implement structured logging in order to be able to execute the queries described in the prior article. This structured logging will involve a few components: a lambda layer including</p><ul><li>a middleware module that routes requests and automatically adds key information (such as correlation id) to the thread context</li><li>log4j configuration file</li><li>a custom json schema for our log output</li><li>a lambda bringing in this layer and adding additional properties to the thread context</li></ul><h3>Deployment and Traffic Generation</h3><p>Start off by cloning the repo</p><pre>git clone <a href="mailto:git@gitlab.com">git@gitlab.com</a>:connorbutch/cloudwatch-logs.git</pre><p>Deploy the stack, run the following command</p><pre>sam build &amp;&amp; sam deploy --guided</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wPhi4sGP7aO9AB2tdBY-Xw.gif" /><figcaption>note: i ran the deploy without the — guided flag because I had already deployed previously. You will need the flag</figcaption></figure><p>Now let’s generate some traffic against the apis using <a href="http://gatling.io">gatling</a>. The default will generate a constant 50 users per second for 15 seconds. This will stay well within the free tier, but if you wish, you can see the addendum section of this article to see how to generate more or less load and the price points of various solutions. The default costs at most a few cents to run (if you aren’t in the free tier). You can see a video of this being executed in the first article.</p><pre>./gradlew gatlingRun</pre><h3>Ensuring Logging Format</h3><p>In order to enable the queries executed in the <a href="https://medium.com/@connorbutch/the-importance-of-structured-logging-in-aws-and-anywhere-else-52a4534c53aa">first article in the series</a>, the first thing every component must do upon receiving a request is to capture/generate the correlation/request id and to store them on the logging context. In order to prevent overlooking this, I would suggest <strong>baking this functionality into your middleware</strong> (be it something like aws lambda powertools, or a custom framework). This example includes a very simple middleware layer which sets up the thread context with correlation id and request id (as well as any custom values each lambda needs), deserializes and routes request to the appropriate method. <strong>The only important part of this class is the first few lines of the <em>handleRequest</em> method</strong> — you can ignore the rest of it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5562315d4b2a11a982a8726a84d9f6e4/href">https://medium.com/media/5562315d4b2a11a982a8726a84d9f6e4/href</a></iframe><p>This middleware then works in conjunction with a lambda layer (the layer’s implementation is specified below) to ensure structured logging and allowing teams to focus on purely business logic.</p><h3>Lambda Layer Implementation</h3><p>NOTE: for all the failed attempts,<em> I am intentionally NOT including the source code</em>, as to not confuse people on which format to use. If you want to see these examples, you can comment, or look through the repository’s commit history</p><h4>Failed attempt #1</h4><p>When I first tried to log in a structured format, I used my own <a href="https://logging.apache.org/log4j/2.x/manual/layouts.html">custom pattern layout</a>. I templatized this custom pattern layout to output the correlation id from the context object using the <em>${ctx:correlationId} </em>syntax<em> </em>(and request id and hash as well)<em>.</em> This works in conjunction with the java code where the correlationId is stored on the context in our java code (you can see this in the middleware shown above). However, this doesn’t allow for applications to add their own key-value pairs to the thread context, which is a fundamental requirement. Without this our search query application could not log the search query as a root level json; which would make many of our queries much harder (and in some cases, not possible at all). Hence, this is not viable option for our logging format. (and to avoid confusion, I have not included a code sample where I do this).</p><h4>Failed attempt #2</h4><p>After this, I realized log4j2 comes with a default json layout, and I switched to use it. While this improves upon the previous pattern layout by allowing applications to add custom values to the thread context, it includes unneeded information, such as threadId and threadPriority which makes debugging more difficult (threading in a lambda is usually an anti-pattern and shouldn’t be used). For reference, you can find a sample log output that this format emits below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0a0d12a2e0ec790c4f1bc76eabf99a5/href">https://medium.com/media/a0a0d12a2e0ec790c4f1bc76eabf99a5/href</a></iframe><h4>Third time is a charm</h4><p>At this point, I realized that while the json format is a step in the right direction, I needed more customization to make this solution work for me. Specifically, I needed to remove a lot of the extra fields, such as threadId. Two options came to mind for how to do this:</p><ul><li>I could write my own java format class and add the proper annotations</li><li>I could pass my own json format file to log4j2.xml</li></ul><p>I opted for the second option; as I did not want to maintain/upgrade my own java code, deal with security issues, etc. After screwing around for a while, I came up with the following schema file, which produces satisfactory json:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/797a39d0bec9a31c96491eaf5e34dd47/href">https://medium.com/media/797a39d0bec9a31c96491eaf5e34dd47/href</a></iframe><p>I then specified this as the format to be used in the log4j2.xml file (notice the <em>eventTemplateUri </em>attribute points to the file specified above)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d20dce2fcec183783c9d08c6da9f039/href">https://medium.com/media/9d20dce2fcec183783c9d08c6da9f039/href</a></iframe><p>With these two files in our lambda layer (well technically included as a transitive dependency of our layer), our log messages are now output in a format that enables the queries detailed in the first article without containing unecessary information.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31b9e2b780ccb04bcfe03ea025d6b472/href">https://medium.com/media/31b9e2b780ccb04bcfe03ea025d6b472/href</a></iframe><h3>Gotchas!</h3><p>While using lambda layers can be very beneficial in that they ensure best practices are followed and they allow developers to focus purely on business logic, I would be amiss if I didn’t remind you to automate a process for upgrading functions that use lambda layers. Consider the following situation: there is a critical security flaw in a logging library (say maybe something like <a href="https://en.wikipedia.org/wiki/Log4Shell">log4shell</a>). While you <a href="https://medium.com/codex/upgrading-dependencies-doesnt-have-to-suck-8d5b2b767d58">automatically upgrade (gradle) dependencies on a nightly basis</a>, your lambda layer will NOT automatically be upgraded. You will need to institute a separate process to upgrade the layer ARN when a new version is created (you could likely use cloudwatch events to do this), however, that is outside the scope of this article.</p><h3>Conclusion</h3><p>In this article, we’ve seen a simple way to implement structured logging in aws. Our implementation involved a layer of custom middleware, as well as a lambda layer containing logging dependencies and two configuration files — one file to specify that we wish to use a json format, and the other to specify the specific json format we desire, which includes the information we need without cluttering our logs with unneeded information. With this design, we are able to output structured logs that can be used to run the queries specified in the first article; which allows us to run a more reliable, operationally excellent, and cost effective system.</p><h3>Related Links</h3><ul><li><a href="https://gitlab.com/connorbutch/cloudwatch-logs">Connor Butch / cloudwatch-logs · GitLab</a></li><li><a href="https://medium.com/@connorbutch/the-importance-of-structured-logging-in-aws-and-anywhere-else-52a4534c53aa">The Importance of Structured Logging In AWS (and Anywhere Else)</a></li></ul><h3>Further Reading</h3><ul><li><a href="https://logging.apache.org/log4j/2.x/manual/layouts.html">Log4j - Log4j 2 Layouts</a></li><li><a href="https://medium.com/codex/upgrading-dependencies-doesnt-have-to-suck-8d5b2b767d58">Upgrading dependencies doesn’t have to suck</a></li><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">Creating and sharing Lambda layers</a></li><li><a href="https://awslabs.github.io/aws-lambda-powertools-java/">Homepage</a></li></ul><h3>Addendum</h3><h4>Cost Evaluation</h4><p>Let’s start with lambda costs: consider you go with the default load you will send 50 requests/second * 15 seconds = 750 requests. Then the average billed duration is around 400ms (note, you aren’t billed for initialization/cold start time). Your lambda gets 256mb of memory. That means (even if you are not in the free tier), the requests will cost you .2/1000000 * 750 = $0.00015 (that’s way less than a cent). Your billed duration will cost you $0.0000000017/gb/ms * 400ms/request * 750requests = $0.00051 (again, way less than a cent). Your data transfer in is free, and data transfer out is billed at $0.09/GB * (no way we hit a gb) = $.10 (being super liberal, it’s likely way less than a cent). Api gateway pricing has the first 1000000 free, and minimal after that. So I’m pretty confident running this load test costs under a dime (and that’s being liberal).</p><h4>Adjusting gatling load</h4><p>The gatling simulation takes in two parameters — the number of users per second and the number of seconds to apply the load. While it is quite cheap to run this simulation (see the above analysis), you might want to adjust either the stress or the duration. In this case, you can can adjust them by setting system properties. If you do not set them, the defaults are 50 requests per second for 15 seconds. For example, the below would send 75 requests per second for 40 seconds.</p><pre>./gradlew gatlingRun -DUSERS_PER_SECOND=75 -DDURATION_IN_SECONDS=40</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc3f80929750" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Importance of Structured Logging In AWS (and Anywhere Else)]]></title>
            <link>https://medium.com/@connorbutch/the-importance-of-structured-logging-in-aws-and-anywhere-else-52a4534c53aa?source=rss-efbfc5b6ca1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/52a4534c53aa</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[cloudwatch]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[operational-excellence]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Connor Butch]]></dc:creator>
            <pubDate>Tue, 31 May 2022 11:56:45 GMT</pubDate>
            <atom:updated>2022-05-31T11:56:45.793Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using cloudwatch queries and cloudwatch logs insights to “dive deep” and increase system reliability</h4><figure><img alt="a man is shown staring intently through a magnifying glass" src="https://cdn-images-1.medium.com/max/800/0*t1qPLI3swjn9oecP.jpg" /><figcaption><a href="https://friendlystock.com/wp-content/uploads/2018/02/2-business-man-using-magnifying-glass-cartoon-clipart.jpg">src</a></figcaption></figure><p><em>As always, you can jump to the code for this article by going</em> <a href="https://gitlab.com/connorbutch/cloudwatch-logs">here</a>.</p><p>Yes, I know I’ve written about observability a lot.</p><p>I’ve written about <a href="https://medium.com/@connorbutch/bite-sized-aws-part-two-88b6ea3f76b3">using x-ray to it’s fullest extent by leveraging traces, annotations, metadata, and exceptions</a>.</p><p>I’ve written about <a href="https://medium.com/@connorbutch/bite-sized-aws-part-one-90dd54879717">using emf to generate custom metrics</a>, while giving you the capability to run queries on high cardinality properties (such as company Id) in a cost effective manner when needed.</p><p>I’ve written about <a href="https://medium.com/@connorbutch/the-hardest-issue-to-debug-with-aws-lambda-d636d672d6bc">using cloudwatch logs insights to generate a custom metric to quantify the number of lambda timeouts</a> (which can be hard to debug using out of the box metrics).</p><p>I’ve written about <a href="https://medium.com/@connorbutch/automatically-instrument-your-java-lambdas-with-a-single-annotation-without-spring-1c17c5c6474">using AspectJ to allow us to automatically time method execution time</a> and create metrics out of them.</p><p>I’ve also shown us how to <a href="https://medium.com/@connorbutch/automatically-instrumenting-your-java-lambdas-with-a-single-annotation-part-two-2c2e2ceab8f0">create x-ray traces with a single annotation</a>.</p><p>At this point, my flooding of observability-related articles probably has some of you looking like this</p><figure><img alt="a cartoon image of an exasperated man pulling on his hair is shown" src="https://cdn-images-1.medium.com/max/800/0*3Lmi-uYsT-qaXFfg.jpg" /><figcaption>Yes, I know some of you really are looking at this article like this guy (<a href="https://thumbs.dreamstime.com/b/exasperated-business-cartoon-illustration-showing-business-man-pulling-his-hair-out-as-looks-his-computer-screen-94528126.jpg">img src</a>)</figcaption></figure><p>And yet, this is another article focused on observability. Why? Because it is the most important thing (besides security) that an enterprise system needs to be successful. If you look at Amazon and Google, they are hyper-focused on observability — you can find tons of talks about the topic, Amazon has two builder’s library articles about dashboards (which display metrics) and Amazon includes observability as a key point of the <a href="https://wa.aws.amazon.com/wellarchitected/2020-07-02T19-33-23/wat.pillar.operationalExcellence.en.html">operational excellence pillar</a>, which states a goal of, “…gain insight into their operations, and to continuously improve supporting processes and procedures to deliver business value”. Some ways observability can help deliver business value include:</p><ul><li>the ability to make business decisions that maximize profit (you want a bigger bonus, right?). For example, you can look at the cost per order shipped, and determine that it is more profitable to ship a few big items, as opposed to many smaller ones on a given truck.</li><li>the ability to gain insight into user experience and minimize customer impact (if your api is taking 9 seconds to give a response <a href="https://aws.plainenglish.io/stop-making-synchronous-calls-f101af15cd46">because it makes synchronous calls, you now know this and can refactor it</a>)</li><li>the ability to diagnose and remediate problems — when a problem occurs, you know have information to determine what is going wrong and how to fix it</li><li>the ability to run a/b tests — you can test two versions of your system to determine which is most desirable (i.e. if one version of your mobile app leads to increased sales conversions, then you should likely opt for that design)</li><li>the ability to make informed decisions about technology choices — for example, you can see that at scale, a nosql database like dynamo performs much faster and more consistent than a relational database at scale</li></ul><p>Sadly, despite it’s foundational status, <strong>I find that observability is something that is often neglected by academia, coding bootcamps, internal training, and even in discussions among many “senior” software engineers and mid/upper management. </strong>An emphasis on observability is something I wish someone would have impressed upon me earlier in my career, as it would have saved me a lot of stress and helped me design higher quality systems. It is my hope that these articles will help you avoid the stumbling blocks that I encountered earlier in my career.</p><h3>More Specifics</h3><p>Okay, rant about observability over 😉. Let’s look at structured logging. Structured logging means we output our logs in json (or yaml) format, with specific attributes, such as correlation id and log level. I’ve included an example of a structured log below, but don’t worry too much about the specific information being logged, as there is more on this later in the “How should I format logs to get these benefits” section; <em>the important thing is that it is written in json/yaml</em>.</p><pre>{<br>        &quot;correlationId&quot;: &quot;9ac54d82-75e0-4f0d-ae3c-e84ca400b3bd&quot;,<br>        &quot;requestId&quot;: &quot;58d9c96e-ae9f-43db-a353-c48e7a70bfa8&quot;,<br>        &quot;commitHash&quot;: &quot;9d9154e&quot;,<br>        &quot;level&quot;: &quot;INFO&quot;,<br>        &quot;message&quot;: &quot;Returning response {statusCode: 200,body: []}&quot;<br>}</pre><p>Now that we’ve defined structured logging, as well as looked at a simple example, we will now see why you <strong>MUST</strong> implement structured logging for all of your logs (not just metrics you wish to publish with <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html">emf</a>).</p><p>Then, in a subsequent article (soon to be published) we will see how I implemented structured logging using, aws lambda, lo4j2, lambda layers, and middleware (and the concepts apply to other languages as well).</p><h3>Let’s See It In Action</h3><p>First, I’m going to generate some load (750 requests) against my application using gatling. This load shows us the usefulness of structured logging, and how it functions in a high volume system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E1h5BBMoK2j1F8XE40dHIQ.gif" /><figcaption>Here you can see me executing the gatling simulation to generate load</figcaption></figure><h3>Usefulness of structured logging</h3><p>Now that we’ve simulated traffic to our application, let’s look at three situations which demonstrate the value of structured logging.</p><h4>Situation one: an important customer (say a VP of operations) inquires, “Why did MY request fail?”</h4><p>Consider this, your system is working really well. It is handling thousands of requests per minute, and it exceeds hundreds of thousands of requests per hour. All of a sudden, the VP of operations calls you and says, “I am running a really important client demo, and my request failed. Can you please see why and fix it ASAP? My correlation id is <em>30878b07–654b-4322-b7a3–0472e5b452c6</em>” You open your logs, and realize you have hundreds of lambda instances active in the last hour. Searching through all these logs streams (even if you knew the exact time) is not really a viable solution.</p><p>You look at your dashboard (you do have dashboards, right?), and see your error rate is less than 1%, so his request was likely an anamoly. You search in cloudwatch logs to see his correlation id, and you see it was a network timeout interacting with dynamodb. You tell him it was just a transient failure and ask him to please try again (if he <a href="https://medium.com/@connorbutch/enhancing-openapi-code-generation-with-custom-features-58d38e38222">used your autogenerated open api client that includes automatic retries</a> he wouldn’t be calling you 😉). He clicks submit again, and is happy that his request worked.</p><p>Without structured (json) logs, digging through these log streams would have been all but impossible. Even if some tools <em>do</em> allow for plain text searching, it is not going to be as efficient at scale (as querying indexed json is much quicker than regex matching). Here is a video of me searching in cloudwatch logs streams (notice the query syntax is different from the one I use later for cloudwatch logs insights).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RcCHR4mA_YII98jNFD5urw.gif" /><figcaption>notice how easy it is to search a ton of logs for those relevant to our correlation id</figcaption></figure><p>the query I ran was <em>{ $.contextMap.correlationId=”18d3107e-db33–4688-a60c-5d1b585ba649&quot; } </em>There will be more information on queries later in the article</p><h4>Situation two: A cloudwatch alarm alerts you of a higher than normal error rate, and you want to find similarities among failed requests so you can do a root cause analysis</h4><p>You are on call when a cloudwatch alarm notifies you that your system is experiencing higher than normal error rates. Since you are using aws sam with canary deploys, async lambdas with dlq, and automatic rollbacks, the system continues operating as normal. However, you need to figure out the root cause of the problem (out of band) and apply a fix.</p><p>Using cloudwatch logs insights, you can easily filter your logs for only errorred requests and gather context around why they failed. In this case, we are interested in the search query that was passed that caused the error, so you run the below query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0WLgqwngh621lRdzjPcAkg.gif" /><figcaption>I search for errors, and notice the queries seem to be longer</figcaption></figure><pre>fields @timestamp, @message<br>| filter level = &quot;ERROR&quot;<br>| limit 20</pre><p>After looking at the searches that result in errors, you notice that many of them seem to be quite long, and thus you suspect lengthier queries might be causing the errors. In order to gather further evidence, you dig into cloudwatch logs insights and use it to select the minimum lengths of the searches that end in error. You now see that all of the queries ending in error in the last thirty minutes have a length longer than 66 characters. Armed with this evidence, you can now improve the reliability of the system by limiting the length of queries or by modifying the application to support longer searches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TjgIp5jpDjMQ91_udpXArg.gif" /><figcaption>the shortest failed query had a length of 66 characters</figcaption></figure><pre>fields strlen(contextMap.searchQuery) as queryLength<br>| filter level = &quot;ERROR&quot;<br>| sort queryLength asc<br>| limit 10</pre><h4>Situation three: You are debugging an error in your application, but the stack trace doesn’t line up with the lines of code in your repo… so you wonder, what commit is this using anyways?</h4><p>Consider that an alarm has gone off for your application. You have rollbacks in place, so production is working and there is minimal customer impact, but you are trying to debug the error in your codebase. It is showing a null pointer on line 102. However, your lambda code is only 94 lines long. After beating your head for a few minutes, you then realize that you could be looking at the wrong commit hash (as some of the code might still be “baking” in a lower environment, or production has a canary deploy, so traffic is split between two revisions). You quickly run a query to confirm that errors are occurring in this certain git commit hash, and now you are reasonably assured the error has already been resolved.</p><p>(no video here, I’ll leave it to you to figure this one out 😉)</p><h3>Important Tip: there are different query formats depending on if you are querying a log stream or using cloudwatch logs insights</h3><p>One thing that I always forget is that there are different syntax for searching logs depending on what part of cloudwatch you are in.</p><h4>Cloudwatch log stream query examples</h4><pre>{ $.contextMap.correlationId=”18d3107e-db33–4688-a60c-5d1b585ba649&quot; }</pre><pre>{ $.level = “ERROR” } </pre><h4>Cloudwatch log insights query examples</h4><pre>fields @timestamp, @message<br>| sort @timestamp desc<br>| filter correlationId = &quot;88f38a99-0d61-44dc-b6e1-51d11a0deb73&quot;<br>| limit 20</pre><pre>fields @timestamp, @message<br>| sort @timestamp desc<br>| filter level = &quot;ERROR&quot;   <br>| limit 20</pre><pre>fields strlen(contextMap.searchQuery) as queryLength<br>| filter level = &quot;ERROR&quot;<br>| sort queryLength asc<br>| limit 10</pre><h3>How should I format logs to get these benefits?</h3><p>Now that we’ve seen the benefits of structured logging, you are likely asking, “how should I format my logs? What should be included?”. First of all, logging should be done in a way that is consistent across services. From a practical perspective, that means that all logs should use properly formatted json (with double quotes surrounding all keys and string values, and including commas between fields). And this json MUST contain the following fields, regardless of the service or team:</p><ul><li><a href="https://www.rapid7.com/blog/post/2016/12/23/the-value-of-correlation-ids/"><strong>correlation id</strong> </a>— a unique id that is generated when an event reaches the system, and <em>is propagated to all downstream services</em>.</li><li><strong>request id</strong> — a unique id that is generated for each request. Each call to downstream service should <em>return a unique request id</em>.</li><li><strong>commit hash </strong>— the git commit hash for this component. Especially important in a world of canary deploys, and CI/CD</li><li><a href="https://sematext.com/blog/logging-levels/"><strong>(log) level </strong></a>— an enum that denotes the importance of a message. Most logging frameworks define these for you (i.e. trace, debug, info, warn, error)</li></ul><p><strong>I always include these fields at the top of json in my logs before the message field. </strong>This is<strong> </strong>to remind myself that its important that I am looking at the correct request that is associated with the same transaction, and that I am referencing the correct version of the source code.</p><p>In addition to these fields, it is <em>often useful</em> (but not required) for teams to include additional json keys in their logs. They can do this by adding key-value pairs to the thread context (you can see examples of this in part two of this article). I would usually suggest treating this like annotations in x-ray — any field that you would like to search upon that can be safely recorded in logs should be added as a field. For example, it would probably make sense to include fields for the following attributes</p><ul><li><em>order id</em> for a shipping company</li><li><em>email address</em> for a marketing company</li><li><em>transaction id </em>for a banking company</li></ul><h3>Structured Logging vs X-ray</h3><p>If you’ve read my article on x-ray, you might be thinking, “wait, why do I need this if I can use x-ray? Don’t they do the same thing?”. While they can accomplish many of the same things, keep in mind a few of the points I made in the x-ray article, namely that <em>default x-ray sampling rate is only 5% </em>(excluding the first request every minute). That means odds are for 95% of requests you want to view the traces for, they will not be available. If you choose to increase the sampling rate to 100%, then this can get <em>expensive</em>. Even if you were to pay to save traces for every event, it is <em>difficult to derive metrics from x-ray</em> compared to cloudwatch logs insights. Think about the above example where we determined the average length of a failing query. That was accomplished with a few lines of query code in cloudwatch console, but it would take hundreds of lines to do such a thing with x-ray (and would need an ide to write the code and such as well).</p><p>Hence, while x-ray is a useful tool; I would usually believe you can achieve a superset of its capabilities using cloudwatch logs insights in a more cost-optimized manner. Thus, <strong>I would suggest to always log the information to cloudwatch, and only supplement it with x-ray if you really feel it adds value</strong>.</p><h3>Conclusion</h3><p>In this article, we’ve been reminded the benefits of observability. We then focused in on how structured logging lends itself to more observable systems. We looked at three different examples of questions that can be answered using structured logging — looking for information on a specific request, finding commonality among errors, and confirming the git commit hash when errors occur, so we can use the stack trace line numbers most effectively. Finally, we have seen that while x-ray offers somewhat similar capabilities, we can achieve these capabilities (and more) using cloudwatch logs insights, all the while saving money.</p><p>I hope this article helps you design and operate more reliable, performant, and cost optimized systems. <strong>Be on the lookout for part two, in which I show how to implement these technologies using aws lambda, log4j2, lambda layers and middleware.</strong></p><h3>Related Links</h3><p><a href="https://gitlab.com/connorbutch/cloudwatch-logs">Connor Butch / cloudwatch-logs · GitLab</a></p><h3>Further Reading</h3><ul><li><a href="https://medium.com/@connorbutch/the-hardest-issue-to-debug-with-aws-lambda-d636d672d6bc">The Hardest Issue To Debug With AWS Lambda</a></li><li><a href="https://medium.com/@connorbutch/bite-sized-aws-part-one-90dd54879717">Bite-Sized AWS (Part One)</a></li><li><a href="https://medium.com/@connorbutch/bite-sized-aws-part-two-88b6ea3f76b3">Bite-sized AWS (Part Two)</a></li><li><a href="https://medium.com/@connorbutch/automatically-instrument-your-java-lambdas-with-a-single-annotation-without-spring-1c17c5c6474">Automatically instrument your java lambdas with a single annotation (without spring)</a></li><li><a href="https://medium.com/@connorbutch/automatically-instrumenting-your-java-lambdas-with-a-single-annotation-part-two-2c2e2ceab8f0">Automatically instrumenting your java lambdas with a single annotation (Part Two)</a></li><li><a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html#metric-filters-extract-json">Filter and pattern syntax</a></li><li><a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax-examples.html">Sample queries</a></li><li><a href="https://aws.amazon.com/blogs/compute/using-lambda-layers-to-simplify-your-development-process/">Using Lambda layers to simplify your development process | Amazon Web Services</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2Fjt-gV1YwmnI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fwatch%3Fv%3Djt-gV1YwmnI&amp;image=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2Fjt-gV1YwmnI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/47bcb4606b16423befac50a1fcbd0f97/href">https://medium.com/media/47bcb4606b16423befac50a1fcbd0f97/href</a></iframe><ul><li><a href="https://www.rapid7.com/blog/post/2016/12/23/the-value-of-correlation-ids/">The Value of Correlation IDs | Rapid7 Blog</a></li><li><a href="https://logging.apache.org/log4j/2.x/manual/layouts.html">Log4j - Log4j 2 Layouts</a></li><li><a href="https://gatling.io/">Professional Load Testing Tool | Gatling</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52a4534c53aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatically instrumenting your java lambdas with a single annotation (Part Two)]]></title>
            <link>https://medium.com/@connorbutch/automatically-instrumenting-your-java-lambdas-with-a-single-annotation-part-two-2c2e2ceab8f0?source=rss-efbfc5b6ca1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c2e2ceab8f0</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[aspectj]]></category>
            <dc:creator><![CDATA[Connor Butch]]></dc:creator>
            <pubDate>Mon, 16 May 2022 11:26:54 GMT</pubDate>
            <atom:updated>2022-05-16T11:26:54.719Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using AspectJ to avoid repetitive code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*nHScVfwl3iNCcr25.jpg" /><figcaption>AspectJ can seem like magic</figcaption></figure><p>In <a href="https://medium.com/@connorbutch/automatically-instrument-your-java-lambdas-with-a-single-annotation-without-spring-1c17c5c6474">part one</a> of this series we saw how easy it is to use <a href="https://www.eclipse.org/aspectj/">AspectJ</a> to generate latency metrics for how long it takes a method to execute, as well as creating traces by simply adding an annotation or two to a given method. This is similar to the approach taken by<a href="https://awslabs.github.io/aws-lambda-powertools-java/core/metrics/"> aws lambda powertools</a> (for java), if you’re interested.</p><p>In this article, we will show how aspects are implemented (i.e. how the metrics are actually created and how the traces are generated for methods that are annotated with @Timed and @Traced respectively).</p><h3>Implementation Basics</h3><p>Both the timing and tracing aspects are implemented in the <a href="https://gitlab.com/connorbutch/aspectj-metrics-and-traces/-/tree/main/timing-aspect">same gradle module</a> (but you could easily split them into two separate ones). Both aspects are implemented in a similar manner, so while this article primarily focuses on the metric publication aspect (<strong>@Timed</strong>) , the same principles apply for the trace aspect (<strong>@Traced</strong>), and I’d encourage you to look at how that is implemented 😉</p><p>. In order to create an aspect that executes code whenever a method marked with the given annotation is executed, do the following:</p><ul><li>add @Aspect annotation to the top of the class</li><li>add a method that will execute around the <a href="https://www.eclipse.org/aspectj/doc/next/runtime-api/org/aspectj/lang/ProceedingJoinPoint.html">ProceedingJoinPoint</a>— annotate the method to make it execute around any method annotated with the @Timed annotation</li></ul><pre><strong>@Aspect</strong><br>public class TimingAspect {<br>    private final MetricPublisher metricPublisher;<br><br>    public TimingAspect(MetricPublisher metricPublisher) {<br>        this.metricPublisher = metricPublisher;<br>    }<br><br>    public TimingAspect() {<br>        this(MetricPublisherFactory.getMetricPublisher());<br>    }<br><br><strong>    @Around(&quot;@annotation(com.connor.monitoring.Timed)&quot;)</strong><br>    public Object callMethodAndRecordLatencyMetrics(ProceedingJoinPoint invocation)<br>            throws Throwable {<br>        //do whatever you want in here, then call proceed to execute method<br>        return invocation.proceed();</pre><pre>    }</pre><p><em>NOTE: the </em><a href="https://www.eclipse.org/aspectj/doc/next/runtime-api/org/aspectj/lang/ProceedingJoinPoint.html"><em>ProceedingJoinPoint</em></a><em> contains all sorts of information, such as the parameters, the method name, etc that can be used (for more information, look across the aspects I’ve implemented).</em></p><p>That is the basics on how to implement an aspect to execute code around an annotated method. If you’d like to see how I used this to publish metrics, you can find the full source code <a href="https://gitlab.com/connorbutch/aspectj-metrics-and-traces/-/blob/main/timing-aspect/src/main/java/com/connor/monitoring/TimingAspect.java">here</a> and you can read the rest of the article.</p><h3>Metric Publishing Specifics</h3><p>The full source code used to publish metrics is shown below. This code does the following:</p><ul><li>read in the Timed annotation from the method (used to get metric namespace)</li><li>record the system time (in milliseconds)</li><li>executes the method and records the system time (in milliseconds)</li><li>if there is an error, it calls the exception handler, then rethrows the error</li><li>if it succeeds, it publishes a success latency metric</li></ul><pre>package com.connor.monitoring;<br><br>import org.aspectj.lang.ProceedingJoinPoint;<br>import org.aspectj.lang.annotation.Around;<br>import org.aspectj.lang.annotation.Aspect;<br>import org.aspectj.lang.reflect.MethodSignature;<br><br>@Aspect<br>public class TimingAspect {<br>    private final MetricPublisher metricPublisher;<br><br>    public TimingAspect(MetricPublisher metricPublisher) {<br>        this.metricPublisher = metricPublisher;<br>    }<br><br>    public TimingAspect() {<br>        this(MetricPublisherFactory.getMetricPublisher());<br>    }<br><br>    @Around(&quot;@annotation(com.connor.monitoring.Timed)&quot;)<br>    public Object callMethodAndRecordLatencyMetrics(ProceedingJoinPoint invocation)<br>            throws Throwable {<br>        return callMethodAndRecordMetrics(invocation);<br>    }<br><br>    private Object callMethodAndRecordMetrics(ProceedingJoinPoint invocation) throws Throwable {<br>        MethodSignature methodSignature = (MethodSignature) invocation.getSignature();<br>        Timed timed = methodSignature.getMethod().getAnnotation(Timed.class);<br>        final long startTimeInMs = System.currentTimeMillis();<br>        Object obj = executeMethodAndHandleException(invocation, timed, startTimeInMs);<br>        final long endTimeInMs = System.currentTimeMillis();<br>        String latencyMetricName = getLatencyMetricName(timed);<br>        metricPublisher.publishMetric(timed.metricNamespace(), latencyMetricName, endTimeInMs - startTimeInMs);<br>        return obj;<br>    }<br><br>    private Object executeMethodAndHandleException(ProceedingJoinPoint invocation, Timed timed, long startTimeInMs) throws Throwable {<br>        try {<br>            return invocation.proceed();<br>        } catch (Exception e) {<br>            final long endTimeInMs = System.currentTimeMillis();<br>            handleException(timed, startTimeInMs, e, endTimeInMs);<br>            throw e;<br>        }<br>    }<br><br>    private void handleException(final Timed timed, final long startTimeInMs, final Exception e, final long endTimeInMs) {<br>        try {<br>            MetricExceptionHandler metricExceptionHandler = timed.exceptionHandler().getDeclaredConstructor().newInstance();<br>            metricExceptionHandler.handleException(e, timed, endTimeInMs - startTimeInMs);<br>        } catch (Exception ex) {<br>            System.out.println(&quot;Error creating exception metric handler&quot;);<br>            ex.printStackTrace();<br>        }<br>    }<br><br>    private String getLatencyMetricName(Timed timed) {<br>        String latencyMetricName = timed.latencyMetricName().trim();<br>        if (!latencyMetricName.endsWith(&quot;latency&quot;) &amp;&amp; !latencyMetricName.endsWith(&quot;Latency&quot;)) {<br>            latencyMetricName = latencyMetricName + &quot;Latency&quot;;<br>        }<br>        return latencyMetricName;<br>    }<br>}</pre><h3>Reminders</h3><p>There are a few things to keep in mind when using this approach.</p><h4>It can be easy to miss creating metrics</h4><p>If a project forgets to include the plugin the build.gradle, a method can have the annotation, but not publish metrics 😱. To remedy this, <em>alarm on lack of data</em>, and use <em>cloudwatch synthetics to continuously execute the api.</em></p><p>Here is a quote from <a href="https://aws.amazon.com/builders-library/going-faster-with-continuous-delivery/?did=ba_card&amp;trk=ba_card">aws builder’s library</a> that speaks to continuously exercising their services</p><blockquote>We want fast feedback if our service isn’t working correctly, so we run our synthetic tests at least every minute. We design synthetic tests to make sure that our running processes are healthy and that all dependencies are tested, which often involves testing all public-facing APIs</blockquote><h4>Using reflection is slow</h4><p>Getting an instance of the metric publisher from the class name uses <a href="https://www.geeksforgeeks.org/reflection-in-java/">reflection</a>. We avoid this by using <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#putIfAbsent-K-V-">putIfAbsent</a> on a map (cache) for warm starts; however, with the current design, it will inevitably use reflection on cold starts. To avoid this, you could <em>store the metric publisher instance somewhere</em> (say as a singleton) and not use reflection to get the instance.</p><h4>Publishing dimensions/properties for a given metric is harder</h4><p>You could add an interface that takes in the annotation or method arguments and outputs the dimensions/properties to be published with the metric (similar to what we do with the exception handler), but that might be making this a little too complicated. At that point, it might be best to <em>write the “regular” code</em> rather than using aspects.</p><h3>Tracing Implementation</h3><p>This article isn’t going to go over the tracing implementation in depth, but <a href="https://gitlab.com/connorbutch/aspectj-metrics-and-traces/-/blob/main/timing-aspect/src/main/java/com/connor/trace/TracingAspect.java">here</a> is the source code (also shown below), so you can feel free to inspect it as you wish.</p><pre>package com.connor.trace;<br><br>import org.aspectj.lang.ProceedingJoinPoint;<br>import org.aspectj.lang.annotation.Around;<br>import org.aspectj.lang.annotation.Aspect;<br>import org.aspectj.lang.reflect.MethodSignature;<br><br>import java.util.Optional;<br><br>@Aspect<br>public class TracingAspect {<br>    @Around(&quot;@annotation(com.connor.trace.Traced)&quot;)<br>    public Object callMethodAndStartTrace(ProceedingJoinPoint invocation)<br>            throws Throwable {<br>        MethodSignature methodSignature = (MethodSignature) invocation.getSignature();<br>        try (Trace trace = TraceProviderXrayImpl.getInstance().createTrace(getTraceName(methodSignature))) {<br>            Traced traced = methodSignature.getMethod().getAnnotation(Traced.class);<br>            if (traced.doLogParametersAsMetadata()) {<br>                logParametersAsMetadata(invocation, trace);<br>            }<br>            return invocation.proceed();<br>        }<br>    }<br><br>    private void logParametersAsMetadata(final ProceedingJoinPoint invocation, final Trace trace) {<br>        MethodSignature methodSignature = (MethodSignature) invocation.getSignature();<br>        for (int index = 0; index &lt; methodSignature.getParameterNames().length; ++index) {<br>            trace.putMetadata(methodSignature.getParameterNames()[index], invocation.getArgs()[index]);<br>        }<br>    }<br><br>    private String getTraceName(MethodSignature methodSignature) {<br>        return Optional.of(methodSignature)<br>                .map(MethodSignature::getMethod)<br>                .map(method -&gt; method.getAnnotation(Traced.class))<br>                .map(Traced::subsegmentName)<br>                .filter(subsegmentName -&gt; !subsegmentName.isBlank())<br>                .orElseGet(methodSignature::getName);<br>    }<br>}</pre><h3>Conclusion</h3><p>In this article, we have seen how easy it is to implement the backing code for an aspect. We saw that we can read in various information about the method being executed, including method name, annotations present (as well as values contained in the annotation). Finally, we saw we can read in runtime specific information, such as parameter values (which we add as metadata to our traces).. We then automatically create latency metrics in cloudwatch using emf, as well as generating traces in x-ray. Hopefully you can use this technique in your own projects.</p><h3>Related Links</h3><ul><li><a href="https://gitlab.com/connorbutch/aspectj-metrics-and-traces">Connor Butch / aspectj-metrics-and-traces · GitLab</a></li><li><a href="https://medium.com/@connorbutch/automatically-instrument-your-java-lambdas-with-a-single-annotation-without-spring-1c17c5c6474">Automatically instrument your java lambdas with a single annotation (without spring)</a></li></ul><h3>Further Reading</h3><ul><li><a href="https://www.eclipse.org/aspectj/">The AspectJ Project | The Eclipse Foundation</a></li><li><a href="https://www.geeksforgeeks.org/reflection-in-java/">Reflection in Java - GeeksforGeeks</a></li><li><a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html">Specification: Embedded metric format</a></li><li><a href="https://medium.com/@connorbutch/bite-sized-aws-part-one-90dd54879717">Bite-Sized AWS (Part One)</a></li><li><a href="https://aws.amazon.com/xray/">Debug Tool - AWS X-Ray - AWS</a></li><li><a href="https://medium.com/@connorbutch/bite-sized-aws-part-two-88b6ea3f76b3">Bite-sized AWS (Part Two)</a></li><li><a href="https://awslabs.github.io/aws-lambda-powertools-java/core/metrics/">Metrics</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c2e2ceab8f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatically instrument your java lambdas with a single annotation (without spring)]]></title>
            <link>https://medium.com/@connorbutch/automatically-instrument-your-java-lambdas-with-a-single-annotation-without-spring-1c17c5c6474?source=rss-efbfc5b6ca1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c17c5c6474</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Connor Butch]]></dc:creator>
            <pubDate>Mon, 09 May 2022 11:03:17 GMT</pubDate>
            <atom:updated>2022-05-09T11:03:17.406Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using AspectJ to avoid repetitive code and ensure the usage of best practices</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*UK3YMfabluoGS80U.jpg" /><figcaption>img <a href="https://s3.amazonaws.com/lowres.cartoonstock.com/transport-truck-trucker-delivery-delivery_guy-delivery_driver-dbcn419_low.jpg">src</a></figcaption></figure><h3>Business Case</h3><p>Pretend you are in charge of a team that accepts orders and sends them out for fulfillment. When your service receives a request for a new order, it validates the address. Rather than build an address validation service, you decide to use a SaaS solution (such as <a href="https://www.smarty.com">Smarty</a>).</p><p>While most component interactions <a href="https://aws.plainenglish.io/stop-making-synchronous-calls-f101af15cd46">can and should be done asynchronously</a>, we must validate the order’s address before we return success response to the customer, hence address validation is a call that must be made synchronously. This <a href="https://en.wikipedia.org/wiki/Remote_procedure_call">RPC</a> (and I would argue, all synchronous out of process calls) must be instrumented in such a way that it gives visibility into various metrics, which are discussed more in depth below. While most of these metrics (as well as others) come out of the box with aws services, I’ve often found myself building solutions to fill these gaps when calling third party services, such as the address validation api mentioned in this example, or when using stripe to process card payments.</p><h3>System Architecture</h3><p>Before we go any further, let’s look at our system architecture, which consists of a lambda triggered by api gateway, an sqs queue and a cloudwatch dashboard.</p><figure><img alt="An architecture diagram is shown. It is simple and shows a lambda triggered by api gateway, an sqs queue, cloudwatch dashboard, as well as a third party api" src="https://cdn-images-1.medium.com/max/719/1*bpMmPnk3yZ66mtnN8WA8aw.png" /><figcaption>Our system architecture</figcaption></figure><p><em>NOTE: the architecture is intentionally simple, so that we can focus on AspectJ usage within our single lambda.</em></p><h3>Enterprise-Grade Instrumentation</h3><h4>Metrics</h4><p>As mentioned above, we need (custom) cloudwatch metrics to ensure our system is functioning as expected, to automate remediation actions if needed, as well as to visualize on dashboards that are visible to both internal and external (smarty) users. Finally, these can also be used to ensure that third parties are meeting their contractual <a href="https://en.wikipedia.org/wiki/Service-level_agreement">SLA</a> (such as uptime or latency requirements). The two metrics we need to achieve these goals are:</p><ul><li>success latency</li><li>error latency</li></ul><p>By using various <em>aggregations </em>(such as count)<em> </em>against these metrics in combination with <em>metric math </em>(to perform functions such as adding two metric values together), we can generate the following statistics.</p><ul><li>total number of calls made to the external api (count and metric math)</li><li>number of successful calls made to the external api (count)</li><li>number of failed calls made to the external api (count)</li><li>success latency (percentiles)</li><li>error latency (percentiles)</li></ul><p>We can use <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html">emf</a> to publish metrics, and then we can use it with <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html">cloudwatch logs insights</a> to glean further information about specific events when needed. You can read an in-depth article about this incredibly useful technique <a href="https://medium.com/@connorbutch/bite-sized-aws-part-one-90dd54879717">here</a>.</p><h4>Traces</h4><p>In addition to metrics, <a href="https://aws.amazon.com/xray/">x-ray traces</a> can help us track an event’s processing across distributed microservices. With x-ray, you can search on annotations (such as IDs) and view metadata (such as request/response interactions with external services). You can find an article discussing x-ray in-depth <a href="https://medium.com/@connorbutch/bite-sized-aws-part-two-88b6ea3f76b3">here</a>.</p><h3>Different Approaches</h3><p>There are different ways to instrument our code to capture the above metrics and to generate traces with the appropriate metadata. I have shown two approaches below that accomplish our goals of creating traces and metrics. One approach uses “traditional” java coding (shown on the right), and one using <a href="https://www.eclipse.org/aspectj/">AspectJ</a> annotations (shown on the left).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vaAoUEOR6TZQFu6ZJPqV_Q.png" /><figcaption>On the left, you see the aspectJ approach, and on the right, you see a more traditional approach</figcaption></figure><h3>Advantages of AspectJ</h3><p>There are quite a few benefits of using the AspectJ approach for instrumentation (shown on the left in the above diagram) over the “traditional” one shown on the left. Some of these include:</p><ul><li>less code -&gt; less chance of errors</li><li>less code -&gt; easier to validate functionality via unit testing</li><li>less code -&gt; easier for others to read and understand</li><li>standardization/following best practices -&gt; less chance of errors</li></ul><p><em>There are a few nuances with the AspectJ approach, which we will touch on later.</em></p><h3>AspectJ Usage</h3><p>After seeing the simplicity (and advantages) of using AspectJ, you are likely asking, “How do I implement this in my project?” (and as a matter of fact, aws has implemented similar functionality in the <a href="https://awslabs.github.io/aws-lambda-powertools-java/core/tracing/">aws powertools for java libraries</a>) Usage is simple, and requires updating only a few lines of code (please note <strong>this does NOT use spring</strong> or any other heavy dependencies 😃)</p><ul><li>add dependencies (build.gradle)</li></ul><pre>dependencies <strong>{<br>    </strong>implementation &#39;com.amazonaws:aws-lambda-java-core:1.2.1&#39;<br>    implementation &#39;com.amazonaws:aws-lambda-java-events:3.11.0&#39;<br><strong>    aspect project(&quot;:timing-aspect&quot;)<br>    implementation &#39;org.aspectj:aspectjrt:1.9.8&#39;</strong><br>    implementation &#39;com.amazonaws:aws-java-sdk-sqs:1.12.119&#39;<br><strong>}</strong></pre><ul><li>add the <a href="https://plugins.gradle.org/plugin/io.freefair.aspectj.post-compile-weaving">AspectJ plugin</a> (build.gradle)</li></ul><pre>plugins <strong>{<br>    </strong>id &#39;java&#39;<br><strong>    id &quot;io.freefair.aspectj.post-compile-weaving&quot; version &quot;6.4.1&quot;</strong><br><strong>}</strong></pre><ul><li>add the @Timed annotation above the method you wish to instrument (I added the tracing annotation as well)</li></ul><pre>@Timed(metricNamespace = &quot;address&quot;, latencyMetricName = &quot;validateAddressApi&quot;)<br>@Traced(doLogParametersAsMetadata = true)<br>private void validateAddress(APIGatewayProxyRequestEvent input) {<br>    simulateLatency();<br>    if (shouldThrowException(input)) {<br>        throw new RuntimeException(&quot;Oh no, something went wrong&quot;);<br>    }<br>}</pre><p>That’s it! If you’re curious, you can find links to the full files below</p><ul><li><a href="https://gitlab.com/connorbutch/aspectj-metrics-and-traces/-/blob/main/validate-order/build.gradle">build.gradle</a></li><li><a href="https://gitlab.com/connorbutch/aspectj-metrics-and-traces/-/blob/main/validate-order/src/main/java/com/connor/RequestHandlerValidateOrderImpl.java">instrumented lambda</a></li></ul><h3>Let’s See It In Action</h3><p>Let me show you that this code does indeed generate metrics and x-ray traces with only a single line of code (the annotation).</p><ul><li>clone the repo</li></ul><pre>git clone <a href="mailto:git@gitlab.com">git@gitlab.com</a>:connorbutch/aspectj-metrics-and-traces.git</pre><ul><li>provision the infrastructure</li></ul><pre>sam build &amp;&amp; sam deploy --guided</pre><ul><li>generate traffic against the api</li></ul><pre>./gradlew generateTraffic</pre><ul><li>open the <em>order-dashboard</em> cloudwatch dashboard to verify metrics are published</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X6-W69aDjiREE3ry6cToGw.png" /></figure><ul><li>query x-ray to verify trace creation (note the exception is automatically added to failures, and the names of the subsegments — one is gotten from the method name and one uses the custom name we assign it via annotation)</li></ul><pre>service(&quot;validate-order&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JIHHPDMbf4YXa606jphelA.gif" /></figure><h3>Conclusion</h3><p>In this article, we’ve seen how easy it is to automatically instrument our code to capture various metrics, as well as creating traces for us by adding two annotations above the method we wish to observe and adding two dependencies to our build.gradle. In addition to being easy to implement, this technique decreases the chance of errors, makes it easier to validate functionality via unit testing, makes our code more readable, and ensures our code is standardized/follows best practices.</p><p>If you are interested in going beyond using the annotation to instrument your code, and would like to see how you can implement the backing pointcut aspect code, then be on the lookout for the next article in this series, where I will show how these particular aspects work.</p><h3>Related Links</h3><p><a href="https://gitlab.com/connorbutch/aspectj-metrics-and-traces">Connor Butch / aspectj-metrics-and-traces · GitLab</a></p><h3>Further Reading</h3><ul><li><a href="https://www.eclipse.org/aspectj/">The AspectJ Project | The Eclipse Foundation</a></li><li><a href="https://aws.plainenglish.io/stop-making-synchronous-calls-f101af15cd46">Stop making synchronous calls!</a></li><li><a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/using-metric-math.html">Using math expressions with CloudWatch metrics</a></li><li><a href="https://awslabs.github.io/aws-lambda-powertools-java/core/tracing/">Tracing</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c17c5c6474" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Rebuild AWS EC2 (Part 2)]]></title>
            <link>https://medium.com/@connorbutch/lets-rebuild-aws-ec2-part-2-8b87d8cd8778?source=rss-efbfc5b6ca1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b87d8cd8778</guid>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Connor Butch]]></dc:creator>
            <pubDate>Mon, 02 May 2022 12:10:35 GMT</pubDate>
            <atom:updated>2022-05-02T12:10:35.625Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using event filtering to selectively process events on dynamodb streams</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*nVMp9SGfT6DPl0FP.jpg" /><figcaption>img <a href="https://cdn5.vectorstock.com/i/1000x1000/89/99/building-construction-cartoon-vector-10628999.jpg">src</a></figcaption></figure><h3>Background</h3><p>In <a href="https://medium.com/@connorbutch/lets-rebuild-aws-ec2-part-1-a53349f8e5a">part one of this series</a>, we saw how to replicate the launch instances functionality of aws ec2 control plane using dynamodb. This design ensured three important things:</p><ul><li>remember that <a href="https://www.linkedin.com/pulse/everything-fails-all-time-fernando-schubert#:~:text=Let&#39;s%20go%20back%20to%20our,fail%2C%20usually%20sooner%20than%20later.">everything fails all the time</a>, so <a href="https://aws.amazon.com/builders-library/making-retries-safe-with-idempotent-APIs/?did=ba_card&amp;trk=ba_card">our requests must be retryable</a></li><li>we must launch <em>exactly one</em> instance for a given request and its associated retries</li><li>we must return <em>the same response, including the same server-side generated id </em>for both an original request and its associated retries</li></ul><p>In this article, we will selectively process events off the dynamodb (kinesis) stream using event filtering. This will allow us to process inserts to our table while ignoring deleted item events (these will occur when our ttl configuration deletes old items in our table to minimize storage cost and to help with debugging).</p><h3>Example DynamoDb Events</h3><p>Below is an example of an event that was emitted to the change stream when I inserted an item to our dynamodb table, as well as an event that was emitted to the change stream when I deleted an item from the table. We will need to write the filter on our event source mapping to only process the insert events, while ignoring deletions.</p><h4>Insert Item Event</h4><pre>{<br>  Records: [<br>    {<br>      eventID: &#39;cca782a1ccbaea802e6f918507401bae&#39;,<br><strong>      eventName: &#39;INSERT&#39;,</strong><br>      eventVersion: &#39;1.1&#39;,<br>      eventSource: &#39;aws:dynamodb&#39;,<br>      awsRegion: &#39;us-west-2&#39;,<br>      dynamodb: [<br>        Object<br>      ],<br>      eventSourceARN: &#39;arn:aws:dynamodb:us-west-2:111111111111:table/dynamo-stream-RequestIdempotencyTable-XSCC4MJQZE48/stream/2022-04-18T20:51:23.540&#39;<br>    }<br>  ]<br>}</pre><h4>Delete (remove) Item Event</h4><pre>{<br>  Records: [<br>    {<br>      eventID: &#39;890b96571ba234afeb3cbffa5995bb25&#39;,<br><strong>      eventName: &#39;REMOVE&#39;,</strong><br>      eventVersion: &#39;1.1&#39;,<br>      eventSource: &#39;aws:dynamodb&#39;,<br>      awsRegion: &#39;us-west-2&#39;,<br>      dynamodb: [<br>        Object<br>      ],<br>      userIdentity: [<br>        Object<br>      ],<br>      eventSourceARN: &#39;arn:aws:dynamodb:us-west-2:111111111111:table/dynamo-stream-RequestIdempotencyTable-XSCC4MJQZE48/stream/2022-04-18T20:51:23.540&#39;<br>    }<br>  ]<br>}</pre><p><em>that’s not my real aws account id, btw 😉</em></p><h3>Sam (Cloudformation) Changes</h3><p>In order to ensure our lambda only processes inserts into our table, we have to add an event filtering section to our <a href="https://gitlab.com/connorbutch/ec2-clone/-/blob/main/template.yaml#L68">sam template</a>. You can see the relevant section highlighted in bold below.</p><pre>VmPackingLambda:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      CodeUri: vm-packing/<br>      Description: This lambda processes the requests for launching instances<br>      Events:<br>        IdempotencyTableInsert:<br>          Type: DynamoDB<br>          Properties:<br>            Stream: !GetAtt RequestIdempotencyTable.StreamArn<br>            StartingPosition: LATEST <em><br>           </em><strong><em> </em>FilterCriteria:<br>              Filters:<br>                - Pattern:   &quot;{ \&quot;eventName\&quot;: [ \&quot;INSERT\&quot; ] }&quot;</strong></pre><p>We also need to enable the change stream on the dynamodb table. In this case, we know there change stream will not contain updates, so we can set the <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-streamspecification.html">change stream specification</a> to only show the new images (see the bold section of the cloudformation template below)</p><pre>RequestIdempotencyTable:<br>  Type: AWS::DynamoDB::Table<br>  Properties:<br>    AttributeDefinitions:<br>      - AttributeName: &quot;clientToken&quot;<br>        AttributeType: &quot;S&quot;<br>    KeySchema:<br>      - AttributeName: &quot;clientToken&quot;<br>        KeyType: &quot;HASH&quot;<br>    TimeToLiveSpecification:<br>      AttributeName: expirationTime<br>      Enabled: true<br>    BillingMode: PAY_PER_REQUEST<br><strong>    StreamSpecification:<br>      StreamViewType: NEW_IMAGE</strong></pre><p>In addition to adding the lambda, associated event filtering, and specifying the stream to emit new items, we also modify the cloudwatch dashboard section of our template to include the following metrics:</p><ul><li>ConsumedWriteCapacityUnits on our dynamodb table</li><li>TimeToLiveDeletedItemCount on our dynamodb table</li><li>Invocations on our processing lambda function</li></ul><p>You can see this <a href="https://gitlab.com/connorbutch/ec2-clone/-/blob/main/template.yaml#L54">in our sam template</a> which appears on the last few rows of the cloudwatch dashboard that gets provisioned as part of our stack (this screenshot is from the bottom part of the dashboard)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6aB1cRlS8GqmT9CkPZBwlA.png" /><figcaption>Notice that the lambda is invoked when there are items inserted to the table (top left and bottom left), but not invoked when items are deleted from it (top right graph) — you can see this in the cloudwatch dashboard</figcaption></figure><h3>Lets see it in action</h3><ul><li>clone the repo</li></ul><pre>git clone git@gitlab.com:connorbutch/ec2-clone.git</pre><ul><li>provision the infrastructure (don’t need the guided flag after the first deploy)</li></ul><pre>sam build &amp;&amp; sam deploy --guided</pre><ul><li>send requests to the api</li></ul><pre>cd launch-instance/ &amp;&amp; npm run cucumberNonRetry</pre><ul><li><strong>wait for a few minutes</strong> then come back (note that dynamodb expiration is not exact)</li><li>check the logs for the lambda and do a sanity check that they only contain “insert” records</li><li>check the dynamodb table — there should be zero items in the table</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rVY-MR2wIsiX5Il0-7TzWw.png" /><figcaption>notice there are no items in the table — they have all been cleared by the ttl configuration</figcaption></figure><h3>Nuanced Implementation Details</h3><p>There are <a href="https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html">two options for the starting position</a> on the event source mapping for a given stream. Your choice on which to select has serious implications on which items are processed by your lambda. Be sure to pick the one that best fits your applications needs based on whether you want your lambda to process <em>all events</em> ever pushed onto this stream, or if you only want it to process events emitted to the stream <em>after the event source mapping is created</em>:</p><ul><li><strong>Latest</strong> — Process only new records that are added to the stream (in this case, either inserts or deletes)</li><li><strong>Trim horizon</strong> — Process all records in the stream, even those created before the lambda/event source mapping was created</li></ul><p>In this example, we are going to choose latest in order to avoid extra executions of our lambda — which burns our account’s concurrency, wastes money, delays processing of more important (and more recent) events, as well as making debugging more difficult (as your logs will now be polluted with far more entries). However, there are certainly cases in which it makes sense to use trim horizon 😉.</p><pre>VmPackingLambda:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      CodeUri: vm-packing/<br>      Description: This lambda processes the requests for launching instances<br>      Events:<br>        IdempotencyTableInsert:<br>          Type: DynamoDB<br>          Properties:<br>            Stream: !GetAtt RequestIdempotencyTable.StreamArn<br>            <strong>StartingPosition: LATEST</strong> <em><br>            </em>FilterCriteria:<br>              Filters:<br>                - Pattern:   &quot;{ \&quot;eventName\&quot;: [ \&quot;INSERT\&quot; ] }&quot;</pre><h3>Next Steps</h3><p>At this point, we would likely use some sort of <a href="https://en.wikipedia.org/wiki/Bin_packing_problem">bin (vm) packing algorithm</a> to determine which physical hardware to use to launch the given instance (but that is another topic for another article 😉).</p><h3>Conclusion</h3><p>In this article we have seen one potential use case for using lambda event filtering — that is to only process inserts/updates to a dynamodb table while ignoring deletes from either api calls or items that reach their time to live and are automatically deleted from the table. We used this capability to continue on creating our clone of ec2, and it is a very useful feature that you can use in any project you may have.</p><h3>Related Links</h3><p><a href="https://gitlab.com/connorbutch/ec2-clone">Connor Butch / ec2-clone · GitLab</a></p><h3>Further Reading</h3><ul><li><a href="https://aws.amazon.com/blogs/compute/filtering-event-sources-for-aws-lambda-functions/">Filtering event sources for AWS Lambda functions | Amazon Web Services</a></li><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html">Using AWS Lambda with Amazon DynamoDB</a></li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/metrics-dimensions.html">DynamoDB Metrics and Dimensions</a></li><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/monitoring-metrics.html">Working with Lambda function metrics</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b87d8cd8778" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Rebuild AWS EC2 (Part 1)]]></title>
            <link>https://medium.com/@connorbutch/lets-rebuild-aws-ec2-part-1-a53349f8e5a?source=rss-efbfc5b6ca1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a53349f8e5a</guid>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Connor Butch]]></dc:creator>
            <pubDate>Mon, 18 Apr 2022 13:16:17 GMT</pubDate>
            <atom:updated>2022-04-28T01:05:21.062Z</atom:updated>
            <content:encoded><![CDATA[<h4>Looking deeper into some of the nuances of ec2 (idempotency, retries, conditional writes, time to live, etc) and extrapolating them to other system designs</h4><p>Let’s pretend we are building a replica of <a href="https://aws.amazon.com/ec2/">ec2</a> (or at least part of it). We are focusing on the <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html">run instances functionality</a>. Specifically, we will be considering building this command for use from within an <a href="https://en.wikipedia.org/wiki/Infrastructure_as_code">iac orchestrator</a> (such as <a href="https://www.terraform.io/">terraform</a> or <a href="https://aws.amazon.com/cloudformation/">cloudformation</a>).</p><p><em>NOTE: this is meant to be demonstrative of how ec2 might be designed and to show concepts we can apply when designing our apis, and while it is close to how ec2 works, it might differ slightly (for example, having a simpler request so we can focus on system design) rather than function exactly the same as ec2 does.</em></p><h3>Special Considerations</h3><p>Before we even get to launching the instance, there are a few special considerations that I’d like to draw your attention to; please keep these in mind while reading (as they will help solidify why we design the system the way that we do):</p><h4>Remember that <a href="https://www.linkedin.com/pulse/everything-fails-all-time-fernando-schubert#:~:text=Let&#39;s%20go%20back%20to%20our,fail%2C%20usually%20sooner%20than%20later.">everything fails all the time</a>, so <a href="https://aws.amazon.com/builders-library/making-retries-safe-with-idempotent-APIs/?did=ba_card&amp;trk=ba_card">our requests must be retryable</a></h4><p>This allows clients to blindly retry when they do not recieve a 2xx or 4xx response</p><h4>We must launch <em>exactly one</em> instance for a given request and its associated retries</h4><p>This helps manage cost and ensure we don’t launch extra instances that aren’t tracked via iac</p><h4>We must return <em>the same response, including the same reservation id </em>for both an original request and its associated retries</h4><p>This lets the iac tool track the instance it has launched for updates and deletions (for example, keeping track of the instance by reservation id in the tfstate file). This is not possible if retries do not return the same reservation id.</p><h3>System Overview</h3><h4>Client-Side Flow</h4><p>The client populates the request with information about the instance(s) to launch. For simplicity’s sake, <em>our example only takes in the instance type and a client token</em> (see an example request below), but the actual <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html">run instances api</a> request has much more information.</p><pre>{<br>  &quot;instanceType&quot;: &quot;t2.large&quot;,<br>  &quot;clientToken&quot;: &quot;27d49fc2-996c-41b7-b945-5da9f6ddb2a5&quot;<br>}</pre><p>When making a request, the client generates a unique id for use in the <em>clientToken</em> field. The client then makes a launch instance request, passing the clientToken and instance type. If the the client does not get a 2xx or 4xx response, the client retries the same request (using <a href="https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/">exponential backoff and jitter</a>) with the <strong>same clientToken</strong> until it receives either a 4xx or 2xx response or exceeds a maximum number of retries.</p><h4>Server-Side Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XZJOUjdMwx1sdSZUw-CRjg.png" /><figcaption>Server-side architecture is shown featuring an api gateway, lambda, and dynamodb table</figcaption></figure><p>On the server-side, we have a REST (post) endpoint exposed via the api gateway, which accepts a request to launch a new instance. This api gateway routes traffic to a lambda backend, which performs basic validation that cannot be done by the api gateway based on the open api specification. If the request is invalid, it returns a 400. Otherwise, it generates a unique reservation id for the instance to be provisioned, and then it attempts to save the request and the to dynamodb using a conditional update. If the updateitemrequest succeeds, then we know this is the first time handling this request, and we know the reservation id is the one we just generated.</p><p>If the write fails with a <em>ConditionalCheckFailedException</em>, then we know that this is a retry for a request that we already initiated the instance provisioning process. We query the table to get the reservation id we generated for the original request with the same clientToken, and include this id in the response.</p><pre>{<br>  &quot;reservationId&quot;: &quot;1620c4cd-1b34-4af3-a89b-815a9d5a650f&quot;<br>}</pre><p><em>NOTE: the actual ec2 implementation also checks if you pass the same request for the same clientToken. If you pass the same clientToken for different request bodies (within a given period), it will return an error, however I ommitted this here for simplicity’s sake 😜</em></p><p><em>After this, we would likely have a lambda that subscribes to the change stream for inserts (using event source filtering to not be triggered for deletes), and actually provisions the instance (not discussed in this article, but maybe I’ll write about it in a later one 😉).</em></p><h3>Optimization</h3><p>We’ve configured our dynamodb table with a ttl attribute (named ttl). When we write items to the table, we specify a ttl for five minutes later than the current time. <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html">Dynamodb will automatically delete items</a> (approximately) five minutes after we write them, which save us money on storage costs and keep our table size smaller (easier to debug). You can see this done in our sam template <a href="https://gitlab.com/connorbutch/ec2-clone/-/blob/main/template.yaml#L42">here</a>.</p><h3>Nuanced implementation details</h3><p>When I first started, I thought I would use a combination of two features (conditional update and return values), to execute this in a single call, but I had to change plans. This is because when a condition is violated for a conditional update in dynamodb, the <em>client throws a ConditionalCheckFailedException and does not return the existing values</em>. Hence, we have to try to perform the conditional insert to dynamo, and perform different actions based on whether or not the write attempt throws a ConditionalCheckFailedException.</p><p>If it writes successfully, this means that it is our first time handling this request (i.e. it is not a retry of an original request that already reached us with the same clientToken), and we can return the generated reservation id. If it fails with a ConditionalCheckFailedException (only catch this specific exception, not all exceptions), then we know this is a retry of a request that we have already handled. Thus, we must make a getitemrequest to retrieve the previously generated reservation id. However, this design can lead to latent bugs (as it <a href="https://aws.amazon.com/builders-library/avoiding-fallback-in-distributed-systems/">is a form of fallback, which we should look to avoid whenever possible</a>). To minimize the drawbacks associated with fallbacks, we must do the following:</p><ul><li>emit individual metrics on both retries and original requests, and set separate alarms on both statistics</li><li>routinely excercise (test) all code branches to avoid latent bugs associated with rarely executed fallbacks</li></ul><h4>Metrics</h4><p>In order to properly operate our system, we should create the following metrics using <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html">emf</a>. These metrics should live in the namespace <em>replicaOfEc2, </em>have<em> no dimensions, </em>and have a single attribute<em> clientToken (</em>which has the clientToken passed in the request<em>). </em>This can then be <a href="https://medium.com/@connorbutch/bite-sized-aws-part-one-90dd54879717">used with cloudwatch logs insights to gather information on a specific request when needed</a> while keeping costs low (there are tons of benefits of using this, and I highly recommend you read this <a href="https://medium.com/@connorbutch/bite-sized-aws-part-one-90dd54879717">article</a> giving more details). You can use the count aggregator to see how many requests of each type (originals versus retries) are being sent to your service; and you can use the p99 aggregator to look at the 99th percentile latencies for a given action.</p><ul><li>insertSuccessLatency — time taken to insert on a non-retry request</li><li>insertDuplicateLatency—time taken to attempt an insert on a retry (and fail the condition check)</li><li>retrieveExistingLatency — time taken to retrieve the existing reservation id</li><li>nonRetryTotalLatency — total time taken for a non-retry request</li><li>retryTotalLatency —total time taken for a retry request</li></ul><p>You can (and should) use these metrics for separate alarms and display then on your dashboard</p><h3>Exercising all code branches</h3><p>It is well-documented that having <a href="https://aws.amazon.com/builders-library/avoiding-fallback-in-distributed-systems/">fallback (or branching in general) in distributed systems</a> can result in bad consequences. However, in cases where we must have branching, we can minimize the chance of latent errors by continually exercising <em>all branches</em> within our code using <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html">cloudwatch synthetics (canaries)</a>. I’ll write another article on this, but the point you should take away from this is to ensure that you are regularly excercising any code branches you have to discover bugs before they become latent and bring down your system.</p><h4>Handling race conditions</h4><p>In addition to using metrics/canaries to avoid fallback, we also need to pay special care to avoid race conditions, which can result in two instances being launched. This might occur if we make a get item request first, then if it does not exist, make a put item request. To get an idea of how this could occur, please consider the following situation</p><p>A request goes over network, hits considerable latency (say an extra second delay), it eventually reaches the server, it checks and no item exists for token. At this point, the request is still going to be processed, but the client has timed out, so it sends a retry. The retry doesn’t experience much latency, so it reaches before the original request has written to the database, so it makes a updateitem request with a random id. At around the same time the first request will make a updateitem request with a different id. This results in two items being written to the change stream for the same clientToken, which will result in two instances being launched for the same request, which is a clear violation of our requirements.</p><p>In order to avoid this double write, we follow the architecture described above in this article, with a conditional write performed first, then if it fails, performing a fetch.</p><h3>See it in action</h3><p>In order to run the application:</p><ul><li>clone the repo</li></ul><pre>git clone git@gitlab.com:connorbutch/ec2-clone.git</pre><ul><li>run the provided sam template to provision the infrastructure and copy the output api gateway url</li></ul><pre>sam build &amp;&amp; sam deploy --guided</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*nkxwWuJFjLEIZ5y2tX7MTw.gif" /><figcaption>Deploying your own copy of these stack is easy!</figcaption></figure><ul><li>run the cucumber tests that don’t involve retries</li><li>look at the associated report, which shows the cucumber tests results</li><li>look at the cloudwatch dashboard —notice that this only shows metrics for original requests (the metrics for retries are not present yet)</li></ul><pre>cd launch-instance/ &amp;&amp; npm run cucumberNonRetry</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*er_P9_yVMs7ro60U5yAdYg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwz6kkzEIL33mbwYT-N9rg.png" /><figcaption>Here is an example of the report that is generated and automatically opened after running tests (notice the @NonRetry scenario tag)</figcaption></figure><ul><li>now run the cucumber tests associated with retries and view the associated test results</li><li>now open the cloudwatch dashboard — notice that it now shows metrics for retries</li></ul><pre>cd launch-instance/ &amp;&amp; npm run cucumberWithRetry</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*W49bTOAUtrPjilqqfTAMJQ.gif" /><figcaption>Here is a video running the retries now — notice the dashboard now has stats for retry statistics (bottom row)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OqEkItL9hnsEnfzY9DPnZg.png" /><figcaption>Here is an example of the report that is generated and automatically opened after running tests (notice the @Retry scenario tag)</figcaption></figure><h3>Other applications</h3><p>As mentioned above, the ideas in this article can (and should) be applied to other contexts as well. Consider, for example, a crm solution similar to <a href="www.salesforce.com">salesforce</a> in which an individual can be created/registered using a variety of different identifying information (say ssn, drivers license number, etc). In this case, the api can accept a post request containing pertinent information (i.e. a specific field such as ssn) and return an id for the party inside of the crm. This could be used with <a href="https://aws.amazon.com/blogs/compute/creating-a-single-table-design-with-amazon-dynamodb/">single table design</a>, where the partition (primary) key is a combination of a prefix concatenated with an underscore then a value (i.e. an ssn of 123456789 could be stored as ssn_123456789 and a drivers license of b111111111 could be license_b1111111)… but that’s another topic for another article 😉</p><pre>{<br>  &quot;ssn&quot;: &quot;123456789&quot;<br>}</pre><p><em>creating a party based on ssn would have a request like this</em></p><pre>{<br>  &quot;driversLicenseNumber&quot;: &quot;b111111111&quot;<br>}</pre><p><em>creating a party based on drivers license would have a request like this</em></p><p>These items could both be stored in the same table as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*THAH-rnWnAM9B40P7FcpVA.png" /><figcaption>An example using single table design showing two different parties being created — one identified by drivers license and one identified by ssn</figcaption></figure><p><strong>This could also be used for making </strong><a href="https://martinfowler.com/bliki/CQRS.html"><strong>cqrs</strong></a><strong> and event sourcing idempotent (since, by default, event sourcing is not idempotent).</strong></p><h3>Conclusion</h3><p>In this article, we “recreated” a portion of ec2’s launch instance capabilities; and in doing so, we have seen that that there are many subtle implementation details that are important when creating a highly-usable service. We were reminded that all apis must be idempotent, and client sdks should automatically retry non success responses that do not contain validation errors using exponential back off and jitter. We also saw that in order to provide our clients (specifically those using iac) with the best experience possible, we must go beyond idempotency, and also return the same response for any given request and its associated retries. This allows clients to track the ec2 reservation id for comparison when determining what actions to take upon the instance. We implemented this by having a client pass a unique clientToken for a given request (and its associated retries). We then generated a unique reservation id, and attempted to save using dynamodb conditional writes with the clientToken as the partition key. If it suceeded, then return the response to the client. If it failed, then go ahead and retrieve the existing item and return that in a response to the client. While this implementation may seem specific to ec2, we can extrapolate these design patterns and use them when designing a wide variety of systems.</p><h3>Related Links</h3><p><a href="https://gitlab.com/connorbutch/ec2-clone">Connor Butch / ec2-clone · GitLab</a></p><h3>Further Reading</h3><ul><li><a href="https://aws.amazon.com/builders-library/making-retries-safe-with-idempotent-APIs/?did=ba_card&amp;trk=ba_card">Making retries safe with idempotent APIs</a></li><li><a href="https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/">Timeouts, retries and backoff with jitter</a></li><li><a href="https://www.alexdebrie.com/posts/dynamodb-condition-expressions/#1-confirming-existence-or-non-existence-of-an-item">Understanding DynamoDB Condition Expressions</a></li><li><a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html">RunInstances</a></li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html">Using time to live (TTL) in DynamoDB</a></li><li><a href="https://aws.amazon.com/cloudformation/">Provision Infrastructure as Code - AWS CloudFormation - AWS</a></li><li><a href="https://www.terraform.io/">Terraform | HashiCorp Developer</a></li></ul><p>Be on the lookout for the next article in the series, where I discuss the next part of this ec2 replica.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a53349f8e5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bite-sized AWS (Part Two)]]></title>
            <link>https://medium.com/@connorbutch/bite-sized-aws-part-two-88b6ea3f76b3?source=rss-efbfc5b6ca1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/88b6ea3f76b3</guid>
            <category><![CDATA[aws-x-ray]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Connor Butch]]></dc:creator>
            <pubDate>Mon, 07 Mar 2022 13:39:24 GMT</pubDate>
            <atom:updated>2022-03-07T13:39:24.759Z</atom:updated>
            <content:encoded><![CDATA[<p>Using <a href="https://aws.amazon.com/xray/">AWS x-ray</a> to trace and debug events across distributed systems</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*hwoCXLok1Eadr-xQSN11kQ@2x.jpeg" /><figcaption>some spinach artichoke appetizers look good right now (<a href="https://www.pinterest.com/pin/319333429823620775/">src</a>)</figcaption></figure><p>As always, you can skip to the code used in this example, found <a href="https://gitlab.com/connorbutch/loan-app">here</a></p><h3>Modern Challenges Require Modern Solutions</h3><p>As competitive markets demand more and more reliable business capabilities with less and less downtime, software systems inevitably move from monolithic applications to distributed microservices, and their exchanges evolve <a href="https://aws.plainenglish.io/stop-making-synchronous-calls-f101af15cd46">from synchronous RPCs (such as REST) to asynchronous, event-driven interactions</a>.</p><p>While these modernizations certainly have a lot of benefits (such as greater reliability emphasized above), they also brings with them new challenges that are not present in old school, monolithic systems. One of them is distributed tracing, which <a href="https://www.dynatrace.com/news/blog/what-is-distributed-tracing/#what-is-distributed-tracing">dynatrace defines as</a></p><blockquote>a method of observing requests as they propagate through distributed cloud environments</blockquote><p>To better understand the benefits of distributed tracing, please consider the following use case for a loan application system.</p><h3>Business Use Case — A Loan Application System</h3><p>Pretend you are in charge of a team that develops and operates a system for handling loan (i.e. mortgage) applications. End users request a loan for a certain amount of money, and our system either approves or rejects the application based on the requestor’s credit history.</p><h3>System architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*crkoo5BtAjlyt7rlF-KK6w.png" /><figcaption>Our system architecture is shown here</figcaption></figure><ul><li><a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html">Api gateway</a> triggers the validation <a href="https://aws.amazon.com/lambda/">lambda</a>. It is triggered by a put request. The open api spec is found <a href="https://gitlab.com/connorbutch/loan-app/-/blob/main/openapi-spec.yaml">here</a> and a screenshot of the relevant operation can be found at the bottom of the section</li><li>loan-validation <a href="https://aws.amazon.com/lambda/">lambda</a> validates the loan application. If request is valid, it publishes the request as an event to <a href="https://aws.amazon.com/sns/?whats-new-cards.sort-by=item.additionalFields.postDateTime&amp;whats-new-cards.sort-order=desc">sns</a> with an attribute of “<em>type=LOAN_REQUESTED</em>”</li><li>credit-history lambda is triggered by <a href="https://aws.amazon.com/sqs/">sqs</a>, which has a subscription to the loan event topic for “<em>type=LOAN_REQUESTED</em>”. It pulls credit history for the requestor (for the sake of this example, I created a <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html">cloud formation custom resource</a> that loads the table with data), combines it with the loan request, and places a message on sqs with the conglomerated event containing credit history and loan request.</li><li>loan-decision lambda is triggered by sqs; if credit score greater than 700, approve the application, otherwise, reject it. If approved, publish an event to loan event topic with attribute “<em>type=LOAN_APPROVED</em>”, and if rejected, publish with attribute attribute “<em>type=LOAN_REJECTED</em>”</li></ul><p><em>There are two other lambdas that publish metrics using emf (one for loan rejected and one for loan accepted events), but I ommitted them for the sake of brevity in the diagram.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v48_xsn1JyjD1KFTMrpKHQ.png" /><figcaption>Here is the only operation defined in our open api spec for this demo</figcaption></figure><h3>What capabilities does x-ray provide?</h3><p>Before I go farther and give specific examples of how x-ray can be used to provide business value for our loan system, I will give a brief overview of what technical capabilities x-ray provides. First and foremost, x-ray gives us the ability to create segments and subsegments (subsegments are just segments nested inside other segments). Segments/subsegments consist of a name, as well as additional optional information contained in annotations, metadata, and exception information.</p><ul><li><strong>annotations</strong> — these are <strong>user-defined key/value pairs that are indexed and can be used to search for specific traces</strong>. You can perform exact matching, contains, starts with, etc. Use this for values such as <em>ids</em> (in our example, I create a custom annotation for loan application id)</li><li><strong>metadata</strong> — this is unindexed data (usually arranged in JSON format) stored in user-defined key/value pairs. Use this for larger text that does not need to be searched on, but <strong>provides useful information for debugging</strong> (in our example, we hold <em>http request/response bodies, what we send to sns, and the items retrieved from dynamodb</em>. Other useful use cases are for <em>sql queries</em>, grpc calls)</li><li><strong>exceptions</strong> — this holds <strong>stack traces for exceptions</strong> that occurred during a given trace. Use this to debug what went wrong when processing a certain event. Uncaught exceptions automatically show up here, and you can programmatically add caught exceptions to a segment/subsegment.</li></ul><p><em>Xray also comes with various other capabilities, such as service graphs, and visualizations for latency for given subsegments, but for the sake of brevity, I am not focusing on them in this article.</em></p><h3>Why do you need distributed tracing?</h3><p>Now that we’ve seen the various parts of a segment, let’s see how we can use them.</p><p>Put back on your loan app team lead hat, and now you are getting asked a various questions involving your loan application. These questions come from actuaries, customer service staff, management, and sometimes from other engineers. A few of these are listed below; and for each question, I show how to answer it with x-ray.</p><p><em>If you would like to recreate try these requests yourself, you can find the postman collection in the </em><a href="https://gitlab.com/connorbutch/loan-app/-/tree/main/postman"><em>repo</em></a><em> (just change the loan base url to the output of your cloudformation stack).</em></p><h4>Actuaries ask, “why was this loan application with id <em>f3be0c7c-9b42–4d77–8c54–4106c29b484f </em>rejected?”</h4><ul><li>search for traces involving the loan annotation id in the loan decision lambda (<em>annotation.loanApplicationId=”f3be0c7c-9b42–4d77–8c54–4106c29b484f” and service(“loan-decision-function”</em>)<em>)</em>)</li><li>click on the trace, click on the approvalDecision subsegment, then click the metadata tab to view the debug information available; which gives a clear reason for rejection, “Customer credit score of 625 is less than required credit score of 700”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52vLB1Ad7YhKuW8TLNn_NA.gif" /><figcaption>Here we go ahead and submit a loan, then look at why it is rejected using the metadata</figcaption></figure><h4>Customer service team asks, “we are seeing slowness in making a decision on this loan, what’s taking so long?”</h4><ul><li>search for traces involving the loan annotation id in the loan decision lambda <em>(annotation.loanApplicationId=”193da82a-530d-4144–8c74-f2ad050dfabf”</em>)</li><li>Look at size of subsegment (circled below)— this gives us an idea that this part of processing is slow</li><li><em>See later points about alternative ways to do this as well</em></li></ul><p><em>At scale, we would need cloudwatch metrics/alarms on this</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tEUxJ8BZuqI3KaIn" /><figcaption>Looking at the circled part, you can see that the loan approval decision took 7 seconds for this particular loan — if you go ahead and look at the other traces, the decision will take 0 seconds (maybe a few ms)</figcaption></figure><h4>On call engineer asks, “why did a user get an error submitting this loan application request (request id 1646417701892)? Can I see the stack trace anywhere?”</h4><ul><li>search for traces involving the request id (<em>annotation.requestId=1646417701892</em>)</li><li>Look at the exceptions tab to view the stack trace. Here we see our “fake” exception was thrown. We can use this to debug, and fix, application errors.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBjz1e9yYtZXiwXsHuhm1g.gif" /><figcaption>Here you can see that we search based on the request id to get the relevant trace, then click the subsegment with the red exclamation point, and we can see the stack trace</figcaption></figure><h4>AWS account executive informs us of that some customers are reporting elevated sns latencies, and management asks us, “Is this impacting your teams?”</h4><ul><li>click on any arbitrary trace</li><li>ensure your aws clients are wrapped with x-ray interceptors (see below section on nuanced usage details)</li><li>look at the graph at the top which shows aws service latencies and see if it’s impacting a given request</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ayhn85nOMjukZxaYJ-Strw.png" /><figcaption>We can do a quick sampling to confirm our metrics which show that in our aws account, sns latencies are somewhat normal (the circle in the top box shows this)</figcaption></figure><h3>Nuanced Nodejs Usage Details</h3><p>While the ways of using x-ray to create traces is generally the same across languages, here are a few nuanced <a href="https://nodejs.org/en/">Nodejs</a> specific details.</p><h4>Automatically capturing outgoing aws calls</h4><ul><li>You can automatically instrument outgoing calls to other aws services (such as sns, s3, dynamodb, etc) by <a href="https://gitlab.com/connorbutch/loan-app/-/blob/main/loan-validation/app.js#L8">wrapping the client</a> on instantiation. You can read the docs about this technique <a href="https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-awssdkclients.html">here</a>, and below you can see a relevant code snippet.</li></ul><pre>const snsClient = AWSXRay.captureAWSv3Client(new SNSClient({region: process.env.AWS_REGION}));</pre><p>you can then use the client exactly as you would normally</p><h4>Wrapping functions in subsegments</h4><ul><li>You can automatically create named subsegments for function calls (both synchronous and asynchronous functions) using the <a href="https://gitlab.com/connorbutch/loan-app/-/blob/main/credit-history/app.js#L16">captureFunc</a> and <a href="https://gitlab.com/connorbutch/loan-app/-/blob/main/credit-history/app.js#L14">captureFuncAsync</a> methods in the sdk. You can read the docs about this technique <a href="https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-subsegments.html">here</a>. Note, that when using capture function async, you must close the subsegment yourself, and you must add errors to the subsegment on your own.</li></ul><pre>const errors = AWSXRay.captureFunc(&#39;validateRequest&#39;, <br>                function () {<br>                     return validateRequest(event);<br>                })</pre><p>here is an example using capture function for synchronous code</p><pre>response = await AWSXRay.captureAsyncFunc(&#39;handleValidRequest&#39;, async function (nestedSubsegment) {<br>                    return await handleValidRequest(event, loanApplicationId, nestedSubsegment);<br>                })</pre><p>here is an example using capture function async (make sure to use await 😉)</p><h3>Other Neat X-ray Tricks</h3><p>Those are some <a href="https://nodejs.org/en/">Nodejs</a> specifics, but there are tons of neat ways to utilize x-ray across different languages. For example, when I had worked with <a href="https://www.java.com/en/">Java</a>, we created custom annotations which automatically generated named subsegments for us (and optionally allowed us to publish latency metrics) using <a href="https://dzone.com/articles/working-gradle-spring-aspects">aspectj compile-time weaving</a> (you could do this with a custom annotation processor, or a <a href="https://docs.oracle.com/javaee/6/tutorial/doc/gkhqf.html">decorator</a> as well). There’s a great article by my friend Ben on how to do this, which you can find <a href="https://benjaminhoogterp.medium.com/write-an-annotation-processor-for-java-c9cd6d9cc93f">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dL357HU5tg0-tbbKK0G2jQ.png" /><figcaption>This shows how we had implemented a custom annotation to automatically create a named subsegment (and an optional cloudwatch latency metric). Simply add the annotation, and bang, you’re done.</figcaption></figure><h3>Things to keep in mind</h3><p>While we’ve shown the vast capabilities of x-ray and how it can be used to answer difficult questions, it has a quirks you must keep in mind when using it:</p><ul><li>By default, X-ray <strong>only samples a small percentage of requests</strong> ; <a href="https://docs.aws.amazon.com/xray/latest/devguide/xray-console-sampling.html">it samples the first request every minute, but then only 5% of requests after that</a></li><li>You can adjust the sampling rate, but you will have to <a href="https://aws.amazon.com/xray/pricing/"><strong>pay for the number of traces created</strong></a>, which can get <strong>expensive</strong> quite quickly</li><li>There is a <a href="https://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html">limit to the size of the x-ray segments you can send</a> (<em>64kb</em> at time of writing), which can limit what you can include in the metadata section</li></ul><p>On top of the above considerations regarding x-ray itself, there are a few other things to keep in mind regarding your usage of the tool:</p><ul><li>X-ray (generally speaking) can only be used to get latency for single request; <strong>you should always use cloudwatch metrics for bigger picture alarms, and only use x-ray to confirm suspicions for an individual event</strong></li><li>It can be <strong>difficult</strong> to <strong>search for traces</strong> based on an annotation value in most lambdas, where items are retrieved in <strong>batches</strong>, and usually get batched when sent in requests (for cost optimizations, since you pay per request, as well as latency, since each call adds latency to your app). In this case, you have to use string contains on your searches for x-ray traces. You will notice this in the credit-history lambda, which uses a <a href="https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchGetItem.html">batch get item</a>.</li></ul><h3>Alternative, often better, solutions</h3><p>Given that, by default, x-ray only samples a small percentage of requests, and that sampling more than that can be quite expensive at scale, you might be wondering, “<strong>is there a way we can answer the questions above</strong> (such as “why was this loan application rejected?”) <strong>without paying an arm and a leg for x-ray</strong>?”</p><p><strong>Here is where other aws services, namely </strong><a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html"><strong>emf</strong></a><strong> and </strong><a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html"><strong>cloudwatch logs insights</strong></a><strong>, come in handy</strong> (I’ve written <a href="https://medium.com/@connorbutch/the-hardest-issue-to-debug-with-aws-lambda-d636d672d6bc">an article showing how to use these services to debug timeouts in aws lambda</a> and<a href="https://medium.com/@connorbutch/bite-sized-aws-part-one-90dd54879717"> an article on using emf for generating metrics and using the emf logs for generating adhoc metrics</a> on high cardinality dimensions as needed).</p><p>Even if you choose not to use emf, you should still write your logs in json format, so that you can query the latency for a given loan application when needed without paying to track every request in x-ray or for tons of custom cloudwatch metrics. This allows you to only pay for business value, the same way tools like lambda allow you to only pay for the compute resources you consume.</p><p>In the end, keep in mind that because you can use x-ray to answer certain questions, that doesn’t mean it is necessarily the best way to find the answers (and to consider using emf/cloudwatch logs insights instead).</p><h3>Conclusion</h3><p>In this article we’ve been reminded that tracing and debugging in distributed systems is a new challenge that is not faced in monolithic designs. We’ve seen how aws x-ray makes this challenge easier by giving us the ability to perform distributed tracing. We used x-ray to find traces for a particular loan application within a particular lambda by searching on a custom annotation for the loan application id, as well as specifying the lambda name. We then used the metadata section of the trace to view the information surrounding a users credit history when it was in the decision lambda. This allowed us to verify that the correct decision was made to reject the loan application. Finally, we used x-ray to quickly find the stack trace for requests that ended in errors.</p><p>We were also reminded that although x-ray can be very useful, there are quite a few “gotchas” you should consider before relying on the service as a large part of your production support plans. The default sampling rate is 5%; so you likely won’t have traces for the vast majority of events in a high-traffic system. While you can increase the sampling rate, this will increase your cost, and in almost all use cases, it is often better to use cloudwatch logs insights (usually with emf) to run queries as needed for a given event, as opposed to paying for 100% sampling rate for x-ray. It is also best practice to use cloudwatch metrics to get a general view of your system, then to use logs insights or x-ray to examine a specific request.</p><p>Well, I hope you enjoyed this bite-sized nugget of aws knowledge, and stay tuned for more (maybe we will have some desert next week).</p><h3>Related Links</h3><p><a href="https://gitlab.com/connorbutch/loan-app">Connor Butch / loan-app</a></p><h3>Further Reading</h3><ul><li><a href="https://aws.amazon.com/xray/">Debug Tool - AWS X-Ray - AWS</a></li><li><a href="https://aws.plainenglish.io/stop-making-synchronous-calls-f101af15cd46">Stop making synchronous calls!</a></li><li><a href="https://medium.com/@connorbutch/bite-sized-aws-part-one-90dd54879717">Bite-Sized AWS (Part One)</a></li><li><a href="https://docs.aws.amazon.com/xray/latest/devguide/xray-console-sampling.html">Configuring sampling rules in the X-Ray console</a></li><li><a href="https://docs.aws.amazon.com/xray/latest/devguide/xray-console-filters.html#console-filters-string">Using filter expressions to search for traces in the console</a></li><li><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html">Custom resources</a></li></ul><p>I used a custom resource along with aws sam automatic upload to s3 capabilities to take data from a json file in our repo to s3, inserting the contents into our template, and then inserts this json into dynamodb as test data for these examples. I plan on doing a full article on these in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88b6ea3f76b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bite-Sized AWS (Part One)]]></title>
            <link>https://medium.com/@connorbutch/bite-sized-aws-part-one-90dd54879717?source=rss-efbfc5b6ca1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/90dd54879717</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[sre]]></category>
            <dc:creator><![CDATA[Connor Butch]]></dc:creator>
            <pubDate>Mon, 21 Feb 2022 13:52:37 GMT</pubDate>
            <atom:updated>2022-02-21T13:52:37.524Z</atom:updated>
            <content:encoded><![CDATA[<p>Using EMF together with cloudwatch logs insights for monitoring and debugging your AWS applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*exef90QNrg8racry.jpg" /><figcaption>Pictures of tapas has me missing Madrid (<a href="https://cdn.contexttravel.com/image/upload/w_1500,q_60/v1612522198/blog/What%20is%20Tapas%20-%20Best%20Tapas%20in%20Madrid/shutterstock_1392833918.jpg">img src</a>)</figcaption></figure><p><em>As always, you can skip to the code used in this example, found </em><a href="https://gitlab.com/connorbutch/weather-app"><em>here</em></a></p><h3>What is EMF</h3><p><a href="https://aws.amazon.com/about-aws/whats-new/2019/11/amazon-cloudwatch-launches-embedded-metric-format/">Embedded metric format (EMF)</a> is an AWS service that automatically processes logs written to cloudwatch. When it detects logs written in a <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html">specific format</a>, it parses a metric name, values, and optional dimensions from the log stream and publishes them as custom metrics data point(s). Outputting logs in this specified format is easy to do using AWS-provided <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Libraries.html">sdks/libraries/modules,</a> which are available in various languages (we show this in the example part of our article). Using any of these libraries will result in metrics being published to cloudwatch.</p><h3>Why EMF?</h3><p>There are quite a few ways to generate and track metrics, some of which include:</p><ul><li><a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_PutMetricData.html">cloudwatch putmetricdata call</a></li><li>custom log parsing with <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html">cloudwatch logs insights</a> (here is <a href="https://gitlab.com/connorbutch/debugging-lambda-timeouts/-/blob/main/template.yaml#L103">an example</a> from my debugging lambda timeout article)</li><li>datadog <a href="https://docs.datadoghq.com/api/latest/metrics/">REST api call</a></li><li>datadog <a href="https://docs.datadoghq.com/developers/dogstatsd/?tab=hostagent">dogstatsd client</a></li></ul><p>So <em>why would we use EMF over the above options</em>? Find a few of the reasons below:</p><ul><li><strong>Latency </strong>— making an out of process call (especially <a href="https://www.khanacademy.org/computing/computers-and-internet/xcae6f4a7ff015e7d:the-internet/xcae6f4a7ff015e7d:transporting-packets/a/transmission-control-protocol--tcp">TCP</a> calls) will add latency to your application; writing to logs will be quicker</li><li><strong>Reliability </strong>— by writing to the logs, we allow the metrics to be processed asynchronously, which increases our reliability</li><li><strong>Cost effectiveness</strong> — by writing metrics to logs, we eliminate the cost of making <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_PutMetricData.html">PutMetricData api calls</a></li><li><strong>Debugging/Extensibility</strong> — by writing to logs in EMF format, we can run ad hoc queries against high cardinality properties (such as companyId) using cloudwatch logs insights.</li><li><strong>Security</strong> —applications no longer need cloudwatch:PutMetricData permissions, or the ability to get a key from secrets manager to call a service like datadog, which strengthens security posture</li><li><strong>Flexibility </strong>— in some situations, you may not have the ability to control the environment running the code where you would like to publish metrics from (for example, another team might be using your generated rest client). In this case, the lambda including your sdk might not have permissions to invoke putMetricData, but it is highly unlikely they lack permissions to write to the logs.</li></ul><h3>Business Use Case</h3><p>Now that we’ve seen the theory behind why we would use EMF over other methods for generating metrics, let’s look at a real-life use case involving EMF.</p><p>Pretend you are running a weather forecasting company with a SaaS business model. You provide a REST api, which is really just a proxy which calls out to another api (say weather.com) to get the data and manipulate it a little bit. Latency is important to your customers, so you want to know how long calling weather.com takes (versus how long it takes for you to manipulate the data), so you create a custom cloudwatch metric for weather.com latency.</p><p>Weather.com also offer a few different major versions of their client library with similar features (say 1.0, 2.0, and 3.0 for this example). All of them work and provide the features you need, hence you want to know the latency for each version, so that you can choose the one that offers the lowest latency.</p><p>In addition, you want to have the capability to query for latency on a company by company basis <strong>when needed </strong>(on an <strong>infrequent basis</strong>). This might amount to .05% of your companies once every few months.</p><p>You wisely decide to use EMF for creating metrics, and implementation details are given below.</p><h3>Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bb0-BaxOvNQ88w2SYKL2Qg.png" /><figcaption>Architecture diagram for our weather api</figcaption></figure><p>The architecture consists of the following components</p><ul><li>api gateway -&gt; lambda</li><li>lambda simulates a call to the external weather api and records a simulated latency metric <br> –if it is the “slow” company id (indicated by x-company-id header value of <em>90556f50-bed9–47be-a894–863a166ddf45</em>), then return a large latency value<br> –otherwise return a normal latency value</li><li>lambda uses EMF to write latency metric <br> –dimension for sdk version — there are only a few values (1,2,3) and we want to choose a value when seeing latency metrics<br> –property for companyId — don’t have to select company id when querying values, but can be used in cloudwatch logs insights queries</li></ul><h3>Code Excerpt</h3><p>Writing the above-specified metrics using EMF is easy. We produce them with a <a href="https://gitlab.com/connorbutch/weather-app/-/blob/main/weather/app.js#L6">few lines of code</a>, shown below (this is in javascript, but there are clients for many languages, like python, java, etc):</p><pre><strong>const { createMetricsLogger, Unit } = require(&quot;aws-embedded-metrics&quot;);</strong></pre><pre>exports.lambdaHandler = async (event, context) =&gt; {<br>   <strong> const metrics = createMetricsLogger();<br>    metrics.setNamespace(&quot;weather&quot;);</strong><br>    //get weatherClientVersion and latency variable values<br>    <strong>metrics.setDimensions({ &quot;weatherClientVersion&quot;: simulatedVersionNumber.toString() });<br>    metrics.putMetric(&quot;weatherRetrievalLatency&quot;, simulatedTimeToFetchWeatherData, Unit.<em>Milliseconds</em>);<br>    metrics.setProperty(&quot;companyId&quot;, companyId);<br>    await metrics.flush();</strong><br>    //other code can go here<br>}</pre><h3>Deployment</h3><p>To deploy the code to aws, clone the <a href="https://gitlab.com/connorbutch/weather-app">repo</a>, and run the following command in your terminal:</p><pre>sam build &amp;&amp; sam deploy --guided</pre><h3>Generating Traffic</h3><p>To generate traffic against your newly deployed api, you can use the <a href="https://gitlab.com/connorbutch/weather-app/-/tree/main/postman">postman collection</a> included in the repository. While you can run the collection by hand, I prefer to run the collection multiple times using newman. The command to do this is shown below:</p><pre>newman run weather_postman_collection.json --global-var &quot;weatherUrl=&lt;your url here&gt;&quot; -n 20</pre><p>For example, mine looks like this (I have since torn down the url, so this won’t work for you to DDoS me 😉):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qRtd21uoZDYbhB004i--lg.png" /><figcaption>Running a sam deploy spits out the url of your api — go ahead and copy the entire string from https: until the final /</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y5oLBEklm0a0tbDSCfqqrQ.gif" /><figcaption>This video shows how to run the postman collection (against your api) using newman</figcaption></figure><h3>Results</h3><p>After running the above It prints to the logs piece of json that looks like this (I copied this from the cloudwatch log group, picture is shown below):</p><pre>{<br><strong>  &quot;weatherClientVersion&quot;: &quot;1&quot;,</strong><br><strong>  &quot;companyId&quot;: &quot;e4d51ea0-025f-4ef6-aea6-daf6980dd30d&quot;,</strong><br>  &quot;executionEnvironment&quot;: &quot;AWS_Lambda_nodejs14.x&quot;,<br>  &quot;memorySize&quot;: &quot;128&quot;,<br>  &quot;functionVersion&quot;: &quot;$LATEST&quot;,<br>  &quot;logStreamId&quot;: &quot;2022/02/17/[$LATEST]8e96caf7957a4d439f5eeaeca01550c8&quot;,<br>  &quot;_aws&quot;: {<br>    &quot;Timestamp&quot;: 1645071469726,<br>    &quot;CloudWatchMetrics&quot;: [<br>      {<br>        &quot;Dimensions&quot;: [<br>          [<br><strong>            &quot;weatherClientVersion&quot;</strong><br>          ]<br>        ],<br>        &quot;Metrics&quot;: [<br>          {<br><strong>            &quot;Name&quot;: &quot;weatherRetrievalLatency&quot;,</strong><br>            &quot;Unit&quot;: &quot;Milliseconds&quot;<br>          }<br>        ],<br><strong>        &quot;Namespace&quot;: &quot;weather&quot;</strong><br>      }<br>    ]<br>  },<br><strong>  &quot;weatherRetrievalLatency&quot;: 480.9952106324499</strong><br>}</pre><p>Below is a picture of what this looks like from the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RhGOwFoeTN4kHcn7fwi0qw.png" /><figcaption>Here is a screenshot from the aws console, in case you didn’t believe me</figcaption></figure><p>Here is a screen capture of the metric created in cloudwatch with a dimension for the client version. Note that yours will only show the metric with a single dimension (<em>I made a mistake at first which is why I have two extra boxes, which you will not see</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OU_oCh76JfcHysgwJ86gqw.gif" /><figcaption>Here you can see the metric created with various values.</figcaption></figure><h3>Usage With Cloudwatch Logs Insights</h3><p>Now consider that <em>a particular company reaches out to us to discuss latency issues with our service</em>. With just cloudwatch metrics (even the ones created by EMF), we can’t easily see the latency for each company — there are two many companies. In order to search for a given company, we would have to use companyId as a dimension. Using it as a dimension would end up in a different metric for each companyId, so we would lose the ability to see larger trends in the data across companies. We would also rack up quite a large bill, as each individual combination of name and dimension value creates a custom metric, that we are charged for.</p><p>However, this is where cloudwatch logs insights (paired with EMF) comes in handy. It’s an awesome tool that is only available with EMF (this <strong>doesn’t work with metrics published using other means, such as calling the put metric data api</strong>). Since we added companyId as a property (NOT A DIMENSION), we can use cloudwatch logs insights to look at the latency experienced by a particular client. The below query gives us the 95th percentile latency experienced by a given company (this is a company we intentionally simulated really slow response time for):</p><pre><em>stats pct(weatherRetrievalLatency, 95)<br>| filter companyId = &#39;90556f50-bed9-47be-a894-863a166ddf45&#39;<br>| sort @timestamp desc<br>| limit 20</em></pre><p>Using cloudwatch logs insights, we can indeed confirm that the client is seeing slow responses from the weather api — we see their p95 value is more than 2.5 seconds (&gt;2500ms). We’ve confirmed their claim, and now we can investigate further (maybe reach out to weather.com) to help fix their issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PGqnZOL1gT_qp1qKz26nwQ.png" /><figcaption>We can see the 95th percentile for the latency for this particular company is higher than 2.5 seconds — this is something we need to look into for them!</figcaption></figure><h3>Cleanup</h3><p>While this stack shouldn’t cost you any money (since it will be well within the <a href="https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/free-tier-limits.html">free tier usage limits</a>), if you wish, you can tear down your stack. The command to do so is:</p><pre>sam delete</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PhGqGI3gbPtxc4DeogNxVA.png" /><figcaption>Type ‘y’ at every prompt, and at the end, you should see the phrase “Deleted successfully”</figcaption></figure><h3>Summary</h3><p>We’ve seen that EMF is an aws service that allows us to create custom metrics by writing data to our logs in structured format using aws sdks. We’ve seen that in many cases, EMF is preferred over other methods of generating metrics (such as putmetricdata api calls), as it is more generally more secure, cost effective, and reliable. We then looked at a “real-life” example, in which we used EMF to generate a custom metric for latency calling a downstream (third-party) service. This metric had a dimension for the client sdk version, as well as a property for the client id. We’ve used a dimension for the sdk version, since we know that this can hold only a few different values, and we know we must always specify a specific value when filtering the metric latency. On the other hand, we’ve used a property is used for a high-cardinality metric (companyId) and it is not required for filtering metric data. However, if we need to filter on the value of property, we can cloudwatch logs insights to perform queries for a particular value. We used this capability to confirm that a particular company was experiencing above normal latency on a data set that we generated using a postman in combination with newman cli runner.</p><p>Hopefully this helped give a greater understanding of EMF, as well as how it can be used with cloudwatch logs insights, and be on the lookout for more “bite-sized” examples of other aws services moving forward.</p><h3>Related Links</h3><p><a href="https://gitlab.com/connorbutch/weather-app">Connor Butch / weather-app</a></p><h3>Further Reading</h3><ul><li><a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html">Specification: Embedded metric format</a></li><li><a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html">Analyzing log data with CloudWatch Logs Insights</a></li><li><a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html">Publishing custom metrics</a></li><li><a href="https://learning.postman.com/docs/running-collections/using-newman-cli/command-line-integration-with-newman/">Running collections on the command line with Newman | Postman Learning Center</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90dd54879717" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>