Lambda是否在内存中保留任何数据? [英] Does lambda persist any data in memory?

查看:42
本文介绍了Lambda是否在内存中保留任何数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在AWS lambda中具有以下代码:

 const cache = {};exports.handler =异步(事件)=>{//TODO工具如果(cache [event.key]){console.log('从缓存读取');返回缓存[event.key];}console.log('生成值');缓存[event.key] = Math.random()返回缓存[event.key];}; 

当我运行lambda时,我可以在日志上看到从缓存读取,这意味着lambda在缓存中缓存了一些值.lambda变热时是否会保留其记忆?这是否意味着我可以利用此内存进行一些缓存以提高性能?

解决方案

即使调用完成,Lambda容器仍保持活动状态.因此,在Lambda容器的整个生命周期中,加载到容器内存中的任何数据都将可用.

因此,此内存可用作缓存的杠杆.

如果您的应用程序是读取型的,则缓存中的数据将很有用.例如,在必须从数据库中获取相同的用户名的情况下,我们可以缓存该用户名以供将来调用.因此,减轻了数据库查询的成本.

上述方法似乎有帮助,但缺点也很少:

  1. 由于多次调用lambda而导致的不同lambda容器之间缺乏同步,这将导致在高速缓存中存储相同的数据以及许多已经存储的数据丢失.
  2. 如果缓存中的数据已增加到lambda处理所需的内存耗尽水平,则可能导致lambda完全停止工作.

I have below code in AWS lambda:


const cache = {};

exports.handler = async (event) => {
    // TODO implement
    if (cache[event.key]) {
        console.log('read from cache');
        return cache[event.key];
    }
    console.log('generate value');
    cache[event.key] = Math.random()
    
    return cache[event.key];
};

when I run the the lambda and I can see read from cache on the log which means the lambda cache some values in cache memory. Does the lambda persist its memory when it becomes warm? Does it mean I can make use of this memory for some caching in order to improve performance?

解决方案

Lambda container remains alive even after the invocation is complete. So, whatever data loaded in the container's memory will be available throughout the Lambda container lifecycle.

So, this memory can be used as leverage for caching.

Data in the cache would be useful if your application is read-extensive. For example in a case where the same username has to be fetched from Database, we can cache the username for future invocations. Thus, mitigating the cost of DB query.

Above approach seems to help but there are few downsides as well:

  1. The lack of synchronization between different lambda containers created by multiple invocations of the lambda would cause to store the same data and many misses of already store data in the cache.
  2. If the data in the cache has increased to a level of memory exhaustion needed for lambda for processing could cause to stop lambda working altogether.

这篇关于Lambda是否在内存中保留任何数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