1. 程式人生 > >[email protected] Design Best Practices

[email protected] Design Best Practices

This blog post is the first in a series about [email protected] best practices to help you optimize using [email protected] throughout the life cycle of your application. Topics will include how to create the best [email protected] design for your use case, how to integrate [email protected]

in your CI/CD pipeline, and how to make sure your solution is working well and addressing your business needs. In this first post, I’ll focus on best practices for designing [email protected] solutions. I’ll share some common use cases when our customers have implemented [email protected] solutions, explain how to choose when to trigger a
[email protected]
function, and, finally, provide recommendations to optimize performance and cost efficiency when you’re working with [email protected]

[email protected] enables you to run Node.js functions across AWS locations globally without provisioning or managing servers. This capability allows you to deliver richer and more personalized content to your customers with low latency. Functions that customize content can run at different times, depending on what you want to accomplish. For example, you might decide to have CloudFront execute a function when viewers request content, or when CloudFront makes a request to your origin server. After you upload your Node.js code to

[email protected], the service takes care of everything required to replicate, route, and scale your code with high availability, so functions can run at an AWS location close to your users. You pay only for the compute time that you use.

Common use cases

There are many solutions already implemented by our customers today for business use cases. The benefits of using [email protected] can be divided into the following four categories:

Performance: One of the biggest benefits of using [email protected] is to improve the cache hit ratio by either increasing the likelihood that content will be cached when it’s returned from the origin, or increasing the usability of content that’s already in cache. An improved cache hit ratio results in better application performance by avoiding latency caused by a cache miss. Here are some examples of how you can use [email protected] to improve the cache hit ratio:

  • Add or modify cache control headers on responses
  • Implement follow redirection for 3xx responses from your origin, to reduce viewer response latency
  • Use query string or user agent normalization to reduce request variably
  • Dynamically route to different origins based on attributes of request headers, cookies, or query strings

Dynamic Content Generation: With [email protected], you can dynamically generate custom content based on attributes of requests or responses. For example, you can do the following:

  • Resize images based on request attributes
  • Render pages based on a logic-less template, such as Mustache
  • Do A/B testing
  • Generate a 302/301 redirection response for all requests to an expired or outdated resource

Security: [email protected] can also be used to handle custom authentication and authorization. The following are some example use cases:

  • Sign requests to custom origins that enforce access control
  • Configure viewer token authentication, for example, by using a JWT/MD5/SHA token hash
  • Set up bot detection
  • Add HSTS or CSP security headers

Origin independence: In some scenarios, origins require additional logic for requests and responses. Instead of implementing this in code that runs on the origin server, you can execute a [email protected] function in CloudFront instead, for a more seamless solution. For example, you can implement logic to do the following:

  • Create pretty URLs
  • Manage authentication and authorization for origin requests
  • Manipulate URL or requests to match your origin directory structure
  • Implement custom load balancing and failover logic

Choose the right trigger

You can trigger [email protected] functions to be executed on the following four different CloudFront events:

Request Response
Origin Executes on a cache miss, before a request is forwarded to the origin Executes on a cache miss, after a response is received from the origin
Viewer Executes on every request before CloudFront’s cache is checked Executes on all requests, after a response is received from the origin or cache

General guidance is provided in the developer guide, to help you choose a [email protected] trigger, based on what you want to do. In addition, the following questions can help you decide which [email protected] trigger to use:

  • Do you want your function to be executed on a cache miss? Use origin triggers.
  • Do you want your function to be executed on all requests? Use viewer triggers.
  • Do you want to modify a cache key (URL, cookies, headers, query string)? Use a viewer request trigger.
  • Do you want to modify the response without caching the result? Use a viewer response trigger.
  • Do you want to dynamically select the origin? Use an origin request trigger.
  • Do you want to rewrite a URL to the origin? Use an origin request trigger.
  • Do you want to generate responses that will not be cached? Use a viewer request trigger.
  • Do you want to modify the response before it’s cached? Use an origin response trigger.
  • Do you want to generate a response that can be cached? Use an origin request trigger.

Optimize for cost efficiency

