serverless-nextjs / serverless-next.js

⚡ Deploy your Next.js apps on AWS Lambda@Edge via Serverless Components
MIT License
4.47k stars 457 forks source link

Any advantages or disadvantages serving NextJS app with Lambda over EC2. #561

Closed thevarunraja closed 4 years ago

thevarunraja commented 4 years ago

Thanks for the great work on this. I would like to know when to choose this approach of serving the app through Lambda@Edge over EC2. I tried to google for an answer but couldn't find any. Thanks in advance.

dphang commented 4 years ago

Hey @thevarunraja,

Generally the issues are used for feature requests / bug reports, though I guess there isn't any gitter (or similar) yet, so I'll answer this here.

You can search for Lambda vs. EC2 comparisons, I think there should be many. Lambda@Edge just means it replicates your Lambda function and deploys it to all of AWS's edge locations so that code runs closer to your user (instead of one region like normal Lambda). Here is one comparison of Lambda vs. EC2: https://lumigo.io/blog/aws-lambda-vs-ec2/, it mostly applies to Lambda@Edge as well. I've also summarized based on my experiences:

Advantages of Lambda@Edge:

Disadvantages of Lambda@Edge:

Advantages of EC2:

Disadvantages of EC2:

Note that Next.js apps strongly prefer using statically generated (SSG) pages over SSR pages. In which case, they will mostly be served by CloudFront caches and if it hits your Lambda (cache miss), it has very light logic to figure out which page to retrieve based on URL and retrieves it from S3 instead. In my experience, it is around 20-40 ms if cached and around 100-250 ms if uncached (I do live near an edge location).

If you have to SSR render a page, it will need to load all npm dependencies and will easily make the runtime close to a second or more.

So it depends: if most of your pages can be statically generated and you need very little / no SSR pages, then Lambda@Edge is a very good choice. Or if you have few users from many locations then it also works for saving some costs. If you need to SSR many or all pages, then it will probably be much slower than using EC2 (network savings won't offset this).

thevarunraja commented 4 years ago

Thanks for your awesome explanation. This is exactly what I am looking for. Thanks again