vercel 认为 LRU caching 对云函数来说不太适用,因为云函数实例冻结或销毁时,缓存也会被清空,而一个云函数实例往往只会运行很短一段时间,意味着缓存根本保存不了多久。
vercel 建议云函数使用在 header 的 Cache-Control
对 api 的响应进行缓存配置。
he's saying that LRU caching isn't a viable method for serverless due to them clearing their memory every few seconds when they freeze.
The only problem with this is that we shouldn't be storing data in memory, as the short life time of Lambda will quickly wipe it. For these cases, we suggest caching API responses using the s-maxage value in the Cache-Control header.
当然,如果用 Cache-Control
,那除非过期或手动清除,否则前端拿到的数据都不会变,而后端虽然用 lur,但后端可以根据需要更新数据,从而保证前端获得的数据是新的。另外 Cache-Control
似乎对 POST
请求不适用。
虽然 vercel 认为 LRU caching 对云函数来说不太适用,但是 nextjs 官方有一个例子使用 lru-cache 实现 api 的 rate limit:
Adds an example using lru-cache to implement a simple rate limiter for API routes。I'm going to update this to use Redis or something else persisted
rate limit 涉及 X-RateLimit-Limit、X-RateLimit-Remaining 这两个 header。