[email protected] is charged based on the following two factors:

  1. Number of requests. Currently (at the time of this blog post), the cost is $0.60 per 1M requests.
  2. Function duration. Currently (at the time of this blog post), the cost is $0.00005001 for every GB-second used. For example, if you allocate 128MB of memory to be available per execution with your [email protected] function, then your duration charge will be $0.00000625125 for every 128MB-second used. Note that [email protected] functions are metered at a granularity of 50ms.

Please refer to our pricing guide for current prices and several [email protected] pricing examples. To help reduce the cost of using [email protected], follow these suggestions to make sure you invoke functions only when needed and optimize how resources are allocated.

First, optimize function invocation by triggering [email protected] on the most specific CloudFront behaviour. For example, in this solution where [email protected] is used to authorize viewers, the [email protected] function is triggered only for private content. In this use case, the origin’s private content is identified by specifying a “private/*” path pattern in a CloudFront cache behavior.

Next, choose the right trigger. Some [email protected] logic can be implemented by using either origin or viewer triggers, such as when you add an HSTS header on HTTP responses to viewers. In these scenarios, choose an origin trigger rather than a viewer trigger, to optimize [email protected] invocation and leverage the CloudFront cache.

Finally, optimize function resource allocation. While resource allocation for viewer triggers is limited to 128MB, for origin triggers you can allocate up to 3008MB. Any increase in memory size results in an equivalent increase in the CPU available, which can be crucial to optimizing your function’s execution time. You need to pick the best memory size configuration to balance these factors, depending on what your logic requires and your budget.

Optimize for performance

[email protected] functions execute across AWS locations globally on the CloudFront network. When a viewer request hits an edge location, the request is terminated at the edge, and then [email protected] executes the function at an AWS location close to the viewer.

When you compare using a CloudFront distribution with and without using [email protected], the latency perceived by viewers is different. This difference depends on several factors, including the CloudFront distribution configuration, trigger type, edge location, function code, and application logic. Here are some examples:

  • Consider an origin in the us-east-1 Region with a Lambda function behind an API Gateway. The application dynamically generates 3xx redirects for global viewers with an average first byte latency (FBL) of 260 ms (160 ms network FBL to us-east1 Region + 100ms origin FBL). When redirection logic is moved to a [email protected] function, the average application FBL drops to 110 ms (80 ms CloudFront FBL + 30 ms [email protected] invocation time on viewer request trigger).
  • Consider the delivery of static html files on CloudFront with a cache hit ratio of 95%, where [email protected] is used to add HTTP security headers. When [email protected] is configured to only execute on cache misses, the average FBL increases by 0.5 ms (5% x 10 ms invocation time on origin response trigger).

The [email protected] Service team is constantly improving the performance of the service, so the latency figures above will evolve over time.

For each use case, you can improve your viewers’ experience by optimizing your implementation of [email protected] To do this, explore ways to reduce the [email protected] function execution time and make sure your function executes within the functional and scaling limits set by the service.

First, reduce function execution duration by doing the following:

  • Optimize your function code for performance. For example, reuse the execution context to limit the re-initialization of variables and objects on every invocation. This is especially important if you have an externalized configuration that your [email protected] code retrieves, stores, and references locally. Instead, consider if you can use a static initialization or constructor, global, static variables, and singletons.
  • Optimize the external network calls your function uses. For example, enable TCP Keep Alive and reuse connections (to HTTP, databases, and so on) that you established during previous invocations. In addition, when possible, make network calls to resources in the same region where your [email protected] function is executing to reduce network latency. One way you can do this is by using DynamoDB global tables. Another recommendation is to make an external request to only the resources that you need in your function. For example, you can use query filters in Aurora or S3 Select. Also, if an external variable that you request doesn’t change often, doesn’t vary for different viewers, and doesn’t require immediate propagation, consider using a constant in your code and only update your function when the variable changes.
  • Optimize your deployment package. For example, avoid dependencies on external packages for simple functions that you can write yourself. When you need to use an external resource, choose lightweight packages. In addition, use tools like minify and browserfy to compact your deployment package.

Second, pay attention to the functional and scaling limits of [email protected], and proactively request a limit increase if you need it.

To illustrate how you can estimate the limits your function needs, consider the following example. Suppose that you are delivering static images with CloudFront at a rate of 5000 requests per second (RPS) and a cache hit ratio of 90%, and that you are using a [email protected] function with an origin response trigger to add HTTP security headers.

[email protected] will be invoked at rate of 10% x 5000 RPS = 500 RPS. Because this is a simple function, we can estimate an average execution time of 1 ms. To calculate the number of steady-state concurrent executions, add 10 ms to the average execution time and multiply it by the RPS we just calculated. In our example, the calculation is 500 RPS x (10 ms + 1 ms) = 5.5 which is rounded up to 6 concurrent executions. This is well below the default limit of 1000 concurrent executions per account per region.

Please note that if your traffic profile requires [email protected] functions to burst in a few seconds to hundreds of concurrent executions, you must take into consideration some additional factors. During sudden bursts, [email protected] immediately increases your concurrently executing functions by a predetermined amount, and if it’s not sufficient to accommodate the traffic surge, [email protected] will continue to increase the number of concurrent function executions by 500 per minute in each region until your account safety limit has been reached or the number of concurrently executing functions is sufficient to successfully process the increased load. Because of this automatic scaling, during the first minute of your traffic surge, [email protected]’s concurrent execution is limited to that predetermined amount. Additionally, when scaling out, cold starts increase function execution times up to orders of magnitude over simple functions.

Conclusion

By using CloudFront and [email protected], together with other AWS services like DynamoDB global tables, you can start building high-performing distributed serverless web applications for your use cases. In this blog post, I shared several common [email protected] use cases, and recommended some best practices to improve the performance of your [email protected] implementation, while making sure it fits in your budget. In the next blog post in this series, I’ll explain straightforward ways to develop and test [email protected] functions, and how to integrate [email protected] in your CI/CD pipeline.

相關推薦

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84c8e5e9e6e0e5c4c1e0e3e1">[email&#160;protected]a> Design Best Practices

This blog post is the first in a series about [email protected] best practices to help you optimize using [email protected] throughout t

shell腳本中的$# $0 <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f8dcb8">[email&#160;protected]a> $* $$ $! $?的意義

腳本 $* width 上一個 pre shell int .cn height 轉載自:http://www.cnblogs.com/davygeek/p/5670212.html 今天學寫腳本遇到一些變量不認識,在此做下記錄。 變量 含義 $0 當前腳本的文件

shell中$*與<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b296f2">[email&#160;protected]a>的區別

劃分 位置 一個 這也 差異 獨立 [email protected] 情況 雙引號 $*所有的位置參數,被作為一個單詞 註意:"$*"必須被""引用 [email protected] 與$*同義,但是每個參數都是一個獨立的""引用字串,這就意味著參數

Spring4.0系列<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aa9f87eae9c5c4cec3dec3c5c4cbc6">[email&#160;protected]a>

one window 標識 cto ace ted ada bsp 布爾 這篇文章介紹Spring 4的@Conditional註解。在Spring的早期版本你可以通過以下方法來處理條件問題: 3.1之前的版本,使用Spring Expression Langua

Spring高級話題<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b29ff2f7dcd3d0ded7">[email&#160;protected]a>***註解的工作原理

sso metadata bool logs tcl task ota -c ann 出自:http://blog.csdn.net/qq_26525215 @EnableAspectJAutoProxy @EnableAspectJAutoProxy註解 激活Aspe

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="297a595b40474e69685c5d465e405b4c4d">[email&#160;protected]a>註解與自動裝配(轉發)

配置 調用方法 support autowired 信息 ann over 反射機制 test 1 配置文件的方法我們編寫spring 框架的代碼時候。一直遵循是這樣一個規則:所有在spring中註入的bean 都建議定義成私有的域變量。並且要配套寫上 get 和 se

linux bash Shell特殊變數:Shell $0, $#, $*, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8aaeca">[email&#160;protected]a>, $?

在linux下配置shell引數說明 前面已經講到,變數名只能包含數字、字母和下劃線,因為某些包含其他字元的變數有特殊含義,這樣的變數被稱為特殊變數。  例如,$ 表示當前Shell程序的ID,即pid,看下面的程式碼: [[email protected] /]$ ec

spring <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="62000d0d16222103010a0703000e07">[email&#160;protected]a>中value的理解

先看原始碼 /** * Names of the caches in which method invocation results are stored. * <p>Names may be used to determine the target cache (or cac

{<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="733e3c3f3f2a342136363d203323213c273c3d3e323a3f5d303c3e">[email&#160;protecte

近日,復旦解密安全團隊發現GandCrab4.0活躍度提升,跟蹤到多起GandCrab4.0變種勒索事件,現釋出安全預警,提醒廣大使用者預防GandCrab4.0勒索。 目前復旦解密已經可以成功解密GandCrab4.0變種採用RSA+AES加密演算法 mg中毒檔案可以在一個小時解決.電話151691214

Springboot註解<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="260b0b666549485254494a4a4354">[email&#160;protected]a>和@RestCon

1.使用@Controller 註解,在對應的方法上,檢視解析器可以解析return 的jsp,html頁面,並且跳轉到相應頁面;若返回json等內容到頁面,則需要加@ResponseBody註解 [email protected]註解,相當於@[email protected

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5b2c3e391b33">[email&#160;protected]a>,c小總結

問題0:元素內聯元素,行內元素,行內塊元素.         內聯: 寬高M,P都有效         行內元素:無寬高,內容撐開,M,P左右有效  

SQL Server資料庫mdf檔案中了勒索病毒<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc9f8e858c889998a39d8f9d9293bc9f939f97">[email&#160;p

SQL,資料庫,勒索病毒,mdf檔案中毒,[email protected]_email *SQL Server資料庫mdf檔案中了勒索病毒[email protected]_email。副檔名變為[email protected]_email SQL Serv

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5400313a273b2632383b2379142032">[email&#160;protected]a>_export詳解

Tensorflow經常看到定義的函式前面加了“@tf_export”。例如,tensorflow/python/platform/app.py中有: @tf_export('app.run') def run(main=None, argv=None): """Runs the progr

手把手教你搭建React Native 開發環境 - ios篇 (React <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eda38c99849b88adddc3d8d8c3d9">[email&#

由於之前我是h5的,沒接觸過ios和安卓, 也不瞭解xcode配置,所以 建議學reace-native之前還是先去了解一下ios和安卓開發環境搭建等問題。 環境下載及配置 nodejs:https://nodejs.org/en/download/ 設定淘寶映象 $ npm con

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4978382833093e3a3179797878">[email&#160;protected]a>

function changeSpan(){         var f = document.getElementById("file1").files;         &nb

SpringBoot學習<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7e8f7e7c5d8c7d2c5c3cee4d8c2c5d4d2">[email&#160;protected]a>&am

文章目錄 @PropertySource:載入指定的配置檔案 @ImportResource:匯入Spring的配置檔案,讓配置檔案裡面的內容生效; @Bean @PropertySource:載入指定的配置檔案

eclipse支援@<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95d2f0e1e1f0e7d5c6f0e1e1f0e7">[email&#160;protected]a>註解使用 -轉載

1. 下載lombok.jar 2.將下載的lombok.jar放在你的eclipse安裝目錄下,如圖: 3.修改eclipse.ini檔案,新增如下兩行配置:   -Xbootclasspath/a:lombok.jar -javaage

無法解析的外部符號 <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e41497770537f77705e2f28">[email&#160;protected]a>,該符號在函式 ___tmai

#include using namespace std; int main() { cout <<“This is a C++ program.”; return 0; } 1>------ 已啟動生成: 專案: hello1, 配置: Debug Win32 ---

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ce9eb7baa6a1a08ea4afb8af">[email&#160;protected]a>@C 比較

對所有的程式語言,他們的最後的目的其實就是兩種:提高硬體的執行效率和提高程式設計師的開發效率。 遺憾的是,這兩點是不可能並存的!你只能選一樣。在提高硬體的執行效率這一方面,C語言沒有競爭者!舉個簡單的例子,實現一個列表,C語言用陣列int a[3],經過編譯以後變成了(基地址+偏移量)的方式。對

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="762506041f18113b203529363b1912131a370202041f14030213">[email&#160;protected]<

有 @ModelAttribute 標記的方法, 會在每個目標方法執行之前被 SpringMVC 呼叫 <form action="springmvc/TestModelAttribute" method="post"> 使用者名稱<input