Choosing the Optimal Memory Size - Serverless Architectures with AWS Lambda

Choosing the Optimal Memory Size

Lambda provides a single dial to turn up and down the amount of compute resources available to your function—the amount of RAM allocated to your function. The amount of allocated RAM also impacts the amount of CPU time and network bandwidth your function receives. Simply choosing the smallest resource amount that runs your function adequately fast is an anti-pattern. Because Lambda is billed in 100-ms increments, this strategy might not only add latency to your application, it might even be more expensive overall if the added latency outweighs the resource cost savings.

We recommend that you test your Lambda function at each of the available resource levels to determine what the optimal level of price/performance is for your application. You’ll discover that the performance of your function should improve logarithmically as resource levels are increased. The logic you’re executing will define the lower bound for function execution time. There will also be a resource threshold where any additional RAM/CPU/bandwidth available to your function no longer provides any substantial performance gain. However, pricing increases linearly as the resource levels increase in Lambda. Your tests should find where the logarithmic function bends to choose the optimal configuration for your function.

The following graph shows how the ideal memory allocation to an example function can allow for both better cost and lower latency. Here, the additional compute cost per 100 ms for using 512 MB over the lower memory options is outweighed by the amount of latency reduced in the function by allocating more resources. But after 512 MB, the performance gains are diminished for this particular function’s logic, so the additional cost per 100 ms now drives the total cost higher. This leaves 512 MB as the optimal choice for minimizing total cost.

Choosing the optimal Lambda function memory size

Figure 4: Choosing the optimal Lambda function memory size

The memory usage for your function is determined per invocation and can be viewed in CloudWatch Logs. On each invocation a REPORT: entry is made, as shown below.

REPORT RequestId: 3604209a-e9a3-11e6-939a-754dd98c7be3 Duration: 12.34 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 18 MB

By analyzing the Max Memory Used field, you can determine if your function needs more memory or if you over-provisioned your function's memory size.