<?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 Jaewoo Ahn on Medium]]></title>
        <description><![CDATA[Stories by Jaewoo Ahn on Medium]]></description>
        <link>https://medium.com/@lancers?source=rss-bdf1c6b4acaa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WzkfUflqxV0xe5_t</url>
            <title>Stories by Jaewoo Ahn on Medium</title>
            <link>https://medium.com/@lancers?source=rss-bdf1c6b4acaa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:25:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lancers/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[Amazon API Gateway: WebSocket API + CloudFront Function]]></title>
            <link>https://medium.com/@lancers/amazon-api-gateway-websocket-api-cloudfront-function-ab304fd95ac3?source=rss-bdf1c6b4acaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab304fd95ac3</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[websocket-api-gateway]]></category>
            <dc:creator><![CDATA[Jaewoo Ahn]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 22:27:45 GMT</pubDate>
            <atom:updated>2023-07-25T22:27:45.779Z</atom:updated>
            <content:encoded><![CDATA[<p>In Amazon API Gateway, WebSocket API offers a regional endpoint only while REST API offers Edge-optimized endpoint and Private endpoint in addition to it. You may consider putting your own CloudFront distribution in front of API Gateway regional endpoint. Is it worth it or not? Well, your mile varies based on what you’re looking for.</p><p>Here, I’m going to demonstrate the one of its use cases. API Gateway’s WebSocket API does not support a path parameter in the connection URL. By design (or say it a design oversight), the connection URL path is fixed to the root path / (stage would be prepended when execute-api endpoint is used). This has blocked use cases such as <a href="https://www.openchargealliance.org/">OCPP(Open Charge Point Protocol)</a> which requires a charging station id as a path parameter.</p><pre>GET /ocpp/CS001 HTTP/1.1<br>Host: your.domain.com<br>Upgrade: websocket<br>Connection: Upgrade<br>...</pre><p>To workaround this, you have to use a proxy in front of WebSocket API that transforms a request to other parameter such as query string or header. For example:</p><pre>GET /?stationId=CS001 HTTP/1.1<br>...</pre><p>Although it works, this is counter-intuitive to the customers as you don’t want to maintain your own infrastructure when you use Serverless WebSocket API. Not only cost, but also your proxy becomes a failure point and needs to handle scalability.</p><p>Ideally the best path forward is supporting the path parameter in WebSocket API natively. Until then, you can use CloudFront with CloudFunction to shed the burden to maintain your proxy infrastructure. Obviously using CloudFront may cost you a bit more, but you also can have additional benefits of CloudFront, for example, WAF integration which is not supported by WebSocket API.</p><p>At this point, if you already get an idea about how you can achieve it, then you can stop reading this — your time is precious. Otherwise please continue to read. (<strong>Disclaimer: The examples and codes are written for illustration purpose. Do your diligence if you’re going to leverage this in your production environment</strong>).</p><p>Here is a whole picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7MyRI1frp1cPAY8SeKMrEg.png" /></figure><h3>Create a WebSocket API</h3><p>First, let’s create a WebSocket API and make it to handle a query string stationId in $connect. Once it is connected, when the client send “hello”, then it should return a message with the stationId in the connection URL like this:</p><pre>wscat -c &#39;wss://&lt;YOUR_EXECUTE_API_ENDPOINT&gt;?stationId=CS001&#39;<br>Connected (press CTRL+C to quit)<br>&gt; {&quot;action&quot;:&quot;hello&quot;}<br>&lt; {<br>    &quot;messge&quot; : &quot;Hello, CS001&quot;<br>}</pre><p>I create a WebSocket API with a route selection expression of $request.body.action. For a demonstration, I’ll use Lambda Authorizer to store the stationId to be used for subsequent routes. Here is Lambda function for the authorizer. Please note that it returns stationId as principalId to be used as $context.authorizer.principalId later.</p><pre>export const handler = async (event) =&gt; {<br>  const stationId = event.queryStringParameters.stationId;<br>  <br>  if (stationId &amp;&amp; stationId.length &gt; 0) {<br>    return generateAllow(stationId, event.methodArn);<br>  } else {<br>    return &quot;Unauthorized&quot;<br>  }<br>};<br><br>// Helper function to generate an IAM policy<br>var generatePolicy = function(principalId, effect, resource) {<br>   // Required output:<br>   var authResponse = {};<br>   authResponse.principalId = principalId;<br>   if (effect &amp;&amp; resource) {<br>       var policyDocument = {};<br>       policyDocument.Version = &#39;2012-10-17&#39;; // default version<br>       policyDocument.Statement = [];<br>       var statementOne = {};<br>       statementOne.Action = &#39;execute-api:Invoke&#39;; // default action<br>       statementOne.Effect = effect;<br>       statementOne.Resource = resource;<br>       policyDocument.Statement[0] = statementOne;<br>       authResponse.policyDocument = policyDocument;<br>    }<br>   return authResponse;<br>}<br>    <br>var generateAllow = function(principalId, resource) {<br>   return generatePolicy(principalId, &#39;Allow&#39;, resource);<br>}<br>    <br>var generateDeny = function(principalId, resource) {<br>   return generatePolicy(principalId, &#39;Deny&#39;, resource);<br>}</pre><p>I create a Lambda authorizer in APIGateway with Query String stationId as an identity source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*NddFbshbPlfGa0XnM1kbxQ.png" /></figure><p>then configure $connect route to use the authorizer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0jG95Hb8pUbZeIVIHGssEQ.png" /></figure><p>To get a message with stationId and connectionId, I configure “hello” route with Mock integration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zjYyD7Ds1irtGhNvmGn4jQ.png" /></figure><p>and add an integration response to send back $context.authorizer.principalId, which is stationId query string. I also add $context.connectionId to be used later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u9LvqtsQj1h6zkTX8BTe6g.png" /></figure><p>Here is the template, FYI.</p><pre>{<br>    &quot;messge&quot; : &quot;Hello, $context.authorizer.principalId. Your connectionId is $context.connectionId&quot;<br>}</pre><h3>Test WebSocket API</h3><p>I deploy the API to the stage called ‘beta’. It returns 401 when there is no stationId query string.</p><pre>wscat -c &#39;wss://&lt;YOUR_EXECUTE_API_ENDPOINT&gt;/beta&#39;<br>error: Unexpected server response: 401<br>&gt;</pre><p>When the stationId query string is sent, it connects successfully and “hello” action message echoes back the stationId.</p><pre>wscat -c &#39;wss://&lt;YOUR_EXECUTE_API_ENDPOINT&gt;?stationId=CS001&#39;<br>Connected (press CTRL+C to quit)<br>&gt; {&quot;action&quot;:&quot;hello&quot;}<br>&lt; {<br>    &quot;messge&quot; : &quot;Hello, CS001. Your connectionId is IlqnQenRPHcCFIA=&quot;<br>}</pre><p>WebSocket API itself is working, now it’s time to configure a CloudFront Distribution to use a path parameter instead.</p><h3>Prepare a domain name</h3><p>Using a custom domain name is not mandatory. If you want to use the CloudFront for your WebSocket client only, you can skip this and any other step mentioning about “domain name” below.</p><p>However, if you’re trying to invoke @Connection APIs through CloudFront, you will encounter a signature failure. @Connection API requires IAM authentication which requires signing the host header. Your client will sign the request with your domain name as header, then the request would be sent to CloudFront distribution which forward the request to API Gateway’s execute-api endpoint. Without creating a regional domain name in API Gateway, if your CloudFront distribution preserves the host header, the domain name is unknown to API Gateway so it will fail to identify our API. If your CloudFront distribution does not preserve the host header, SigV4 signature won’t match. To make it work perfectly, you must use a custom domain name, so prepare your domain with your own way.</p><h3>Create SSL certificates</h3><p>To use a custom domain name, I need 2 SSL certificates for the custom domain name: One to associate with CloudFront distribution, another to create a regional custom domain name in API Gateway. When ACM is used, the first certificate for CloudFront must be in us-east-1, while the second certificate for API Gateway should be the same region where the WebSocket API is.</p><h3>Create a regional domain name in API Gateway</h3><p>I create a regional endpoint with the domain name and choose the ACM certificate for API Gateway:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_eeR8OBxBpmIP-xJF1MEg.png" /></figure><p>then configure a base path mapping. I’ll just configure it to WebSocket API’s stage without any path.</p><h3>Create a CloudFront Function</h3><p>We need a CloudFront Function that transforms the path parameter into a query string. Here is a quick example:</p><ul><li>If the URI matches the ocpp path parameter pattern, it changes the parameter to query string</li><li>If the URI starts with /@connections/, it passes through the request</li><li>otherwise, return 404</li></ul><pre>function handler(event) {<br>    var request = event.request;<br>    var regex = /\/ocpp\/(\w+)/g;<br>    var match = regex.exec(request.uri);<br>    <br>    if (match &amp;&amp; match.length == 2) {<br>        var stationId = match[1];<br>        request.uri = &#39;/&#39;;<br>        request.querystring = {<br>            &#39;stationId&#39; : {<br>                &#39;value&#39; : stationId<br>            }<br>        };<br>    } else if (request.uri.startsWith(&#39;/@connections/&#39;)) {<br>        return request;<br>    } else {<br>        var response = {<br>            statusCode: 404,<br>            statusDescription: &#39;NotFound&#39;<br>        }<br>        return response;<br>    }<br>    <br>    return request;<br>}</pre><p>Before pushing it to Live, I verify the function. When I used GET /ocpp/CS001, it is successfully transformed the uri to / and the path parameter to the query string stationId.</p><pre>{<br>  &quot;request&quot;: {<br>    &quot;headers&quot;: {},<br>    &quot;method&quot;: &quot;GET&quot;,<br>    &quot;querystring&quot;: {<br>      &quot;stationId&quot;: {<br>        &quot;value&quot;: &quot;CS001&quot;<br>      }<br>    },<br>    &quot;uri&quot;: &quot;/&quot;,<br>    &quot;cookies&quot;: {}<br>  }<br>}</pre><h3>Create a CloudFront distribution</h3><p>I create a CF distribution with origin of WebSocket API (execute-api) that I’ve created. I chose HTTPS only and TLSv1.2.</p><p>In Default cache behavior, be sure to choose AllViewer Origin request policy that preserves the all the headers including Host header. It is recommended for API Gateway custom domain any way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hJaEE4OkELZtUJFQBMhKFQ.png" /></figure><p>I associate the CloudFront function that I’ve created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kC59lxloEUb8MmWHnnD_0A.png" /></figure><p>Lastly, configure the CNAME and SSL certificate. I hit the create a distribution and wait until it is deployed.</p><h3>Configure Route53 record for the domain name</h3><p>I create a Route53 CNAME record to redirect our domain name to CloudFront distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6TCo2P0TW9zcc1p3OHcgjQ.png" /></figure><h3>Test WebSocket API with path parameter</h3><p>It’s time to confirm our work. If I am hitting the domain name endpoint with the path parameter, and I can see it works perfectly.</p><pre>wscat -c &#39;wss://&lt;YOUR_DOMAIN_NAME&gt;/ocpp/CS002&#39;<br>Connected (press CTRL+C to quit)<br>&gt; { &quot;action&quot; : &quot;hello&quot; }<br>&lt; {<br>    &quot;messge&quot; : &quot;Hello, CS002. Your connectionId is IlrD_c0KvHcCEqg=&quot;<br>}<br>&gt;</pre><p>@connection API also works with the domain name:</p><pre>// CLI 2.0<br>aws apigatewaymanagementapi post-to-connection \<br>--connection-id &#39;IlrD_c0KvHcCEqg=&#39; \<br>--endpoint-url &#39;https://&lt;YOUR_DOMAIN_NAME&gt;&#39; \<br>--data &#39;{&quot;message&quot;:&quot;hello from server&quot;}&#39; \<br>--cli-binary-format raw-in-base64-out<br><br>// WebSocket client connected<br>&lt; {&quot;message&quot;:&quot;hello from server&quot;}</pre><p>If I try to connect with the path / and query string, our CloudFront function will return 404.</p><pre>wscat -c &#39;wss://&lt;YOUR_DOMAIN_NAME&gt;/?stationId=CS001&#39;<br>error: Unexpected server response: 404<br>&gt;</pre><p>Since the transform happens in CloudFront, be aware that WebSocket API actually receives it as query string.</p><h3>Optional: Disabling the default endpoint</h3><p>Once you’ve create a custom domain name, you may want to ensure that the clients can access your API only by using a custom domain name and path parameter. In this case, you must disable the default execute-api endpoint then redeploy your stage.</p><pre>aws apigatewayv2 update-api --api-id &lt;YOUR_API_ID&gt; --disable-execute-api-endpoint<br>...<br>aws apigatewayv2 create-deployment --api-id &lt;YOUR_API_ID&gt; --stage &lt;YOUR_STAGE&gt;</pre><p>Once it is disabled, the endpoint will return 403.</p><pre>wscat -c &#39;wss://&lt;YOUR_EXECUTE_API_ENDPOINT&gt;/beta?stationId=CS001&#39;<br>error: Unexpected server response: 403<br>&gt; ⏎</pre><h3>Wrap up</h3><p>Putting CloudFront in front of WebSocket API could offer some benefits. Especially, with CloudFront Function, it unblocks the use cases such as OCPP without a need of owning your proxy infrastructure.</p><p>Of course, it’s not free. You need to pay for CloudFront cost, CloudFront Function cost, and potential latency impact as it adds another hop. The latency impact may vary depends on where your clients are. If your clients are located far from the region where your API exists, CloudFront and its backbone network to AWS regions may improve the latency. If your clients are in the same region, you will have the latency increase as the request should exit the region, go to the CloudFront PoP, then re-enter the region.</p><p>No need to say this should have been supported out of box. But it’s still better to have a workaround. I hope this helps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab304fd95ac3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Lambda Function URLs — Another way to create HTTP endpoint for a Lambda function]]></title>
            <link>https://medium.com/@lancers/aws-lambda-function-urls-another-way-to-create-http-endpoint-for-a-lambda-function-e991185aa488?source=rss-bdf1c6b4acaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/e991185aa488</guid>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Jaewoo Ahn]]></dc:creator>
            <pubDate>Fri, 08 Apr 2022 03:04:57 GMT</pubDate>
            <atom:updated>2022-04-08T03:04:57.644Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS Lambda Function URLs — Another way to create HTTP endpoint for a Lambda function</h3><p>AWS released <a href="http://aws.amazon.com/blogs/aws/announcing-aws-lambda-function-urls-built-in-https-endpoints-for-single-function-microservices">Lambda Function URLs (aka Lambda FURLs or just Lambda URLs)</a>, which gives you another ability to create a HTTP endpoint for a Lambda functions. In this post, I’ll focus how it is different from existing services that offers such HTTP endpoint for Lambda and what you need to consider when you’re planning to use it for your production service.</p><p>As I said “another”, the concept itself is nothing new. You already can invoke a Lambda function over HTTPS with <a href="https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html">Lambda Invoke API</a> though you won’t want your client do it directly.</p><p>For example, let’s imagine you have a function named GetItem which accepts <em>itemId</em> and <em>filter</em> as parameters. When you invoke it directly, you have to use RPC-style invocation where put everything into payload and you can’t leverage method, resource URI, nor HTTP status code since they are pre-occupied. The client should use Lambda service endpoint, know the function name, and they should sign the request with the credential that has lambda:invokeFunction permission.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sFKasUmFLNDJf7mH7NpX8A.png" /></figure><p>Instead of asking your end user to do this, you will want to:</p><ul><li>Use a different domain name</li><li>Hide a function name</li><li>Encapsulate and/or separate authorization</li><li>Request routing</li><li>HTTP context transformation</li></ul><p>To achieve this, you need a proxy in front of Lambda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xcv4sswXOQ_uCQ49LYwXYg.png" /></figure><p>With this way, the client can call against a different domain name without knowing the function name nor having a credential to invoke the Lambda function. The proxy can authenticate/authorize the client with a different way, and transform the HTTP request/response to/from Lambda Invoke Request/Response.</p><p>Although you can do it yourself, AWS has offered several pre-built services such as API Gateway and Lambda@ALB. Each has some difference in their feature/pricing model/limits, but they fundamentally do same jobs mentioned above. So does Lambda FURLs.</p><h3>Endpoint Domain name</h3><p>API Gateway offers a following form of default endpoint domain:</p><pre>https://&lt;apiId&gt;.execute-api.&lt;region&gt;.amazonaws.com/&lt;stage&gt;</pre><p>The apiId is determined when you create an API, and the stage path depends on the stage that you published your API. If you delete an API, there is no way to recover the API Id again.</p><p>For the people who does not like this, it allows you to create a custom domain and create a base path mapping to map a path under the custom domain to map to a stage of a specific API. There are several reasons for why you should not use the default execute-api endpoint for your public production service, but I’ll save it for later.</p><p>With Lambda@ALB, you can use ELB DNS name :</p><pre>https://&lt;elbName&gt;-&lt;id&gt;.&lt;region&gt;.elb.amazonaws.com</pre><p>but you will want to use your own domain name.</p><p>Lambda Function URL has a following format:</p><pre>https://&lt;url-id&gt;.lambda-url.&lt;region&gt;.on.aws</pre><p>&lt;url-id&gt; is something like <strong><em>4iykoi7jk2kp5hhd5irhbdprn40yxest</em></strong>, a bit lengthy. According to Lambda documentation:</p><blockquote>Lambda generates the &lt;url-id&gt; portion of the endpoint based on a number of factors, including your AWS account ID. Because this process is deterministic, it may be possible for anyone to retrieve your account ID from the &lt;url-id&gt;.</blockquote><p>I’m not sure what exactly “deterministic” means here. Initially I misunderstood that url-id is deterministic, but it does not give a same url-id when I delete and recreate it even though nothing changed. Maybe timestamp or a random value is used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tc51xK4-PU_TiJfxVgDo3w.png" /></figure><p>The domain apparently tells your client that you’re using Lambda FURL. Lambda FURL itself does not support a custom domain. You can put CloudFront in front of Lambda function if you want, though it can fade the benefit of Lambda FURL. Lambda FURL can run up to 15 mins, while CloudFront has 30 seconds request timeout. It could be increased by the request, but not sure it can go up to 15 mins.</p><h3>Hiding a function name</h3><p>Each service allows to configure the target function Arn in a different style. Here is CloudFormation resource for Lambda FURL. I don’t see AWS::Lambda::Url in the CloudFormation documentation yet, and I expect to get the endpoint URL in Outputs.</p><pre>{<br>  &quot;Type&quot; : &quot;AWS::Lambda::Url&quot;,<br>  &quot;Properties&quot; : {<br>      &quot;AuthType&quot; : String,<br>      &quot;Cors&quot; : Cors,<br>      &quot;Qualifier&quot; : String,<br>      &quot;TargetFunctionArn&quot; : String<br>    }<br>}</pre><h3>Encapsulate and/or separate authorization</h3><p>In many cases, you want to decouple <em>the authorization against your client</em> from <em>the authorization against Lambda function</em>. The intermediary should have a credential to invoke Lambda function, while the end user does not necessary to have it.</p><p>API Gateway offers comprehensive solutions for this case. For the authorization from API Gateway to Lambda, you can use either identity-based policy or resource-policy, though <a href="https://medium.com/@lancers/low-hanging-fruit-to-reduce-api-gateway-to-lambda-latency-8109451e44d6">I strongly recommend to use resource policy to reduce the latency</a> if possible. For the authorization from end user to API Gateway, you can use IAM/Lambda authorizer. REST API additionally supports Cognito authorizer, resource policy, and WAF integration. HTTP API additionally supports JWT authorizer.</p><p>Lambda@ALB uses Resource policy based authorization from ALB to Lambda. To protect against confused deputy problem, Lambda function should have a policy to allow the invocation from a source arn, which should be ALB Arn and sourceAccount. However, they don’t offer any out of box support to authorize the end user. Although you can perform an authorization within your Lambda function, it means all unauthorized request will hit your Lambda function. Of course, WAF can be used to reduce the risk.</p><p>Lambda Function URL has a unique approach. There is no specific authorization between Lambda FURL and Lambda Function. Instead, the caller should be authorized against the function itself, but for a different action called lambda:InvokeFunctionUrl.</p><pre>{<br>      &quot;Sid&quot;: &quot;test123&quot;,<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: {<br>        &quot;AWS&quot;: &quot;&lt;user/role&gt;&quot;<br>      },<br>      &quot;Action&quot;: &quot;lambda:InvokeFunctionUrl&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:lambda:&lt;region&gt;:&lt;account&gt;:function:&lt;function_name&gt;&quot;,<br>      &quot;Condition&quot;: {<br>        &quot;StringEquals&quot;: {<br>          &quot;lambda:FunctionUrlAuthType&quot;: &quot;AWS_IAM&quot;<br>        }<br>      }<br>}</pre><p>It feels a bit odd since it doesn’t encapsulate the function name. I expect to be authorized against the Lambda FURL, not the function itself.</p><pre>{<br>      &quot;Sid&quot;: &quot;test123&quot;,<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: {<br>        &quot;AWS&quot;: &quot;&lt;user/role&gt;&quot;<br>      },<br>      &quot;Action&quot;: &quot;lambda:InvokeFunctionUrl&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:lambda:&lt;region&gt;:&lt;account&gt;:url:&lt;url-id&gt;&quot;,<br>      &quot;Condition&quot;: {<br>        &quot;StringEquals&quot;: {<br>          &quot;lambda:FunctionUrlAuthType&quot;: &quot;AWS_IAM&quot;<br>        }<br>      }<br>}</pre><p>There is a difference between them. If I delete Lambda FURL then recreate one, the first policy still allows the access while the second policy does not allow the access any more since url-id is changed.</p><p>Anyway, in Lambda FURL, the caller must go through identity policy based authorization and/or resource policy-based authorization. Wait, isn’t there NONE AuthType? I know it is confusing for you. AuthType in Lambda Function actually indicates AuthN (authentication), not authorization. When AWS_IAM is used, it performs IAM authentication. Once an identity is authenticated, it authorizes against both identity policy and resource policy. When NONE is used, it does not perform an authentication so it can’t authorize against identity policy, but it still authorizes against resource policy. If you really want to allow anyone to invoke your Lambda function, you need to configure a resource policy to allow it.</p><p>However, think twice before using NONE. The <a href="https://aws.amazon.com/blogs/aws/announcing-aws-lambda-function-urls-built-in-https-endpoints-for-single-function-microservices/">AWS blog post example</a> uses NONE and perform a custom authorization within the Lambda function. I strongly discourage this pattern because any unauthorized user can hit your Lambda function and it will consume the Lambda execution concurrency and you’ll be charged for the execution time to perform an authorization. There isn’t any way to mitigate.</p><p>Isn’t it same with using API Gateway’s Lambda authorizer? Not really. API Gateway’s Lambda authorizer checks if the identity source(s) are given, and offers authorizer cache to protect the authorizer function from brownout. API Gateway also requires the request to hit the existing method/resource. You can also narrow the accessibility with Private API, use WAF or even MTLS.</p><p>This is more like when you configure API Gateway authorization type to NONE. I’ve seen many customers who left their API with NONE authorization type, then got a huge bill due to the requests from somewhere in the internet. Since it is exposed in the public internet, anyone can invoke your Lambda.</p><h3>Request Routing</h3><p>The HTTP endpoint should offer a way to route a HTTP request to Lambda function. API Gateway offers REST semantic (method/resource) to map into different Lambda functions. Lambda@ALB offers a rule based routing to map into different Lambda functions.</p><p>In contrast, Lambda Function URL always routes to a single Lambda function. Your lambda function itself should perform as a router to execute a different action based on the request. Although this Mono Lambda pattern is simple and convenient, the draw back is your deployment package can become bigger and you’re losing all granularity about permission, logging/metrics, and concurrency.</p><p>Alternatively, you can use create multiple functions then ask your client to use multiple Lambda FURLs if it is acceptable for them. However, usually the client would want to use a single integrated endpoint, then eventually you’ll end up to put another proxy in front of those Lambda FURLs to aggregate into a single domain.</p><h3>HTTP context transformation</h3><p>When a request comes into HTTP endpoint, a HTTP request must be transformed into a format to be passed as Lambda function’s input argument. In same way, the function output must be transformed into HTTP response.</p><p>When API Gateway launched REST API, initially it had Lambda (non-proxy) integration. It means you have to use VTL to configure the payload to be passed. You have to rely on RegEx to trigger a different status code for the response.</p><p>Later, Lambda Proxy integration is introduced. It offers a specific payload format for the request and response. It saves huge amount time for you from debugging ugly VTL and mappings. If you’re still using Lambda non-proxy integration, I strongly recommend stop using it. If you’re new to API Gateway, do not look at non-proxy integration at all. The payload format, aka Lambda Proxy payload format v1 was adopted to Lambda@ALB later.</p><p>Later, while API Gateway team was building HTTP API, <a href="https://medium.com/@lancers/amazon-api-gateway-explaining-lambda-payload-version-2-0-in-http-api-24b0b4db5d36">Lambda Payload Version 2 has been introduced to incorporate all the lessons learned from REST and WebSocket API</a>. For backward compatibility, HTTP API Integration has an option to <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-payloadformatversion">specify the payload format version</a>.</p><p>Lambda Function URL adopted API Gateway’s Lambda Payload format version 2.0, which means you can use a same Lambda function between HTTP API and Lambda Function URL. However, since it does not support Payload format 1.0, you cannot share the lambda function with REST API. This might be supported in the future.</p><h3>What’s lacking in Lambda Function URL?</h3><p>For the feature perspective, Lambda Function URL is kinda sitting between API Gateway and Lambda@ALB. It lacks many features in API Gateway, while it offers out-of-box IAM auth and CORS comparing to Lambda@ALB.</p><p>Comparing features with API Gateway is not meaningful. Obviously API Gateway has more features while it costs additional money. Is there something lacking in it when it comes to a production service?</p><p>The top concern in my mind is there is no good security mitigation other than authorization. Without IAM Auth, the only security mitigation is Lambda concurrency throttling to protect you from being overcharged or affecting other Lambda functions. There is no other way to protect the function’s availability itself.</p><p>Another lacking point is access logs. You have 4xx/5xx metrics from it, but you don’t have a way to identify the request when the request is rejected before reaching your Lambda function. Since the request never reached your Lambda function, you don’t have any log. This is a big red flag to me in terms of operational visibility.</p><p>For example, Lambda Function URL will return 403 Forbidden without giving any further information. The below example was not caused by authorization problem though it was 403. FWIW, I had an access to the response, but what if your customer complains about this?</p><pre>HTTP/1.1 403 Forbidden<br>x-amzn-ErrorType: AccessDeniedException<br>x-amzn-RequestId: xxxxxxx-ef5a-4cc4-b6bf-7c971d3188d1</pre><pre>{&quot;Message&quot;:&quot;Forbidden&quot;}</pre><h3>Use This, Not That</h3><p>Obviously, Lambda Function URLs have several attractive points. It does not charge extra cost to you (included in the Lambda request/execution) and you can run it up to 15 mins. This feels like a big win over API Gateway that costs you extra money and has 29 seconds integration timeout.</p><p>First, you should be fine with the domain name exposing the fact that you’re using Lambda FURLs. You may consider to put CloudFront in front of it to use a custom domain while it can cost extra money (despite you liked Lambda FURL since it is free) and you need to deal with CloudFront request timeout which fades 15 mins execution benefit.</p><p>I will unlikely use this without IAM authentication as I pointed already. Using IAM Auth restricts the clients to who can sign the request with a credential that has a permission. The account should be in-account, or manageable within a resource policy. In some cases, you could set several conditions with <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html">AWS global condition keys</a> within Resource policy while you’re using NONE auth type. Again, you can put CloudFront in front of it, then associate WAF there, as long as you have a way to restrict the access to Lambda FURL from CloudFront only.</p><p>It works very well when you have a single client only. You can use Lambda function concurrency directly to throttle the client. There is no worry about adjusting throttling limit in API Gateway against Lambda concurrency. However, if multiple clients share the function, a single client can exhaust the concurrency limit since there is no way to throttle per client. it raises a noisy neighbor problem and can lead to unfair throttling. If your clients can agree with the unfairness, it doesn’t matter.</p><p>In summary, this works greatly for a relatively small number of trustful clients who can use IAM Auth without charging me additional cost.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e991185aa488" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lesson learned while I’m using CDK]]></title>
            <link>https://medium.com/@lancers/lesson-learned-while-im-using-cdk-4fbb816d6e3?source=rss-bdf1c6b4acaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fbb816d6e3</guid>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloudformation]]></category>
            <dc:creator><![CDATA[Jaewoo Ahn]]></dc:creator>
            <pubDate>Thu, 17 Mar 2022 02:53:13 GMT</pubDate>
            <atom:updated>2022-03-17T02:53:13.688Z</atom:updated>
            <content:encoded><![CDATA[<p>To be honest, I hadn’t much used CloudFormation, SAM, nor CDK. It is somewhat shameful to say as an engineer who works in AWS, but mostly I had worked on the service application code rather than infrastructure. Recently, I had a chance to work on infrastructure and played with CDK.</p><p>CloudFormation is a declarative format to define AWS infrastructure resources. To add more programmability, people used to tame it with some template engine such as Jinja. Although it gives some flexibility, it becomes really hard to read and debug as your template becomes complex and hierarchical for reusability and modularity. If you ever wasted your time to debug a gigantic template decorated with a template engine, you understand me.</p><p>People have explored more human-friendly ways instead of interacting CloudFormation directly. There are several frameworks that attempts to offer a better developer experience, but it still uses CloudFormation underneath (or AWS APIs) to provision a resource in AWS environment.</p><p><a href="https://docs.aws.amazon.com/cdk/v2/guide/home.html">CDK</a> is another wrapper for this purpose, and it is my favorite so far. The essential of CDK is a different levels of layers of <a href="https://docs.aws.amazon.com/cdk/v2/guide/constructs.html">constructs</a> on top of CloudFormation. Preferably you would want to deal with higher level of constructs, but still you can <a href="https://docs.aws.amazon.com/cdk/v2/guide/cfn_layer.html">access to the low level CFN resources</a>.</p><p>Generally, higher constructs are well abstracted. It intended to reduce the verbosity when you use lower level one, and the defaults are well constructed. However, I often found myself digging the internal of the construct implementation a lot to understand what’s happening within it. In the end, you have to understand how CloudFormation works to use CDK properly. Let’s see some examples from what I learned.</p><h3>Maximum number of resources in a stack</h3><p>What if you suddenly encounter this message while you’re building it?</p><pre>Number of resources: 475 <strong>is</strong> approaching allowed maximum of 500</pre><p>Apparently this limit comes from CloudFormation, which limits resources in a stack to 500 resources. Honestly I can’t imagine how people lived with it when the limit was 250 until few years ago.</p><p>When you deal with CloudFormation resources directly, you have higher chance to aware how many resources that you have. However, it is a bit opaque when you use CDK constructs since you have no idea how many CFN resources can be generated by a single higher level construct until it actually builds and synthesizes a CloudFormation template.</p><p>FWIW, CDK gives you early warning before you actually hit the limit. So you’d better to tackle this as soon as possible.</p><h3>Refactoring a stack</h3><p>To reduce the number of resource in a stack, you need to split this stack by moving some resources into a different stack. How can you split resources from this stack? If you don’t have any idea how the underlying CloudFormation works, you may just create another CDK stack and move the resource into there. Copy and paste, easy peasy. What would happen if you do that? In fact, you’re deleting all existing resources then re-create it. It is not a big deal if you’re setting up a new infrastructure, but what if it is a production service that already has been deployed and serving a traffic?</p><p>Historically, CloudFormation hasn’t solved the stack refactoring problem very well. It requires <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/refactor-stacks.html">a series of c</a>hanges:</p><ol><li>You need to add a Retain deletion policy to all the resources that you want to move</li><li>Delete all the resources from the stack. Since Retain is set, this will actually detach them without deleting it.</li><li><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-import-existing-stack.html">Import the existing resources to the target stack</a> (be aware <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-import-supported-resources.html">not all the resources are supported by import</a>)</li></ol><p>The problem is CDK does not offer a great solution on this procedure neither. Some CDK construct allow you setting a deletion policy, but not all of them. To retain all the resources, you have to access the all underlying CFN resources to set the policy. Even after then, CDK <a href="https://github.com/aws/aws-cdk-rfcs/issues/52">does not support resource import yet</a>. It means you have to import it as CloudFormation stack first, then <a href="https://docs.aws.amazon.com/cdk/v2/guide/use_cfn_template.html">import the CloudFormation template to CDK</a> rather than refactor your CDK stack directly.</p><p>I have tried the above approach, but finally gave up. I couldn’t find a clear and reliable way to do it without disrupting our production service. Instead, I created a new stack first, then updated all references to use a resource in a new stack, then delete the existing resources from the old stack.</p><p>For example, let’s imagine I have following stacks: DDB table streaming triggers a lambda Consumer function, but I have to split this function from Lambda stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*zv8hvg--wiHXaydCf9jV5w.png" /></figure><p>If you’re just switching the streaming to a different Lambda function, it will create a new Lambda function and a new event source mapping to it, then delete the previous event event source mapping and the old Lambda function. While I tested, I found some events have missed without invoking consumer. I thought it would go to the DLQ where we can redrive, but there was no message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wZy1Y7CT0y5iGQcFIwUqg.png" /></figure><p>To avoid any potential event loss, I just created a new stack and another event mapping. By doing this, an event triggers both functions in the old and new stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5ZBdBkBCK_Q46D-jwP2bQ.png" /></figure><p>Our function is designed to handle such duplicated invocation, so it wasn’t big deal. After confirming there was no event loss, I deleted the function from the old stack along with its event mapping (so it becomes same as above picture).</p><p>Clearly I should have design and split the stack from the beginning before encountering this situation. Although a refactoring is doable, it is time-consuming and risky until CDK/CloudFormation offers a better and safe way to do it.</p><h3>Roles per account quota</h3><p>Later, I encountered this error during a deployment.</p><pre>Cannot exceed quota for RolesPerAccount: 1000 (Service: AmazonIdentityManagement; Status Code: 409; Error Code: LimitExceeded; Request ID: D39F040A-80E0-45A4-9219-B442C44F3DDC; Proxy: null)</pre><p>Initially, I naively thought I could delete some unused roles. I found there are hundreds of roles that have been unused more than 120 days, so write a script to <a href="https://aws.amazon.com/blogs/security/identify-unused-iam-roles-remove-confidently-last-used-timestamp/#:~:text=This%20can%20leave%20unused%20roles,then%20confidently%20remove%20unused%20roles.">detach and delete role policies and roles **confidently</a>**.</p><p>Then our stack deployment began to fail. Although those roles are unused (and I thought they’re dangling), but they are still referenced from our stack. Simply speaking, I made a silly drift by deleting them manually. For god’s sake, it’s non-prod environment, and I was managed to recover it.</p><p>Why so many roles have been created? If you don’t provide a role, most CDK constructs create a default role with a minimum privileges to the specific resource. Although it is a good practice to do this, it will create a role per resource, which leads to IAM’s roles per account quota which is 1000 by default. Though it can be increased, but it has a hard limit at 5000.</p><p>Since it is account level quota, it can block any stack change. To solve the problem, you’ll need to aggregate those roles into a single one, and provide your own role instead of letting CDK construct create a default role. Choose wisely between <em>how many roles that you want to aggregate </em>and <em>granularity of privileges from a security perspective</em>.</p><h3>Leverage cdk diff</h3><p>It is common to see CloudFormation deployment works when you deploy the stack for the first time but it fails or leads to unexpected behavior when it updates the existing stack.</p><p>CDK offers <a href="https://docs.aws.amazon.com/cdk/v2/guide/cli.html#cli-diff"><em>cdk diff</em></a><em> </em>command which compares the specified stack with the deployed stack or a local CloudFormation template. It will show IAM statement/policy changes, and Resources changes along with where they would be deleted or retained. This is extremely useful for a stack refactoring or when you’re deploying a sensitive change. It is more straightforward than diff between CloudFormation templates.</p><p>You must be careful especially when you rely on a default role that CDK constructs create internally. Sometimes without noticing it, it may blow up the required permission that your production stack is using.</p><p>Whenever you’re replacing/deleting something in CDK, use cdk diff command to think if any issue can happen when the existing resource is deleted. Sometimes you have to set an explicit dependency among resources are being created.</p><h3>Test a change in non-prod</h3><p>Needless to say, you must verify your CDK change in non-prod environment before deploying it prod. If you had to fix something manually in non-prod during/after the deployment (it means you made a stack drift!), you’d better to roll it back then fix your CDK until you can deploy it successfully. Once non-prod deployment is done without any manual fix, then you can continue to deploy it to your prod. It is recommended to minimize the difference between non-prod and prod, otherwise it increases a chance for uncovered area in your change.</p><p>Remember, Infrastructure as Code also means a bug in your code can break down your infrastructure during run time. It is more critical than run time error of application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fbb816d6e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Deployment” in Amazon API Gateway]]></title>
            <link>https://medium.com/@lancers/deployment-in-amazon-api-gateway-128c522c762e?source=rss-bdf1c6b4acaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/128c522c762e</guid>
            <category><![CDATA[cloudformation]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Jaewoo Ahn]]></dc:creator>
            <pubDate>Fri, 04 Mar 2022 03:24:11 GMT</pubDate>
            <atom:updated>2022-03-22T17:36:12.788Z</atom:updated>
            <content:encoded><![CDATA[<p>For newbie to Amazon API Gateway, one of most frustrating experiences is related to its deployment. Here is an illustrated dialogue. Sounds very familiar?</p><blockquote>“Hi, my API is working in API Gateway console, but does not work as expected when I invoked the API. What’s the problem?”</blockquote><blockquote><strong>“Have you deployed your API?”</strong></blockquote><blockquote>“Yes, I deployed my CloudFormation template.”</blockquote><blockquote>“No, I’m asking whether you’ve created a new Deployment”</blockquote><blockquote>“Yes, I used ‘deploy’ command in CloudFormation. It was successful.”</blockquote><blockquote>“No, no, no, not that one. Did you create a new Deployment resource in API Gateway?”</blockquote><blockquote>“What does that mean?”</blockquote><blockquote>“Okay then… can you go to the console then click “Deploy API”? Then choose a stage to deploy, then click Deploy button.”</blockquote><blockquote>“Hang on, yeah, I just did”</blockquote><blockquote>“Now, wait for a minute, then try to invoke it.”</blockquote><blockquote>“Okay.. Oh yeah, it’s working now!”</blockquote><blockquote>“Great, then it’s definitely deployment related issue. You need to deploy your API to apply your API changes. In CloudFormation, you must create Deployment resource in API Gateway.”</blockquote><blockquote>“Got it, I will do that.”</blockquote><blockquote>(later)</blockquote><blockquote>“Hey, it worked when I first deployed my CloudFormation, but it doesn’t work any more!”</blockquote><p>It’s not your fault. The deployment in API Gateway is a confusing concept which has been amplified with CloudFormation’s behavior. No matter what its concept is, if it confuses many people, we can say it is not well-designed. In this post, I’ll try to explain about it deeper.</p><h3>What is “Deployment” in API Gateway?</h3><p>Deploying API means applying your API changes into a specific stage. When you make any change on API except Stage settings, you must deploy it to stage(s) to take an effect.</p><p>In Console, you can find “Deploy API” action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*fWHi2x8ErIREcNBIEPkTHA.png" /></figure><p>Programmatically, clicking Deploy API represented by a <em>Deployment</em> resource:</p><ul><li>REST API: The <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-deployment.html">AWS::ApiGateway::Deployment</a> resource deploys an API Gateway RestApi resource to a stage so that clients can call the API over the internet.</li><li>WebSocket/HTTP API: The <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-deployment.html">AWS::ApiGatewayV2::Deployment</a> resource creates a deployment for an API.</li></ul><p>Did you notice that they have a slightly different description? In fact, there is a difference between them. In REST API, although you can create a deployment without deploying it to stage (stageName is optional in <em>CreateDeployment</em>), but a stage cannot be created without a deployment (deploymentId is required in <em>CreateStage</em>). In WebSocket/HTTP API, you can create a stage without a deployment. Console experience doesn’t well align with the facts. For example, with REST API/WebSocket API, Console’s <em>Deploy API</em> does not allow you to do it without specifying a stage. Console does not allow you to create a stage in WebSocket API without a deployment.</p><p>If you haven’t noticed yet, ApiGatewayV2 made it clearer by removing “stage” from the description: <strong>You can create a <em>deployment</em> without <em>deploying</em> it to a stage</strong>. Wait, what?</p><p>To understand what truly “Deployment” in API Gateway is, let’s borrow the definition from <a href="https://docs.aws.amazon.com/cdk/api/v1/docs/aws-apigateway-readme.html#deep-dive-invalidation-of-deployments">CDK</a>:</p><blockquote>API Gateway deployments are an immutable snapshot of the API.</blockquote><p>This proves why “Deployment” is badly named. It should have been named as <em>ApiSnapshot</em> or <em>ApiChangeSet</em>. To understand easily, let’s compare it with <em>git</em>. Every changes that you’re making into API (except stage settings) are commits to a master branch, which cannot be invoked externally. To make your API callable, you must create a stage (branch) and deploy an ApiSnapshot (labeled commit) into it. Your change doesn’t take effect until you deploy it to each stage.</p><p>So what exactly <em>CreateDeployment</em> does? It creates a snapshot of API with the current state. When you optionally specified stageName, it updates the stage to point to the new snapshot.</p><p>To help you to understand, let’s see the illustration. Imagine you created a new API, create a new resource <em>/products</em>, create a new method <em>GET</em>, then configured its integration to call Lambda function <em>GetProductV1</em>. Likewise most AWS services, API Gateway consists of ControlPlane (where you create/update/delete APIs, Routes, Stages, etc) and DataPlane (where you can invoke your API). At this time, since you haven’t created any stage, their state would be like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HKf_5EN65CqXs6hmlgiNJg.png" /><figcaption>Picture1: API without any stage</figcaption></figure><p>If you invoke API endpoint (e.g. <a href="https://abcdefgh7">https://abcdefgh7</a>.execute-api.us-west-2.amazonaws.com/products) at the moment, you will receive 403 Forbidden since there is no stage is configured nor your API change is deployed.</p><p>Now, if you use CreateDeployment with stageName <strong><em>dev</em></strong>, it will create a new Deployment(<em>2eh6t9</em>), create a new stage, then associate the stage to point it. Once the change is propagated into API Gateway DataPlane, if you invoke <a href="https://abcdefgh7.execute-api.us-west-2.amazonaws.com/dev/products">https://abcdefgh7.execute-api.us-west-2.amazonaws.com/<strong>dev</strong>/products</a> (Note: stage name has been added to the path), API Gateway will invoke Lambda function GetProductV1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zz453MATL1MEGUqVVSHe8A.png" /><figcaption>Picture2: dev stage is created, pointing to deployment <em>2eh6t9</em></figcaption></figure><p>Later, you decided to create another stage called <em>prod</em>. In REST API, you must create a stage with deploymentId(remember you can’t create a stage without a deployment in REST API?). In WebSocket/HTTP API, you can create a stage first then use UpdateStage to assign deploymentId. Once the change is propagated into API Gateway DataPlane, now you can invoke against prod stage: <a href="https://abcdefgh7.execute-api.us-west-2.amazonaws.com/dev/products">https://abcdefgh7.execute-api.us-west-2.amazonaws.com/<strong>prod</strong>/products</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T7e7MXnjwXIqKq_sP9uQxw.png" /><figcaption>Picture3: prod stage is created, pointing to deployment <em>2eh6t9</em></figcaption></figure><p>Later, you updated it to invoke Lambda function called GetProductV2 but what if you forgot to create a new deployment? Although you see <em>GET /products</em> is configured to invoke GetProductV2, it never been deployed anywhere. If you invoke your API, it will continue to invoke GetProductV1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SRRvhDojGz6G4pigsV6MFQ.png" /><figcaption>Picture4: API is updated, but no deployment created yet</figcaption></figure><p>Now you created a new deployment(<em>0iv5l9</em>), but what if you didn’t specify a stage name? Though a Deployment is created, it wasn’t associated any stage. Your stage is still pointing to a previous deployment <em>2eh6t9</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S60DI63Ac5eu_hAV0xLAjg.png" /><figcaption>Picture5: A deployment is created, but the stages still point to the previous deployment</figcaption></figure><p>Finally, you updated <em>dev</em> stage to point a new deployment <em>0iv5l9</em>, then the change is being propagated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPhtc3Tf5Z5mm2p1M26_RA.png" /></figure><p>If you’re configuring manually, this should be straightforward. However, when you use CloudFormation/SAM/CDK, you can encounter several issues if you don’t understand what happens underneath. Let’s see few examples.</p><h3>Issue: Nothing changed though I deployed my CloudFormation stack</h3><p>What would be a problem of the below CloudFormation template?</p><pre>ApiGatewayDeployment:<br>  Type: AWS::ApiGateway::Deployment<br>  ...</pre><pre>ProdStage:<br>  Type: AWS::ApiGateway::Stage<br>  DeploymentId: !Ref ApiGatewayDeployment</pre><p>CloudFormation relies on a logical id to create/update a resource. When you create a CloudFormation template, you need to use a unique logical id for Deployment resource for each CloudFormation deployment. If you don’t change it, CloudFormation will not create another Deployment nor update existing Deployment (again, Deployment is an immutable snapshot of API). Because of this, your first CloudFormation deployment will be fine, though the subsequent deployment will not create a new Deployment in API Gateway. This leads you the exact same situation of Picture4 above.</p><p>A quick remediation/diagnose on this issue is deploying your API manually. If a problem is solved by doing it, then it means your CloudFormation/SAM/CDK has some problem on creating a new Deployment and update the stage to point it.</p><p>You can fix this issue by making the logic id unique (e.g. append timestamp or a hashed value) for each CloudFormation deployment.</p><pre>ApiGatewayDeployment20220301120000:<br>  Type: AWS::ApiGateway::Deployment<br>  ...</pre><pre>ProdStage:<br>  Type: AWS::ApiGateway::Stage<br>  DeploymentId: !Ref ApiGatewayDeployment20220301120000</pre><p>However, there is one thing to keep in mind. Once CloudFormation creates a new Deployment <em>ApiGatewayDeployment20220301120000</em>, it will delete the previous Deployment <em>ApiGatewayDeployment</em> since you removed it from the stack. During the rollback, a new <em>ApiGatewayDeployment </em>will be created with a new API snapshot at the moment, but the deploymentId would be not the same one. If you have any stack drift meantime, you won’t be rollback into the exact previous state.</p><p>The safest approach is retaining the previous deployment in the stack.</p><pre>ApiGatewayDeployment:<br>  Type: AWS::ApiGateway::Deployment</pre><pre>ApiGatewayDeployment20220301120000:<br>  Type: AWS::ApiGateway::Deployment<br>  ...</pre><pre>ProdStage:<br>  Type: AWS::ApiGateway::Stage<br>  DeploymentId: !Ref ApiGatewayDeployment20220301120000</pre><p>With this, ApiGatewayDeployment won’t be deleted. When the rollback happens, the stage will be updated to ApiGatewayDeployment.</p><p>SAM and CDK have an ability to generate a new logical id of Deployment on behalf of you. It will add a hash value based on the API definition (swagger) to ensure a new Deployment is created and update the stage to use the deploymentId. Be careful though, if a change was made outside of API definition, the hash value could remain same. If a new Deployment is not created, update the API definition (e.g. simply change a description) to generate a different hash value.</p><h3>Issue: Your API throws 5XX during the deployment</h3><p>Let’s go back to the previous example.</p><p>You’ve used GetProductV1:</p><pre>GetProductV1:<br>  Type: AWS::Lambda::Function<br>  ...</pre><pre>// and API Gateway Integration is pointing to GetProductV1</pre><p>but changed to use GetProductV2.</p><pre>GetProductV2:<br>  Type: AWS::Lambda::Function<br>  ...</pre><pre>// and API Gateway Integration is pointing to GetProductV2</pre><p>However, while you’re deploying change, your API is throwing 5XX but subsided after then. Everything on the CloudFormation looks fine. A new Deployment is generated correctly, and the stage was updated.</p><p>The change propagation into all API Gateway DataPlane hosts does not happen at the same time. Since it is not creating/updating your AWS resources, it is not managed within CloudFormation deployment lifecycle. For a certain moment, host1 got the change to use GetProductV2 while host2 still uses GetProductV1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qy4nORRJbidOqAYDZ_swkw.png" /></figure><p>Since you removed GetProductV1 Lambda function from the stack, CloudFormation will delete it during clean up process while API Gateway is still propagating the change to its DataPlane. Since the function is gone, Lambda service will return 4XX, then API Gateway will return 500. Eventually once the propagation is done, 5XX will be gone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8rQS7Es_s48LYJMv6CmpHg.png" /></figure><p>So what should you do? You should retain the previous Lambda function in the stack.</p><pre>GetProductV1:<br>  Type: AWS::Lambda::Function<br>  ...</pre><pre>GetProductV2:<br>  Type: AWS::Lambda::Function<br>  ...</pre><pre>// and API Gateway Integration is pointing to GetProductV2</pre><p>Later, if you confirmed that GetProductV1 is not being called any more, then delete it in a next stack deployment. I used Lambda functions as example, but also applies to its corresponding resources (e.g. A role for API Gateway to invoke Lambda function, Lambda Alias, Lambda Version, etc.) or any other AWS resources that are referred from API Gateway.</p><h3>AutoDeploy in HTTP API</h3><p>AutoDeploy in HTTP API is another approach to solve the problem. When it is enabled on a stage, any updates to the API automatically trigger a new deployment to the stage.</p><p>Although it is convenient, there is a problem. When you create a Deployment resource or use SAM/CDK, it will create a Deployment after all other changes have been made to API. All changes will be reflected at once. In contrast, AutoDeploy may cause a partial delivery of the change. With this reason, it is unlikely for me to use it in a production environment, but YMMV.</p><h3>How do I know what has been deployed?</h3><p>Your boss is asking: “Hey, was the API change A deployed to prod (prod stage in prod stack)?”</p><p>Yeah, you know what’s current deploymentId in the prod stage, but how do you know what’s in the deployment? Unfortunately, there is no way to figure it out.</p><p>REST API’s GetDeployment only returns id, description, and createdDate:</p><pre>aws apigateway get-deployment --rest-api-id abcdefghi7 --deployment-id 3gqycx<br>{<br>    &quot;id&quot;: &quot;3gqycx&quot;,<br>    &quot;description&quot;: &quot;RestApi deployment id: d8d1530bae148c7a4b7f48739131da8db0334c9f&quot;,<br>    &quot;createdDate&quot;: &quot;2022-02-01T14:14:11-08:00&quot;<br>}</pre><p>though the spec was said to return apiSummary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K8DTMUu0mod2DpNb-qm3Ew.png" /></figure><p>APIGatewayv2’s GetDeployment returns little more, though it still gives nothing about the API snapshot.</p><pre>aws apigatewayv2 get-deployment --api-id abcdedfgh7 --deployment-id 38x8hn</pre><pre>{<br>  &quot;AutoDeployed&quot;: true,<br>  &quot;CreatedDate&quot;: &quot;2021-11-23T18:07:55+00:00&quot;,<br>  &quot;DeploymentId&quot;: &quot;38x8hn&quot;,<br>  &quot;DeploymentStatus&quot;: &quot;DEPLOYED&quot;,<br>  &quot;Description&quot;: &quot;Automatic deployment triggered by changes to the Api configuration&quot;<br>}</pre><p>What if a deployment is created without deploying it to any stage? GetDeployment will still report the deployment status as “DEPLOYED” even though it was never been deployed to anywhere.</p><pre>aws apigatewayv2 create-deployment --api-id abcdedfgh7<br>{<br>    &quot;AutoDeployed&quot;: false,<br>    &quot;CreatedDate&quot;: &quot;2022-03-04T01:36:43+00:00&quot;,<br>    &quot;DeploymentId&quot;: &quot;zj1q4g&quot;,<br>    &quot;DeploymentStatus&quot;: &quot;DEPLOYED&quot;<br>}</pre><p>Because of this, the API change must be managed by Infrastructure as code (CloudFormation/CDK/etc.) where you can track the changes and deployment in a pipeline. Still if you don’t create a Deployment resource properly, it might not have been deployed yet.</p><h3>Why does it work in API Gateway console?</h3><p>What you’re referring is Console’s Test feature (aka Test invoke). Console’s test feature does not invoke against any stage, so it always uses the current snapshot of your API. Also Console’s test invoke doesn’t perform pre-processing of your method such as authorization and throttling.</p><h3>How could it be better?</h3><p>As we discussed earlier, it is easy to make a mistake if you don’t understand what it is and how it behaves along with CloudFormation. With this reason, many frameworks like SAM/CDK or AutoDeploy in HTTP is trying to encapsulate “Deployment” in API Gateway by handling it automatically. When there is an ambiguity, it is fair enough to encapsulate it. But how could it be better? Let me express some my personal ideas.</p><p>Creating a snapshot and deploying it to a stage are clearly different ones. It should have been split into 2 separate resources:</p><ul><li>ApiSnapshot: An immutable snapshot of API</li><li>Deployment: Deploying (or publishing) a snapshot to a stage</li></ul><p>ApiSnapshot is similar with creating a current Deployment without deploying it. By naming it as ApiSnapshot, it aligns what exactly it does underneath. However, ApiSnapshot will show what’s inside. You could easily compare differences between 2 snapshots (or stages where those snapshots deployed) to figure out what has been changed.</p><p>Deployment (I mean, new one) replaces the use case for UpdateStage to make the stage to point a new deployment id, or CreateDeployment with a stage name. Deploying an API snapshot is an asynchronous workflow to propagate it to API Gateway DataPlane hosts. Once a deployment is initiated, it should be possible to track the state or its progress. Then the state would be changed Deployed only after it is fully propagated.</p><p>Again, these are just my 2 cents.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=128c522c762e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Low hanging fruit to reduce API Gateway to Lambda latency]]></title>
            <link>https://medium.com/@lancers/low-hanging-fruit-to-reduce-api-gateway-to-lambda-latency-8109451e44d6?source=rss-bdf1c6b4acaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/8109451e44d6</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[latency]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Jaewoo Ahn]]></dc:creator>
            <pubDate>Thu, 23 Sep 2021 05:12:02 GMT</pubDate>
            <atom:updated>2021-09-23T05:12:02.861Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you latency-obsessed? Even if you are not, there is no harm in reducing your latencies, right? In this post, I’ll introduce one of the way to reduce the latency from API Gateway to Lambda. Oh, don’t confuse it with reducing Lambda cold/warm start. That’s a different topic that has been discussed countless time by other people.</p><p>First, let’s understand how API Gateway invokes Lambda. In fact, there is nothing much magical here. API Gateway just invokes Lambda as you do with <a href="https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html">Lambda’s Invoke API</a>. Under the hood, it’s a just plain HTTPS request signed by SigV4 as all AWS APIs do. Of course API Gateway will perform an optimization what the HTTP client usually does, including the connection reuse but there is nothing you can control over it.</p><p>However, you have a control on how your Lambda allows an invocation from API Gateway. In short, it’s all about identity-based invocation vs. resource policy based invocation. At this point, if you already know how they can affect the latency, then you can stop reading.</p><h3>Identity-based invocation vs. Resource policy based invocation</h3><p>IAM already explains well their difference in <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_identity-vs-resource.html">Identity-based policies and resource-based policies</a> so I’m not going to repeat their conceptual difference here, but let’s see how you can configure either of them to invoke Lambda function from API Gateway.</p><p>The below is an CLI example taken from API Gateway’s document.</p><pre>aws apigateway put-integration \<br>  --region us-west-2 \<br>  --rest-api-id te6si5ach7 \<br>  --resource-id 2jf6xt \<br>  --http-method ANY \<br>  --type AWS_PROXY \<br>  --integration-http-method POST \<br>  --uri arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:HelloWorld/invocations \<br>  --credentials arn:aws:iam::123456789012:role/apigAwsProxyRole</pre><p>The CLI document doesn’t explain --credentials argument well, but <a href="https://docs.aws.amazon.com/apigateway/api-reference/resource/integration/">the API reference does a better job</a>.</p><blockquote><strong>credentials</strong></blockquote><blockquote>Specifies the credentials required for the integration, if any. For AWS integrations, three options are available. To specify an IAM Role for API Gateway to assume, use the role’s Amazon Resource Name (ARN). To require that the caller’s identity be passed through from the request, specify the string <strong>arn:aws:iam::*:user/*</strong>. To use resource-based permissions on supported AWS services, specify null.</blockquote><p>The above CLI example uses the first option which is also called “role-based invocation” by specifying `apigAwsProxyRole` role. In other words, it means that API Gateway must call STS(Secure Token Service) to assume the role and get a temporary credential before invoking your Lambda function. Of course, calling STS is not free — it adds a latency.</p><p>In contrast, the second and the third option don’t require STS. The second option(caller-identity) only applies when you use IAM authorization to authorize your client to invoke the API while the third option, resource policy based invocation can be applied for any case.</p><p>Please note that the resource policy should be set on the Lambda function, not on API Gateway side. The below example allows any method/resource in the apiId <em>te6si5ach7</em>’s <em>prod</em> stage to invoke <em>HelloWorld</em> Lambda function.</p><pre>aws lambda add-permission \<br>  --function-name HelloWorld \<br>  --action lambda:InvokeFunction \<br>  --statement-id apigateway2Lambda \<br>  --principal apigateway.amazonaws.com \<br>  --source-arn &#39;arn:aws:execute-api:us-west-2:123456789012:te6si5ach7/prod/*&#39;</pre><h3>Latency difference</h3><p>I hear you’re yelling “Just show me the result!”.</p><p>Here is a p90 latency graph that shows a difference before/after switching from role-based invocation to resource-policy based invocation. Since the absolute number can vary by region, API configuration, etc, I redacted the number, you could see the <em>relative</em> difference. Not only the overall reduction, you can also see the gap between API Gateway and API Gateway Integration latency (aka API Gateway overhead latency) has been decreased significantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*5TLYmV2YfdTzfrECwmtCIQ.png" /></figure><p>If you’re using Lambda authorizer, Lambda authorizer also optionally can use either role-based invocation or resource policy-based invocation. If you’re using different roles between authorizer and integration, then STS can be called up to twice and the overhead could be larger. In the case, by switching resource policy-based invocation on both, you may get more latency reductions!</p><h3>Q: Does it mean Role-based policy is always bad?</h3><p>Not really. In certain circumstances, you may require a role-based policy rather than configuring the resource policy for each Lambda function. For example, if you have 1000s of Lambda functions, you just want to allow a role to invoke any Lambda functions instead of adding/updating 1000s resource policies.</p><p>However, for the latency perspective, resource policy based invocation has a benefit over role-based policy. There could be some potential improvements in the future to reduce the overhead on role-based invocation, but that overhead cannot be 0. Also a resource policy based invocation won’t be impacted from any STS service failure.</p><h3>Q: Can I use resource-policy based invocation for other AWS service to reduce the latency?</h3><p>The short answer is no at this time. That requires 2 pieces: the AWS service should support resource based policy and API Gateway should integrate with the service to send additional information (e.g. sourceArn for Lambda) for the resource policy evaluation. There are several services that support it, but API Gateway hasn’t integrated with them other than Lambda.</p><p>In fact, this is not specific on API Gateway to Lambda. As long as the calling service and the target service support, this resource policy based invocation can be applied.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8109451e44d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon API Gateway: Explaining HTTP Proxy in HTTP API]]></title>
            <link>https://medium.com/@lancers/amazon-api-gateway-explaining-http-proxy-in-http-api-3ea0afe6b03c?source=rss-bdf1c6b4acaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ea0afe6b03c</guid>
            <category><![CDATA[http-api]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[http-proxy]]></category>
            <category><![CDATA[amazon-api-gateway]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Jaewoo Ahn]]></dc:creator>
            <pubDate>Thu, 16 Sep 2021 18:43:06 GMT</pubDate>
            <atom:updated>2021-09-16T18:43:06.515Z</atom:updated>
            <content:encoded><![CDATA[<p>A year ago, I wrote a <a href="https://medium.com/@lancers/amazon-api-gateway-explaining-lambda-payload-version-2-0-in-http-api-24b0b4db5d36">post to explain Lambda Payload version 2.0 in HTTP</a>. This time, this long over-due post will explain how HTTP Proxy integration behavior is different between REST API and HTTP API and why it was designed like that. Are they different? Yes, they are.</p><h3>REST API: HTTP integration vs. HTTP Proxy integration</h3><p>Let’s revisit REST API first. Do you remember that REST API has HTTP integration and HTTP Proxy integration? This is what <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-integration-types.html">the official document</a> says, but can you understand the difference clearly?</p><blockquote>HTTP: This type of integration lets an API expose HTTP endpoints in the backend. With the HTTP integration, also known as the HTTP custom integration, you must configure both the integration request and integration response. You must set up necessary data mappings from the method request to the integration request, and from the integration response to the method response.</blockquote><blockquote>HTTP_PROXY: The HTTP proxy integration allows a client to access the backend HTTP endpoints with a streamlined integration setup on single API method. You do not set the integration request or the integration response. API Gateway passes the incoming request from the client to the HTTP endpoint and passes the outgoing response from the HTTP endpoint to the client.</blockquote><p>The document is trying to say “<em>HTTP proxy is more streamlined, since it requires a less configuration</em>” but it is not clear how their behavior are different in the runtime. And it also says “<em>you do not set the integration request or the integration response</em>” but actually you <em>can</em> set the integration request in the HTTP proxy integration.</p><p>A difference between them is <em>how much</em> changes you can make on the integration request (a request to your HTTP backend endpoint) and integration response (a response from your HTTP backend endpoint). With HTTP integration, you can modify the header/querystring/path parameter /body in the request and the header/body in the response. In contrast, with HTTP proxy integration, you can only modify the header/querystring/path parameter in the request. You cannot change the request body and anything on the response.</p><p>In reality, they do more than that underneath. Some of those behaviors are documented in <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-known-issues.html#api-gateway-known-issues-rest-apis">the known issues</a>, while others are not, but let’s set aside them. Instead, let’s focus on what would be an ideal behavior of HTTP proxy integration in API Gateway and what has been changed.</p><h3>Three common forms of HTTP Intermediaries</h3><p><a href="https://tools.ietf.org/html/rfc7230#section-2.3">RFC7230</a> defines three common forms of HTTP intermediaries. In short:</p><ul><li>A “proxy” (a.k.a. “forward proxy”) is a message-forwarding agent that is selected by the client, usually via local configuration rules, to receive requests for some type(s) of absolute URI and attempt to satisfy those requests via translation through the HTTP interface.</li><li>A “gateway” (a.k.a. “reverse proxy”) is an intermediary that acts as an origin server for the outbound connection but translates received requests and forwards them inbound to another server or servers.</li><li>A “tunnel” acts as a blind relay between two connections without changing the messages.</li></ul><p>Some of other API Gateway product provide Forward-proxy mode, but it only makes sense when the API Gateway is running on-premise. Since Amazon API Gateway does not provide on-premise option, that doesn’t apply. You don’t want to use Amazon API Gateway as a tunnel either since it is too expensive for the purpose. We can say API Gateway should work as “gateway” literally, then it must/should do what “gateway” must/should do as defined in the RFC. What must/should it do?</p><p>HTTP API was primarily designed to pass end-to-end in a transparent way as possible while it complies the RFC specification. No more arbitrary pass-through, drop, nor remap. So you can say HTTP API’s HTTP proxy integration is <strong>HTTP more-transparent proxy integration</strong>. Still how is it different?</p><h3>Via header</h3><p>According to <a href="https://tools.ietf.org/html/rfc7230#section-5.7.1">RFC 7230 Section 5.7.1</a>, an HTTP-to-HTTP gateway MUST send a Via header to the inbound request and MAY send a Via header filed in forwarded response messages. The intention of Via header is telling the presence of intermediary — received-protocol and received-by.</p><p>Let’s imagine the client send a request with HTTP/2 like this.</p><pre>// Client request<br>GET /test HTTP/2</pre><p>Wait, does Amazon API Gateway support HTTP/2? Yes or no. Precisely speaking, API Gateway’s API “endpoint” supports HTTP/2 (meaning you can send HTTP/2 request to it) while API Gateway DataPlane does not support HTTP/2. The endpoint should be downgraded it to HTTP/1.1 to be sent to the DataPlane that is only able to send HTTP/1.1 request to the integration.</p><p>That’s what exactly the Via header should tell to your integration. You can figure out the request comes from AmazonAPIGateway using HTTP/1.1.</p><pre>// Integration request<br>GET /test HTTP/1.1<br><em>Via: HTTP/1.1 AmazonAPIGateway</em></pre><p>Ideally, it should have shown that the API endpoint received HTTP/2 and downgraded to HTTP/1.1 via AmazonAPIGateway, but the endpoint does not support Via header.</p><pre>// Ideal Integration request<br>GET /test HTTP/1.1<br>Via: <em>HTTP/2 abcdef.yourapi.com, </em>HTTP/1.1 AmazonAPIGateway</pre><p>In contrast, Via header is not mandatory for the response. Most people don’t want to expose the fact to the client that your API is served by Amazon API Gateway (though it was common to see “Powered by XXX” in a decade ago). Thus it won’t add the header in the response.</p><pre>// Integration response<br>HTTP/1.1 200 OK<br><br>// Client response <br>HTTP/2 200</pre><p>Just reminder, using Via header for any authorization purpose on your integration is NOT recommended.</p><h3>User-Agent header</h3><p><a href="https://tools.ietf.org/html/rfc7231#section-5.5.3">RFC 7231 Section 5.5.3</a> defines that the header contains formation about the user agent <strong>originating</strong> the request. This implies that User-Agent should not be overwritten by the intermediary unless you intentionally want to hide the originator. Even when the client didn’t send User-Agent header, it should not be added unless you explicitly configure the intermediary to send it.</p><p>It sounds natural as it should be, right? However, REST API has a funky behavior on this. If you use HTTP integration, the integration request would have a following User-Agent whether the original request has User-Agent header or not.</p><pre>User-Agent: AmazonAPIGateway_&lt;YOUR_API_ID&gt;</pre><p>IMHO, this should have been Via header instead of overriding User-Agent header, though you can argue “HTTP integration” is not a proxy since it doesn’t have “proxy” in the name which differentiates it from “HTTP proxy integration”. To forward the original User-Agent with HTTP integration, you need to use a parameter mapping to set the User-Agent header with <em>context.identity.user-agent</em> or use a request override in the mapping template.</p><p>If you use HTTP proxy integration, the integration request would have an original User-Agent header when it is available. However, if the original request doesn’t have the header, API Gateway add the header same as HTTP integration.</p><p>For both HTTP integration and HTTP proxy integration, when the original request does not have User-Agent header, there is no way to send an integration request WITHOUT User-Agent header. Thus there is no way to reflect the original request as is.</p><p>In contrast, HTTP API does not perform a magical override/addition since API Gateway itself does not originate a request. The User-Agent header always reflect the originating request whether it is available or not. Of course, you can use a parameter mapping to override it.</p><h3>Forwarded header</h3><p>Before <a href="https://tools.ietf.org/html/rfc7239">RFC7239</a> came out with a standard <em>Forwarded</em> header, the non-standard X-Forwarded-* headers (X-Forwarded-For, X-Forwarded-Host, X-Forwarded-Proto, etc) has been worked as de-facto-standard. Those headers are not mandatory but optional. However, generally it is expected to be emitted when a proxy or a gateway has been involved as those headers can be used for debugging, statistics, security purposes, etc.</p><p>The standard Forwarded header has a benefit since it embraces several other X-Forwarded-* headers. For example, these 3 headers:</p><pre>X-Forwarded-For: 123.34.567.89, 192.0.2.43, [APIGW_IP]<br>X-Forwarded-Host: apiid.execute-api.us-east-1.amazonaws.com<br>X-Forwarded-Proto: https</pre><p>can be represented by a single Forwarded header:</p><pre>Forwarded: for=123.34.567.89,for=192.0.2.43;by=[APIGW_IP];host=apiid.execute-api.us-east-1.amazonaws.com;proto=https</pre><p>As recommended from the RFC, HTTP API translates incoming X-Forwarded-For headers into a Forwarded header as defined in the RFC and append the egress IP with “by”, the endpoint domain name with “host”, and protocol. This eliminates the necessity of mapping $context variables into the parameter by hand.</p><p>Unfortunately, there is downside. Between API Gateway and your backend, if there is an intermediary (e.g. LoadBalancer) which does not understand Via header, it will end up with adding XFF header. In the case, it is recommended to check both Forwarded header and XFF header.</p><pre>Forwarded: for=123.34.567.89,for=192.0.2.43;by=[APIGW_IP];host=apiid.execute-api.us-east-1.amazonaws.com;proto=https<br>X-Forwarded-For: [APIGW_IP]</pre><p>It would be nice if the behavior is configurable (opt-in to use XFF instead), but it isn’t available at this time.</p><h3>Hop-by-Hop headers</h3><p>Hop-by-hop headers are meaningful only for a single transport-level connection in contrast to end-to-end headers which are transmitted to the ultimate recipient of a request or response.</p><p>The <a href="https://tools.ietf.org/html/rfc2616#section-13.5.1">obsoleted RFC2616</a> listed following hop-by-hop headers:</p><pre>Connection, Keep-Alive, Proxy-Authenticate, Proxy-Authorization, TE, Trailers, Transfer-Encoding, Upgrade</pre><p>and Connection header can contain the list of headers considered as hop-by-hop.</p><p>However, <a href="https://tools.ietf.org/html/rfc7230#section-6.1">RFC7230</a> removed the explicit list of headers, and defer the decision to the Connection header. It means Connection header is the only hop-by-hop header by default, and all other headers must be listed under Connection header if they want to be treated as hop-by-hop headers.</p><pre>Connection: close, TE, Transfer-Encoding</pre><p>By the definition, hop-by-hop headers should be consumed by the immediate connection only and removed before forwarding the request to the downstream. This is a bit complex since there is “API endpoint” between the client and API Gateway DataPlane. From API Gateway DataPlane’s perspective, the API endpoint is an immediate connection.<br>The problem is that the API endpoint does not handle hop-by-hop headers correctly. It consumes and removes Connection header while it does not remove headers specified in the Connection header nor remove the old known hop-by-hop headers in RFC2616. With this reason, HTTP API consumes and removes the old known hop-by-hop headers in RFC2616 as a last resort.</p><h3>RequestId and API Gateway emitted custom headers</h3><p>Like many AWS services, API Gateway also emits API Gateway-specific header. The response from REST API should have “x-amzn-requestid” which is UUID style request id and “x-amz-apigw-id” which is an extended request id. If the response doesn’t contain those headers, that means the request never reach the API Gateway DataPlane and the response came from somewhere else, like your proxy or API endpoint.</p><pre>HTTP/1.1 200 OK<br>x-amzn-requestid: eb26c844-eb6b-4321-a1c5-d23350779a57<br>x-amz-apigw-id: Fw52dGF5vHcFuYg=</pre><p>The existence of “x-amzn-*” headers in the response actually discloses that the customer’s API is built in Amazon API Gateway. You may not like having it in the response, the request id is super-essential for the troubleshooting and operations for both you and AWS. Okay, agree, but should it be “x-amzn-*”? As a result, HTTP API emits a single <em>apigw-requestid</em> header in the response, with a format of extended request id.</p><pre>HTTP/1.1 200 OK<br>...<br>apigw-requestid: Fw406iQ_vHcEPIw=</pre><p>There are few things to note:</p><ul><li>For a long time, the <em>x-</em> prefix has been conventionally used for the custom headers. <a href="https://tools.ietf.org/html/rfc6648">RFC6648</a> deprecated the ‘x-’ convention for the custom header in the application protocol because of the inconveniences it caused when nonstandard fields became standard.</li><li>‘amzn’ has been dropped to make it more generic, not tied to Amazon or AWS.</li><li>HTTP API will use <strong>apigw-</strong> prefix for the any custom header that is emitted by API Gateway. API Gateway reserves the prefix for its own use. Any “apigw-” headers in the incoming request or integration response would be ignored and dropped.</li></ul><p>The header(s) are not passed to the integration request by default except when you’re using Lambda Proxy integration that passes it as part of <em>requestContext</em>. In many cases, you’ll need to have API Gateway’s request id since it makes easier to correlate requests between API Gateway and your backend integration. If you want to pass the request id to the integration for the tracing purpose, you must configure as an explicit parameter mapping with $context.requestId.</p><h3>CORS headers</h3><p>CORS headers is one of the example that can cause a conflict between Integration Response header and API Gateway emitted header. What if API Gateway CORS is configured but the integration response also contains CORS header?</p><p>When HTTP API was in beta, this was what described in the document.</p><pre>… For a CORS request, API Gateway adds the configured CORS headers to the response from an integration.<br><br>Note<br>If your backend integration explicitly returns CORS headers, those headers take precedence and override headers in the CORS configuration.</pre><p>When it became GA, there was a breaking change on this in an opposite way.</p><pre>Note<br>If you configure CORS for an API, API Gateway ignores CORS headers returned from your backend integration.</pre><p>The rationale behind this is simple: When you enabled the CORS in API Gateway, then you want to control the CORS with API Gateway so it takes the precedence over the CORS headers in the integration response regardless of integration type. If you want to honor the CORS header from the integration, just disable API Gateway CORS configuration.</p><h3>Compressed Payload</h3><p>What if the request payload is compressed (content-encoded)?</p><p>REST API always has decompressed the payload before sending it to the integration, thus the integration backend always receives the decompressed payload. This sometimes leads to an unexpected behavior when you’re playing around API Gateway’s 10MB payload limit or Lambda’s 6MB payload limit. If the client sent 7MB compressed payload, you easily think it’s still under API Gateway’s limit. However, it can turn to more than 10MB after decompressing it where API Gateway checks the payload size again, then it would be rejected. For Lambda, the binary payload needs to be base64 encoded which bloats the size, so even compressed 1–2MB binary payload can hit the 6MB limit.</p><p>Since the payload is always decompressed, the Content-Encoding header must be dropped or set to identity in the integration header, but HTTP/Lambda non-proxy integration does not deal it correctly.</p><p>In contrast, HTTP API does not decompress the payload at all, thus the payload and Content-Encoding header would be passed as is into the integration. HTTP API still has 10MB limit, but the compressed 10MB also should be fine for HTTP Proxy integration.<br>However, in other word, there is no way to decompress the request payload nor compress the response payload in HTTP API at this time, thus you must handle it within your integration backend.</p><h3>Summary</h3><p>Here’s a summary for the changes:</p><ul><li>HTTP API adds/appends Via header</li><li>HTTP API translates X-Forwarded-* headers into the standard Forwarded header then append it to the integration request</li><li>HTTP API does not touch User-Agent header</li><li>HTTP API removes Hop-by-Hop headers before forwarding the request to the integration</li><li>HTTP API reserves ‘apigw-’ prefix for the API Gateway specific custom headers. ‘apigw-*’ headers in the incoming request and integration response would be ignored and dropped</li><li>HTTP API renamed the request id header to ‘apigw-requestid’</li><li>HTTP API ignores/drops CORS header in the integration response once API CORS configuration is enabled</li><li>HTTP API passes the compressed payload and Content-Encoding header as is</li></ul><p>p.s. I wrote this with my best personal knowledge but this may contain an inaccurate info. If you found one, feel free to let me know!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ea0afe6b03c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon API Gateway: Enhanced Observability via access logs]]></title>
            <link>https://medium.com/@lancers/amazon-api-gateway-enhanced-observability-via-access-logs-dcc4182ee30c?source=rss-bdf1c6b4acaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcc4182ee30c</guid>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[api-gateway]]></category>
            <dc:creator><![CDATA[Jaewoo Ahn]]></dc:creator>
            <pubDate>Sat, 15 Aug 2020 05:21:14 GMT</pubDate>
            <atom:updated>2020-08-15T05:21:14.504Z</atom:updated>
            <content:encoded><![CDATA[<p>The logging is an essential tool to debug any issue. This is also true when you use API Gateway, and try to diagnose the latency and 4xx/5xx errors. Previously I wrote a post “<a href="https://medium.com/@lancers/how-to-dig-latencies-and-4xx-5xx-errors-on-aws-api-gateway-a5ca460714d3">How to dig latencies and 4xx/5xx errors on API Gateway</a>”, and mentioned API Gateway provides 2 types of log: Execution log and Access Log.</p><p>Execution Log explains how the API Gateway executes API invocation against your API. It shows an execution flow, more human-friendly, but tends to be verbose by the nature.<br>In contrast, Access Log is a structured log, more machine-parsable, and easy for the data processing. You can use it with CloudWatch Insight query or CloudWatch Contributor Insights. You have a full control to define your format with the available $context variables. Boldly speaking, Access Log is MUST-HAVE-ONE for anyone uses API Gateway in their production service. However, it didn’t provide enough information to diagnose latency or 4xx/5xx errors, so you should have to enable the execution log.</p><p>To close the gap, API Gateway just launched a set of new variables to enhance the observability on your API.</p><p><a href="https://aws.amazon.com/about-aws/whats-new/2020/08/amazon-api-gateway-supports-enhanced-observability-via-access-logs/">Amazon API Gateway now supports enhanced observability via access logs</a></p><p>Since now API Gateway has 3 types of APIs, so you have a slightly different set of variables: <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#context-variable-reference-access-logging-only">REST API</a>, <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-logging-variables.html">HTTP API</a>, <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/websocket-api-logging.html">WebSocket API</a>.</p><p>In a nutshell, all new variables will have a following scheme:</p><p><strong>$context.<em>phase</em>.latency<br>$context.<em>phase</em>.requestId<br>$context.<em>phase</em>.status<br>$context.<em>phase</em>.integrationStatus<br>$context.<em>phase</em>.error</strong></p><p>For example, if you WAF, you will have <strong>$context.waf.latency</strong>, <strong>$context.waf.status</strong>, and <strong>$context.waf.error</strong>. For integration, now you have <strong>$context.integration.latency</strong>, which is equivalent to the previous <strong>$context.integrationLatency</strong>. You can use <strong>$context.integration.requestId</strong> instead of <strong>$context.awsEndpointRequestId</strong>.<br>Please note that not all variables are available for all phase. You’ll need to check which phases are available for each API type, and which variables are available in each phase.</p><p>Here are the explanation for the each variables: (I omitted the prefix, <strong>$context.<em>phase</em>.</strong>)</p><h4>latency</h4><p>It’s straightforward. It shows how long it took to execute the phase in ms.</p><h4>requestId</h4><p>This is request id when API Gateway invokes AWS service configured by your authorizer or integration. When API didn’t get a response from the authorizer/integration (e.g. due to timeout or network error), this would be empty. Also some AWS service may not vend the request id which can be captured here, or may not vend one at all.</p><h4>error</h4><p>It’s straightforward, an error message.</p><p><strong>integrationStatus<br></strong>You’ll see this for authorizer or integration only. This is a physical status code when API Gateway received from the authorizer/integration “endpoint”. When you use Lambda, this means the status code from Lambda service itself.</p><p><strong>status<br></strong>This would be available for all phases. For the authorizer and integration, this is a semantic status code. For example, when you use Lambda proxy integration, this is what your Lambda function returned as proxy response format. With this reason, integrationStatus and status could have a different value. If integrationStatus is 200, but status is 5xx, it means Lambda service itself successfully executed your function but your function caused the 5xx. When integrationStatus is 5xx, status is unlikely available since Lambda service itself had an issue to execute Lambda function.</p><h3>Show me the example!</h3><p>Let’s see how it is working. I’ll use REST API as an example here.</p><p>First, here is my previous access log format.</p><pre>{<br>    &quot;requestId&quot;: &quot;$context.requestId&quot;,<br>    &quot;ip&quot;: &quot;$context.identity.sourceIp&quot;,<br>    &quot;requestTime&quot;: &quot;$context.requestTime&quot;,<br>    &quot;httpMethod&quot;: &quot;$context.httpMethod&quot;,<br>    &quot;resourcePath&quot;: &quot;$context.resourcePath&quot;,<br>    &quot;status&quot;: &quot;$context.status&quot;,<br>    &quot;protocol&quot;: &quot;$context.protocol&quot;,<br>    &quot;responseLength&quot;: &quot;$context.responseLength&quot;,<br>    &quot;wafResponse&quot;: &quot;$context.wafResponseCode&quot;,<br>    &quot;integrationStatus&quot;: &quot;$context.integrationStatus&quot;,<br>    &quot;integrationLatency&quot;: &quot;$context.integrationLatency&quot;,<br>    &quot;latency&quot; : &quot;$context.responseLatency&quot;<br>}</pre><p>I configured WAF, Lambda Authorizer, and Lambda integration. To demonstrate, I made 2 calls and got following responses.</p><pre><em>HTTP/1.1 401 Unauthorized<br>…<br>{“message”:”Unauthorized”}<br></em></pre><pre><em>HTTP/1.1 502 Bad Gateway<br>…<br>{“message”: “Internal server error”}</em></pre><p>What does my access log say?<br>Since I already mentioned that I configured authorizer, so you could guess it, but the access log doesn’t clearly tell you who returned 401.</p><pre>{<br>    &quot;requestId&quot;: &quot;309dcd10-f716-4bb3-a35e-09bcf7b5cc82&quot;,<br>    &quot;ip&quot;: &quot;72.21.198.64&quot;,<br>    &quot;requestTime&quot;: &quot;15/Aug/2020:04:05:32 +0000&quot;,<br>    &quot;httpMethod&quot;: &quot;GET&quot;,<br>    &quot;resourcePath&quot;: &quot;/&quot;,<br>    &quot;status&quot;: &quot;401&quot;,<br>    &quot;protocol&quot;: &quot;HTTP/1.1&quot;,<br>    &quot;responseLength&quot;: &quot;26&quot;,<br>    &quot;wafResponse&quot;: &quot;WAF_ALLOW&quot;,<br>    &quot;integrationStatus&quot;: &quot;-&quot;,<br>    &quot;integrationLatency&quot;: &quot;-&quot;,<br>    &quot;latency&quot;: &quot;19&quot;<br>}</pre><p>Here is a log for the second example. Where did 502 come from? IntegrationLatency shows 97ms, but latency is 191ms. Where did the overhead (94ms) come from? Why is API Gateway damn slow like this?</p><pre>{<br>    &quot;requestId&quot;: &quot;599a026a-2203-4dc9-9f74-0a8ae900be6f&quot;,<br>    &quot;ip&quot;: &quot;72.21.198.64&quot;,<br>    &quot;requestTime&quot;: &quot;15/Aug/2020:04:05:36 +0000&quot;,<br>    &quot;httpMethod&quot;: &quot;GET&quot;,<br>    &quot;resourcePath&quot;: &quot;/&quot;,<br>    &quot;status&quot;: &quot;502&quot;,<br>    &quot;protocol&quot;: &quot;HTTP/1.1&quot;,<br>    &quot;responseLength&quot;: &quot;36&quot;,<br>    &quot;wafResponse&quot;: &quot;WAF_ALLOW&quot;,<br>    &quot;integrationStatus&quot;: &quot;200&quot;,<br>    &quot;integrationLatency&quot;: &quot;97&quot;,<br>    &quot;latency&quot;: &quot;191&quot;<br>}</pre><p>This doesn’t have enough information for you to debug. You’ll ended up to enable the execution log to figure it.</p><h3>Show me the enhancement!</h3><p>Here is my revised log format with new variables.</p><pre>{<br>    &quot;requestId&quot;: &quot;$context.requestId&quot;,<br>    &quot;ip&quot;: &quot;$context.identity.sourceIp&quot;,<br>    &quot;requestTime&quot;: &quot;$context.requestTime&quot;,<br>    &quot;httpMethod&quot;: &quot;$context.httpMethod&quot;,<br>    &quot;resourcePath&quot;: &quot;$context.resourcePath&quot;,<br>    &quot;status&quot;: &quot;$context.status&quot;,<br>    &quot;protocol&quot;: &quot;$context.protocol&quot;,<br>    &quot;responseLength&quot;: &quot;$context.responseLength&quot;,<br>    &quot;latency&quot;: &quot;$context.responseLatency&quot;,<br>    &quot;waf&quot;: {<br>        &quot;latency&quot;: &quot;$context.waf.latency&quot;,<br>        &quot;status&quot;: &quot;$context.waf.status&quot;,<br>        &quot;response&quot;: &quot;$context.wafResponseCode&quot;<br>    },<br>    &quot;authorizer&quot;: {<br>        &quot;requestId&quot;: &quot;$context.authorizer.requestId&quot;,<br>        &quot;latency&quot;: &quot;$context.authorizer.latency&quot;,<br>        &quot;integrationStatus&quot;: &quot;$context.authorizer.integrationStatus&quot;,<br>        &quot;status&quot;: &quot;$context.authorizer.status&quot;,<br>        &quot;error&quot;: &quot;$context.authorizer.error&quot;<br>    },<br>    &quot;integration&quot;: {<br>        &quot;requestId&quot;: &quot;$context.integration.requestId&quot;,<br>        &quot;latency&quot;: &quot;$context.integration.latency&quot;,<br>        &quot;integrationStatus&quot;: &quot;$context.integration.integrationStatus&quot;,<br>        &quot;status&quot;: &quot;$context.integration.status&quot;,<br>        &quot;error&quot;: &quot;$context.integration.error&quot;<br>    }<br>}</pre><p>I sent same 2 requests.</p><p>Here is for 401. You can see authorizer triggered 401 but there is no requestId for that. Yes, this means Lambda authorizer function wasn’t invoked at all since I didn’t provide any identity source at all.</p><pre>{<br>    &quot;requestId&quot;: &quot;79d48482-40c0-4209-b503-d7813b25deeb&quot;,<br>    &quot;ip&quot;: &quot;72.21.198.64&quot;,<br>    &quot;requestTime&quot;: &quot;15/Aug/2020:04:26:03 +0000&quot;,<br>    &quot;httpMethod&quot;: &quot;GET&quot;,<br>    &quot;resourcePath&quot;: &quot;/&quot;,<br>    &quot;status&quot;: &quot;401&quot;,<br>    &quot;protocol&quot;: &quot;HTTP/1.1&quot;,<br>    &quot;responseLength&quot;: &quot;26&quot;,<br>    &quot;latency&quot;: &quot;23&quot;,<br>    &quot;waf&quot;: {<br>        &quot;latency&quot;: &quot;7&quot;,<br>        &quot;status&quot;: &quot;200&quot;,<br>        &quot;response&quot;: &quot;WAF_ALLOW&quot;<br>    },<br>    &quot;authorizer&quot;: {<br>        &quot;requestId&quot;: &quot;-&quot;,<br>        &quot;latency&quot;: &quot;0&quot;,<br>        &quot;integrationStatus&quot;: &quot;-&quot;,<br>        &quot;status&quot;: &quot;401&quot;,<br>        &quot;error&quot;: &quot;-&quot;<br>    },<br>    &quot;integration&quot;: {<br>        &quot;requestId&quot;: &quot;-&quot;,<br>        &quot;latency&quot;: &quot;-&quot;,<br>        &quot;integrationStatus&quot;: &quot;-&quot;,<br>        &quot;status&quot;: &quot;-&quot;,<br>        &quot;error&quot;: &quot;-&quot;<br>    }<br>}</pre><p>And this is for 502. You can see integration’s integrationStatus is 200, but there is an error, “Execution failed due to configuration error: Malformed Lambda proxy response”. This means Lambda successfully executed your function, but your function returned malformed response, so API Gateway couldn’t translate it to the semantic status. Also you can see where the latency gap came from. Total latency is 175ms and integration took 87ms. The gap is 88ms, which is contributed by WAF 11ms and authorizer 43ms. So pure API Gateway overhead was 34ms. In fact, this includes STS latency to assume the role since I used role-based invocation to call Lambda, but variables for STS is not supported yet.</p><pre>{<br>    &quot;requestId&quot;: &quot;c122fda2-70de-440d-b0aa-bb3a72363dd3&quot;,<br>    &quot;ip&quot;: &quot;72.21.198.64&quot;,<br>    &quot;requestTime&quot;: &quot;15/Aug/2020:04:32:32 +0000&quot;,<br>    &quot;httpMethod&quot;: &quot;GET&quot;,<br>    &quot;resourcePath&quot;: &quot;/&quot;,<br>    &quot;status&quot;: &quot;502&quot;,<br>    &quot;protocol&quot;: &quot;HTTP/1.1&quot;,<br>    &quot;responseLength&quot;: &quot;36&quot;,<br>    &quot;latency&quot;: &quot;175&quot;,<br>    &quot;waf&quot;: {<br>        &quot;latency&quot;: &quot;11&quot;,<br>        &quot;status&quot;: &quot;200&quot;,<br>        &quot;response&quot;: &quot;WAF_ALLOW&quot;<br>    },<br>    &quot;authorizer&quot;: {<br>        &quot;requestId&quot;: &quot;514d6960-b1aa-4a52-a029-9762ce8b8456&quot;,<br>        &quot;latency&quot;: &quot;43&quot;,<br>        &quot;integrationStatus&quot;: &quot;200&quot;,<br>        &quot;status&quot;: &quot;200&quot;,<br>        &quot;error&quot;: &quot;-&quot;<br>    },<br>    &quot;integration&quot;: {<br>        &quot;requestId&quot;: &quot;afd1ec1c-8534-4072-bc7d-981e443d7954&quot;,<br>        &quot;latency&quot;: &quot;87&quot;,<br>        &quot;integrationStatus&quot;: &quot;200&quot;,<br>        &quot;status&quot;: &quot;-&quot;,<br>        &quot;error&quot;: &quot;Execution failed due to configuration error: Malformed Lambda proxy response&quot;<br>    }<br>}</pre><p>Now, I have a Lambda request id: afd1ec1c-8534–4072-bc7d-981e443d7954. I intentionally made my Lambda to return a malformed response format. You can see I set “body1” instead of expected “body”.</p><pre>START RequestId: afd1ec1c-8534-4072-bc7d-981e443d7954 Version: $LATEST</pre><pre>afd1ec1c-8534-4072-bc7d-981e443d7954 INFO { statusCode: 200, body1: ‘“Hello from Lambda!”’ }</pre><pre>END RequestId: afd1ec1c-8534-4072-bc7d-981e443d7954</pre><p>For Lambda service’s perspective, they executed my function successfully, so my function is the culprit for the error. So you should add your own log from your function (e.g. console.log in node.js).</p><p>I fixed my bug, and invoked again, now it shows a happy 200 result.</p><pre>{<br>    &quot;requestId&quot;: &quot;9ad53459-dbb0-43b9-8f45-883e70d11a52&quot;,<br>    &quot;ip&quot;: &quot;72.21.198.64&quot;,<br>    &quot;requestTime&quot;: &quot;15/Aug/2020:05:06:02 +0000&quot;,<br>    &quot;httpMethod&quot;: &quot;GET&quot;,<br>    &quot;resourcePath&quot;: &quot;/&quot;,<br>    &quot;status&quot;: &quot;200&quot;,<br>    &quot;protocol&quot;: &quot;HTTP/1.1&quot;,<br>    &quot;responseLength&quot;: &quot;20&quot;,<br>    &quot;latency&quot;: &quot;93&quot;,<br>    &quot;waf&quot;: {<br>        &quot;latency&quot;: &quot;7&quot;,<br>        &quot;status&quot;: &quot;200&quot;,<br>        &quot;response&quot;: &quot;WAF_ALLOW&quot;<br>    },<br>    &quot;authorizer&quot;: {<br>        &quot;requestId&quot;: &quot;5cf5daf2-bc79-4aed-b328-38829d4082a5&quot;,<br>        &quot;latency&quot;: &quot;24&quot;,<br>        &quot;integrationStatus&quot;: &quot;200&quot;,<br>        &quot;status&quot;: &quot;200&quot;,<br>        &quot;error&quot;: &quot;-&quot;<br>    },<br>    &quot;integration&quot;: {<br>        &quot;requestId&quot;: &quot;6ee9d2ef-6434-462f-9a37-31dfef20e5e6&quot;,<br>        &quot;latency&quot;: &quot;14&quot;,<br>        &quot;integrationStatus&quot;: &quot;200&quot;,<br>        &quot;status&quot;: &quot;200&quot;,<br>        &quot;error&quot;: &quot;-&quot;<br>    }<br>}</pre><p>We hope that this would provide your better observability over your API when you use API Gateway. Not just adding more variables, we will continue to think about how we can improve the debugging.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcc4182ee30c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebSocket API: Sec-WebSocket-Protocol (Subprotocol) header support]]></title>
            <link>https://medium.com/@lancers/websocket-api-sec-websocket-protocol-subprotocol-header-support-277e34164537?source=rss-bdf1c6b4acaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/277e34164537</guid>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[amazon-api-gateway]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Jaewoo Ahn]]></dc:creator>
            <pubDate>Wed, 17 Jun 2020 22:30:04 GMT</pubDate>
            <atom:updated>2020-06-17T22:30:04.607Z</atom:updated>
            <content:encoded><![CDATA[<p>Fundamentally, WebSocket is a low-level protocol which allows you to send a data frame over HTTP after the handshaking. To leverage it correctly, the client and the server should use an application-level protocol describing how the message would look like, what we call “subprotocol”.<br>During the handshake, the client would ask the server what kind of subprotocols are supported by sending <em>Sec-WebSocket-Protocol</em> header.</p><pre>GET /chat HTTP/1.1<br>Host: server.example.com<br>Upgrade: websocket<br>Connection: Upgrade<br>Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==<br>Origin: http://example.com<br>Sec-WebSocket-Protocol: chat, superchat<br>Sec-WebSocket-Version: 13</pre><p>Then the server would select a subprotocol to use and let the client know which one would be used by sending <em>Sec-WebSocket-Protocol</em> header.</p><pre>HTTP/1.1 101 Switching Protocols<br>Upgrade: websocket<br>Connection: Upgrade<br>Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=<br>Sec-WebSocket-Protocol: chat</pre><p>However, if you ever tried to use subprotocol with WebSocket API in API Gateway in the past, you found that it was not possible. Why Amazon API Gateway didn’t consider this?</p><p>By design, WebSocket API is subprotocol-agnostic not to lock you down to the specific protocol(s). It is a fair criticism to say it is biased for JSON message since <em>routeSelectionExpression</em> supports JSON path only, but if you’re willing to route within your integration, you can use any data format with $default route.<br>WebSocket API is conceptually abstracted as a Serverless stateful service which bridges to the stateless world via routes. Strictly speaking, you own WebSocket API, not WebSocket server itself. There is a flip side: You don’t have a control for the WebSocket server and it does not wish to agree any subprotocol.</p><p><a href="https://tools.ietf.org/html/rfc6455#section-4.2.2">https://tools.ietf.org/html/rfc6455#section-4.2.2</a></p><blockquote>If the client’s handshake did not contain such a header field or if the server does not agree to any of the client’s requested subprotocols, the only acceptable value is null. The absence of such a field is equivalent to the null value (meaning that if the server does not wish to agree to one of the suggested subprotocols, it MUST NOT send back a |Sec-WebSocket-Protocol| header field in its response).</blockquote><p>So it had been subprotocol-ignorant rather than subprotocol-agnostic. What if you want to take a control for the subprotocol selection only? You understand that the subprotocol handling itself must be done by yourself, but you want to control Sec-WebSocket-Protocol header. Since the handshake is handled by API Gateway, API Gateway should allow to respond with the header.</p><p>Since <em>$connect</em> route handles the handshake, you should be able to access <em>Sec-WebSocket-Protocol </em>header in the request from your integration, then return a selected protocol as <em>Sec-WebSocket-Protocol</em> header in the integration response. Then the header in the <em>$connect</em> route response should be sent to the client. The response part was the showstopper since it didn’t allow you to return the header.</p><p>When you tested with wscat (<em>wscat</em> has <strong>-s, --subprotocol &lt;protocol&gt;</strong> option to send the header during the handshake), you had get this error.</p><pre>wscat -c &#39;wss://YOUR_API_ID.execute-api.YOUR_REGION.amazonaws.com/beta&#39; -s &#39;myprotocol&#39;<br>error: Server sent no subprotocol</pre><p>Now, the showstopper was gone as of today.</p><p><a href="https://aws.amazon.com/about-aws/whats-new/2020/06/amazon-api-gateway-allows-subprotocols-on-websocket-api-connection/">https://aws.amazon.com/about-aws/whats-new/2020/06/amazon-api-gateway-allows-subprotocols-on-websocket-api-connection/</a></p><h3>Return Sec-WebSocket-Protocol header from the $connect</h3><p>This is pretty much explained in the public document. You need to configure $connect route and it should return the header. Let’s imagine you’re using Lambda proxy integration. Here is an example of Lambda function:</p><pre>exports.handler = async (event) =&gt; {<br>    if (event.headers != undefined) {<br>        const headers = toLowerCaseProperties(event.headers);<br>        <br>        if (headers[&#39;sec-websocket-protocol&#39;] != undefined) {<br>            const subprotocolHeader = headers[&#39;sec-websocket-protocol&#39;];<br>            const subprotocols = subprotocolHeader.split(&#39;,&#39;);<br>            <br>            if (subprotocols.indexOf(&#39;myprotocol&#39;) &gt;= 0) {<br>                const response = {<br>                    statusCode: 200,<br>                    headers: {<br>                        &quot;Sec-WebSocket-Protocol&quot; : &quot;myprotocol&quot;<br>                    }<br>                };<br>                return response;<br>            }<br>        }<br>    }<br>    <br>    const response = {<br>        statusCode: 400<br>    };<br>        <br>    return response;<br>};</pre><pre>function toLowerCaseProperties(obj) {<br>    var wrapper = {};<br>    for (var key in obj) {<br>        wrapper[key.toLowerCase()] = obj[key];<br>    }<br>    return wrapper;<br>}</pre><p>This function accepts ‘myprotocol’ only, unless it returns 400 for other protocol. Now deploy your API.</p><h3>Test with wscat</h3><p>When &quot;myprotocol&quot; isn&#39;t included, the server will respond with 400 and the connection won’t be established. When it is available, the server will accept the connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*3XrZnGDlcatFPdp1Eju2Pw.png" /></figure><p>I hope this unblock your use case to use WebSocket API.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=277e34164537" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebSocket API: What does it mean that $disconnect is a best-effort event?]]></title>
            <link>https://medium.com/@lancers/websocket-api-what-does-it-mean-that-disconnect-is-a-best-effort-event-317b7021456f?source=rss-bdf1c6b4acaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/317b7021456f</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[amazon-api-gateway]]></category>
            <dc:creator><![CDATA[Jaewoo Ahn]]></dc:creator>
            <pubDate>Sat, 25 Apr 2020 06:58:59 GMT</pubDate>
            <atom:updated>2020-04-25T06:59:56.984Z</atom:updated>
            <content:encoded><![CDATA[<h3>WebSocket API: What does it mean that $disconnect is a best-effort event? How can I count active connections?</h3><p>Amazon API Gateway’s WebSocket API provides $connect and $disconnect routes to handle the initial upgrade (handshake) request and the disconnect event. $connect is synchronous, so the actual connection would be established after $connect is completed successfully. In contrast, you could find this from <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-route-keys-connect-disconnect.html#apigateway-websocket-api-routes-about-disconnect">the $disconnect route documentation</a>.</p><blockquote>The $disconnect route is executed after the connection is closed.</blockquote><blockquote>The connection can be closed by the server or by the client. As the connection is already closed when it is executed, $disconnect is a best-effort event. API Gateway will try its best to deliver the $disconnect event to your integration, but it cannot guarantee delivery.</blockquote><p>What does it mean $disconnect is best-effort event? Does it mean $disconnect might not be triggered at all when the client is disconnected? Many people worry about this part when they use $disconnect to clean up the resource (e.g. delete the connectionId from DDB, decrease the connection count).</p><p>To help your understanding, here is a diagram to show what’s happening when the client is disconnected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*3r7QnB3zcRY5LYnA3WRezQ.png" /></figure><p>Before moving on, you have to understand all boxes *could* be separated and distributed components. If everything happens within a single server, it is very easy to solve.</p><h3>Client and Server: How is the connection closed?</h3><p>In WebSocket, there are multiple ways to close the connection. The server can close the connection due to the idle time out, max connection duration, deleteConnection request, or server’s maintenance purpose. The client can close the connection too. And there is “unclean” close without sending a close frame (e.g. client crashed, network issue).</p><p>When there is an explicit close frame (either of client and server), $disconnect would be triggered immediately. In contrast, if there was no close frame, server doesn’t know until it hit the idle time, so the $disconnect could happen after 10 minutes.</p><h3>Server to $disconnect : Can it fail to deliver?</h3><p>YES. Although the server triggered the event, it may not be delivered to $disconnect route. We do our best effort, but there is no 100% guarantee in the distributed system. However, the failure rate on this phase is extremely low (as a reminder, API Gateway has at least <a href="https://aws.amazon.com/api-gateway/sla/">99.95% availability in SLA</a>).</p><h3>$disconnect to Lambda (or your integration endpoint)</h3><p>You configure $disconnect to invoke your integration, let’s say it’s Lambda. API Gateway invokes Lambda’s endpoint. Hold on, your function is not invoked yet. Even it may not reach to Lambda’s endpoint at all due to the network failure.</p><p>You may consider to use SQS for more reliable delivery. So instead of calling Lambda directly, you can put it to the SQS queue and trigger Lambda from it. Still API Gateway to SQS could be failed.</p><h3>Lambda to your Lambda function</h3><p>Lambda itself also consists of several distributed components. It is not 100% guaranteed to execute your function.</p><p>Additionally, your function may suffer the cold start more than 29 seconds, then the integration request would be timed out on API Gateway. Or, if you don’t have enough concurrency execution limit, Lambda will throttle the integration request.</p><h3>Within your Lambda function</h3><p>We don’t know what you’re doing within your Lambda function. If you’re trying to remove the connectionId from DDB, that can be failed too. Or your lambda function could have a bug. All developers does not suspect their own code.</p><p>Trust me, I saw the most failures here. Rather than worrying about the event is not being delivered, make your logic to handle it correctly when it delivered.</p><h3>Keep your eyes on 410 Gone</h3><p>Do not just rely on $disconnect. We recommend to implement “eventual consistency” along with @connections API (postToConnection, deleteConnection, and getConnection). When you get 410 from @connecton API, remove the connection.</p><h3>Counting active connections</h3><p>Commonly people asks why there is no active connections metric in WebSocket API. Also people feels that it is pretty hard and expensive to count the active connection with their own way.</p><p>So do we. It is very hard and expensive to count the active connections in the real time manner across the distributed systems. We will continue to seek whether we can provide it, but the disadvantage overwhelms it for now.</p><p>Please think again: Do you really need to track the active connection counts? Is it worth for spending efforts and resources? If you still have a reason (hopefully more than just displaying the number on the dashboard to show it to your executives), here are some ideas I can provide.</p><p>The simplest solution would be counting it against your connections storage. However, as you have more connections, count(*) would become more and more expensive. Simple is not the best in this case.</p><p>You can consider to implement a counter. Increase one on $connect, and decrease one on $disconnect. Hey, you already read about $disconnect. It depends how you make your $disconnect reliable. If you use $disconnect for other purpose, then it would be worth to add a counter along with it. Otherwise, I don’t want to recommend to use $disconnect just for the counter.</p><p>If you’re not looking for real-time, you can leverage the access logging. Get the $connect and $disconnect route logs periodically using CloudWatch Insight query to increment or decrement the counter. Similarly, you can leverage the metric instead , but route-level metric (you need this for $disconnect) is available in the paid metrics only.<br>This has an advantage as you don’t need to consider the failure between $disconnect and your integration or within your integration.</p><p>Alternatively, you can consider to leverage your own health check. For example, you expect all clients must report their health for each minute. Whenever you got a health check message from the client, you can increment the counter for the minute. Then use the last completed minute’s counter as an active connections counter. However, this would become more expensive if you’re looking for shorter interval such as each second. It’s trade-off between the accuracy and the cost.</p><p>If you have a better idea, feel free to share!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=317b7021456f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon API Gateway: Explaining Lambda Payload version 2.0 in HTTP API]]></title>
            <link>https://medium.com/@lancers/amazon-api-gateway-explaining-lambda-payload-version-2-0-in-http-api-24b0b4db5d36?source=rss-bdf1c6b4acaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/24b0b4db5d36</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Jaewoo Ahn]]></dc:creator>
            <pubDate>Sun, 15 Mar 2020 01:28:06 GMT</pubDate>
            <atom:updated>2020-03-15T01:37:27.346Z</atom:updated>
            <content:encoded><![CDATA[<h3>API Gateway: Explaining Lambda Payload version 2.0 in HTTP API</h3><p>HTTP API has been <a href="https://aws.amazon.com/blogs/compute/building-better-apis-http-apis-now-generally-available/">GA on Mar 12</a>. <a href="https://aws.amazon.com/blogs/compute/building-better-apis-http-apis-now-generally-available/">The blog</a> described new features and changes including <strong>Lambda payload version 2.0</strong> which would be used by default since GA. Although HTTP API provides a way to use 1.0 version of Lambda payload, <strong>changing the default</strong> introduced breaking changes from beta.</p><p>In this article, I’ll provide a certain level of explanation why and how it has been changed. The change has been made based on the lessons learned from previous experiences, heard a lot of feedbacks, and contemplated this. In short, it wasn’t changed just for an aesthetic reason.</p><h3>Lesson learned from REST API</h3><p>Before HTTP API, API Gateway provided 2 types of APIs: REST API and WebSocket API. REST API is the longest-lived one since 2015 and most popular. It also means that it had <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-known-issues.html#api-gateway-known-issues-rest-apis">more known issues</a> as a nature of the first product. Some of them has been addressed in either of good ways and bad ways. Sometimes, the solution looked good at the time when the decision is made, but later, it might not be in long-term perspective.</p><p>For example, REST API had not supported multi-value headers and query string parameters until <a href="https://aws.amazon.com/blogs/compute/support-for-multi-value-parameters-in-amazon-api-gateway/">they were allowed in 2018</a>. To explain what the change was, let’s imagine a following request:</p><pre>curl <a href="https://{hostname}/{path}?key=val&amp;key=val2&amp;key2=val3">https://{hostname}/{path}?key=val&amp;key=val2&amp;key2=val3</a> \<br>  -H &#39;FOO: bar0&#39; \<br>  -H &#39;foo: bar1&#39; \<br>  -H &#39;foo: bar2&#39; \<br>  -H &#39;foo2: bar3,bar4&#39;</pre><p>It looks silly to you, but mixing case(FOO, foo) had been one of the workarounds to send multi-value parameters in the past. HTTP header MUST be case-insensitive, but REST API has treated them as case-sensitive(NOTE: this is still a known issue in REST API. HTTP API has solved this).</p><p>Before the multi-value parameter was supported, the Lambda payload had looked like (removed other fields for clarification):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d33f22b1079c3c25d386ea49cc899b6/href">https://medium.com/media/2d33f22b1079c3c25d386ea49cc899b6/href</a></iframe><p>You could see the first value of <em>foo</em> and <em>key</em> was not included in the payload. API Gateway put the last value of each parameter and discarded everything else.</p><p>After the multi-value support, now the Lambda payload looks:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82d5a08b972ec55822f2ea7ded63c0bd/href">https://medium.com/media/82d5a08b972ec55822f2ea7ded63c0bd/href</a></iframe><p>It added a new pair of properties called <em>multiValueHeaders</em> and <em>multiValueQueryStringParameters</em> that is essentially a copy of <em>headers</em>/<em>queryStringParameters</em> but contains an array of strings instead of a single string.</p><p>It may be not a big deal for you, but let’s see how you can access each parameter. Does it look good to you?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2df542497dda6bcd66f3d2f8c48e45f4/href">https://medium.com/media/2df542497dda6bcd66f3d2f8c48e45f4/href</a></iframe><p>Although it allowed to use multi-value parameters without causing any breaking change for existing customer, there are some undesirable behaviors in this solution:</p><ul><li>The size of the payload is now bigger because all the headers exist in both “headers” and “multiValueHeaders”.</li><li>It is s non-intuitive that the existing “header” property itself doesn’t have all the values. To get all the values, you need to look in the “multiValueHeader” property, still dealing with comma-concatenated value(s).</li><li>Header case-sensitivity issue was not addressed.</li></ul><h3>Lesson learned from WebSocket API</h3><p>In December 2018, WebSocket API was launched. WebSocket API was the first non-HTTP protocol (although it is on top of HTTP protocol) in API Gateway. At the time, a lot of things within API Gateway had been targeted to REST API. For example, “resource” or “method” does not work well with WebSocket message. This is the reason API Gateway V2 model has been introduced and switched from “Resource” to “Route”.</p><p>The top-level fields in the Lambda payload didn’t require much change. The handshake request ($connect) is a pure HTTP request which does not require any change. The message route and $disconnect aren’t HTTP requests but non-compatible fields (e.g. resource and method) can be omitted.</p><p>But what about <em>requestContext</em>? WebSocket API requires a different set of fields from REST API. It ended up to omit some REST related fields while WebSocket related fields had been added into requestContext. For JSON schema perspective, they’re actually different models.</p><p>This brought questions to us. How can different protocols can be embraced within a unified model? What about grouping the related fields instead of making a lot of “optional” fields and let the consumer to figure out?</p><h3>Lesson learned from Lambda Proxy Response</h3><p>I bet almost everyone experienced “<a href="https://aws.amazon.com/premiumsupport/knowledge-center/malformed-502-api-gateway/">Malformed Lambda Response</a>” with 502 when they attempted to use Lambda proxy integration for the first time. You have tested your Lambda function in the Lambda console and everything works perfectly. But why API Gateway throws 502 when I tried to invoke it via Lambda proxy integration? You finally have to figure out that <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-output-format">API Gateway requires a specific JSON output format for the response</a>.</p><p>When people writes a business logic function, they perform a logic, then just want to return a result. It is perfectly fine within the function, but you have to consider the function returns a result to the remote caller which requires the serialization and data formatting. It is true between API Gateway and Lambda as well.</p><p>Additionally, when something is wrong, an exception would be thrown (some language doesn’t have exception though). If it is uncaught, the exception would be turned into 5xx errors any way. If there is nothing to do with the exception, catching exception and returning 5xx is not much worth to do.</p><p>In this context, we could blame the developer who didn’t read the <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-output-format">API Gateway Lambda Proxy output format documentation</a>. Well, I did a same mistake when I used Lambda Proxy but I didn’t feel comfortable to blame myself though. Can’t API Gateway provide a better developer experience?</p><h3>Lambda Proxy and its payload</h3><p>A HTTP request needs to be transformed into a payload which can be sent as an argument to a Lambda function, currently it is JSON. The payload must contain the semantics of HTTP and additional context information given by API Gateway.</p><p>With this context, Lambda Proxy is not HTTP proxy but it should do its best effort to imitate the behavior of HTTP proxy as much as possible. The previous Lambda payload did certain level of imitations, but there were known issues to be addressed and many lessons has been learned.</p><h3>Multi-value headers in Lambda payload 2.0</h3><p>Having both headers and multiValueHeaders in the payload is not ideal. It is more intuitive and easier to use when all values are available through “headers”.</p><p>To present headers in JSON, headers would be JSON object. Apparently the key would be the header field name, but there are several options to expose multiple header values in the value:</p><ul><li>Array or string</li><li>Always array</li><li>String (comma-concatenated)</li></ul><p><strong>Array or string</strong> is using Array when it is multi-value while using string when it is a single value. In theory, it sounds correct, but practically it is harder for both API Gateway and consumer. API Gateway has to serialize differently whether it is multi-value or not, and the consumer also need to check whether it is array or not.</p><p><strong>Always array</strong> is simple for API Gateway, but not ideal for the consumer who writes a Lambda function. You have to use <em>input.header.foo[0]</em> instead of <em>input.header.foo</em> even you only have a single header. You also need to deal with null or indexOutOfRange when the header is not available.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c300f3bd49785fd05521d982a33db7d9/href">https://medium.com/media/c300f3bd49785fd05521d982a33db7d9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed7c48ac51027448809c9d2fc0014656/href">https://medium.com/media/ed7c48ac51027448809c9d2fc0014656/href</a></iframe><p><strong>String (comma-concatenated)</strong> is most simple for both and it does not change any semantics of the message as mentioned in <a href="https://tools.ietf.org/html/rfc7230#section-3.2.2">RFC 7230</a>.</p><pre>&quot;A recipient MAY combine multiple header fields with the same field name into one &quot;field-name: field-value&quot; pair, without changing the semantics of the message, by appending each subsequent field value to the combined field value in order, separated by a comma.  The order in which header fields with the same field name are received is therefore significant to the interpretation of the combined field<br>value; a proxy MUST NOT change the order of these field values when forwarding a message.&quot;</pre><p>This was chosen in Lambda payload 2.0. As a result, you have a single string whether the value are multiple or not. Also there is no different between duplicated headers(foo) and a single header(foo2) contains a concatenated values. You might also noticed the case-sensitivity issue was gone, now all headers will be lower-cased.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68db3c207d310b4627a2f9862b9dda17/href">https://medium.com/media/68db3c207d310b4627a2f9862b9dda17/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f845c08e3bde9083c9f2ba85091d42e5/href">https://medium.com/media/f845c08e3bde9083c9f2ba85091d42e5/href</a></iframe><h3>Cookies in Lambda payload 2.0</h3><p>There is one problem with comma-concatenation in header: <em>Cookie</em> and <em>Set-Cookie</em>. They are exceptional header which should be concatenated with semi-colon instead. Even <em>Set-Cookie</em> allows to use comma within the value and the directive should be applied to the specific cooke element within the same line. If “cookie” or “set-cookie” header within “headers” in the payload, it does not work well with other headers.</p><p>In 2.0, the payload has a separate key named “cookie” which contains an array. For the request, each element in array corresponds with the value of “cookie” header. Each cookie will be individual element, whether they are sent as multiple “cookie” headers or semi-colon concatenated within a single “cookie” header.</p><p>If the request has following cookie headers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cd79aba35a74c7c9523b3cbae766635/href">https://medium.com/media/1cd79aba35a74c7c9523b3cbae766635/href</a></iframe><p>The payload will have:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c547776e1e871984986d29af7584cd7e/href">https://medium.com/media/c547776e1e871984986d29af7584cd7e/href</a></iframe><p>When the Lambda function returns like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50cb67b08e17fec1317459049b9d8ae6/href">https://medium.com/media/50cb67b08e17fec1317459049b9d8ae6/href</a></iframe><p>The response will have following <em>set-cookie</em> headers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afc6c8ab1d0e314ef9b81d885a99cd9e/href">https://medium.com/media/afc6c8ab1d0e314ef9b81d885a99cd9e/href</a></iframe><h3>Query String in Lambda payload 2.0</h3><p>Unlike headers, the RFC specification doesn’t mention how to handle duplicated query parameters. Depends on server’s implementation, <em>query1=value1&amp;query1=value2</em> could be:</p><ul><li>First-win : “value1”</li><li>Last-win : “value2”</li><li>Array : [ “value1”, “value2” ]</li><li>Comma-concatenated : “value1,value2”</li></ul><p>Lambda payload 2.0 concatenate multi-value query string parameter values with comma. It is consistent along with headers’s behavior and is more intuitive.</p><p>However, there are few more cases to consider in the query string.<br>First, what if the value itself contains comma?<br><strong><em>query1=value1&amp;query2=foo,bar&amp;query1=value2<br></em></strong>A comma(,) is a reserved character in the RFC, but it is not clear when comma is used within the query string parameter value. Some people might use it as a multi-value same as headers, but other might use it in the different semantic. The comma concatenation will cause a problem for the latter case.</p><p>Second, what if the customer are very sensitive for the order of query string? <br>For example, <strong><em>query1=value1&amp;query2=foo,bar&amp;query1=value2</em></strong> will do:</p><ul><li>DoActionOnQuery1(“value1”)</li><li>DoActionOnQuery2(“foo,bar”)</li><li>DoActionOnQuery1(“value2”)</li></ul><p>While <strong><em>query1=value1&amp;query1=value2&amp;query2=foo,bar </em></strong>might cause a different result:</p><ul><li>DoActionOnQuery1(“value1”)</li><li>DoActionOnQuery1(“value2”)</li><li>DoActionOnQuery2(“foo,bar”)</li></ul><p>For those cases, Lambda payload 2.0 will have <em>rawQueryString</em> for those customer to parse the query string as they want. So the <strong><em>query1=value1&amp;query2=foo,bar&amp;query1=value2</em></strong><em> would be:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93b230ec55d403030b46206ec268eb12/href">https://medium.com/media/93b230ec55d403030b46206ec268eb12/href</a></iframe><h3>RequestContext in Lambda payload 2.0</h3><p>As explained before, requestContext has many top-level optional fields depends on the protocol and route type:</p><ul><li>REST API</li><li>WebSocket API $connect</li><li>WebSocket API other routes (message, $disconnect)</li></ul><p>Additionally, which the authorizer are used, all fields under “authorizer” were optional and conditional. Here is a rough view of them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e2968667218f3d64a129d43c55422b8/href">https://medium.com/media/2e2968667218f3d64a129d43c55422b8/href</a></iframe><p>Now, Lambda payload 2.0 has following groups and put them into hierarchical structure. When the protocol is “http” and the authorizer is “jwt”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac931dde00f11e48c6dbca133b318518/href">https://medium.com/media/ac931dde00f11e48c6dbca133b318518/href</a></iframe><p>When the protocol is “websocket” and the authorizer is “lambda”, it would be:<br>(<strong>NOTE: This is an illustration purpose. WebSocket API does not support Lambda Payload 2.0 and Lambda authorizer is not supported in HTTP API yet</strong>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0d07b5672fee8343516eea48699fab9/href">https://medium.com/media/a0d07b5672fee8343516eea48699fab9/href</a></iframe><h3>Simplified Lambda Proxy response in Lambda Proxy 2.0</h3><p>In Lambda proxy 2.0, if you want, you just can return any JSON without the strict formatting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d49604f4e978338d4d0c8ef617742d7/href">https://medium.com/media/1d49604f4e978338d4d0c8ef617742d7/href</a></iframe><p>This is equivalent to this. API Gateway infers that you’re trying to return “200” with JSON payload, then put the JSON into the body.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7971dc0bced5ca979a28cb8e021407e6/href">https://medium.com/media/7971dc0bced5ca979a28cb8e021407e6/href</a></iframe><p>Remember, you can still use the previous response output format to customize status code, header, or isBase64Encoded.</p><h3>Why 2.0 become default in GA?</h3><p>Lambda payload version 2.0 includes the lessons learned and improvements. This should have been a default format in HTTP API. Unfortunately, this wasn’t included in Beta features.</p><p>Choosing a default is very hard decision but generally it should be the suitable for the most of the case since people tend to use it without make any change. If 2.0 format was being introduced to existing REST API which has been running in production since 2015, it would never be default. New features must be opt-in without breaking existing customers.</p><p>In contrast, HTTP API is a brand-new service. So the risks has been taken to make a breaking change since there was a strong belief on doing a right thing in the long-term value. If 1.0 format is kept as default, more people will be in production without customizing it to 2.0.</p><p>Nevertheless, those breaking changes should been communicated well with the people who has used HTTP API Beta. I personally apologize any inconvenience caused by this change.</p><h3>Still don’t favor 2.0 format?</h3><p>I hope that the rationale behind the change has been explained enough, but please free to leave a comment if you have any doubt or if you still don’t like 2.0 format.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24b0b4db5d36" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>