MervCodes

Tech Reviews From A Programmer

AWS Lambda vs EC2: When to Use Serverless vs Traditional Servers

1 min read

AWS Lambda vs EC2: When to Use Serverless vs Traditional Servers

I've gotten this wrong before. Built an entire system on Lambda, hit the 15-minute timeout wall on a critical batch job, and had to migrate part of it to EC2 mid-sprint. The reverse has happened too — running EC2 instances 24/7 for a service that got maybe 50 requests a day and burning money for nothing.

The Lambda vs EC2 decision is one of those choices that seems simple on the surface but has real downstream consequences. Here's the framework I use now to avoid making the same mistakes.


What We're Actually Comparing

AWS Lambda is function-as-a-service. Upload code, define a trigger, and AWS handles everything else — servers, scaling, patching. You pay per invocation and per millisecond of execution. Zero traffic = zero cost.

Amazon EC2 is virtual machine hosting. You pick an instance type, boot it up, and you've got a full server. It runs until you stop it, and you pay by the hour or second regardless of whether anyone's using it.

The difference is fundamental — it's a different relationship with infrastructure.


The Core Tradeoff

Lambda trades control for convenience. EC2 trades convenience for control.

With Lambda, you can't:

  • Run anything longer than 15 minutes
  • Keep persistent in-memory state between invocations
  • Listen on arbitrary ports
  • Install custom OS packages or kernel modules
  • Use more than 10GB memory or 512MB-10GB ephemeral disk

With EC2, you can do all of that — but you also own OS updates, security patches, capacity planning, auto-scaling config, load balancers, and monitoring. None of that is free in time or money.


When Lambda Wins

Event-Driven Workloads

Lambda was literally built for this. HTTP request, S3 upload, SQS message, DynamoDB stream — something happens, your function runs, it terminates. No wasted compute.

Classic example: user uploads a photo to S3, Lambda resizes it into thumbnails, writes them back. Happens thousands of times a day or zero times a day. You pay proportionally.

Bursty or Unpredictable Traffic

If your traffic has sharp peaks and long quiet periods, Lambda's pay-per-use model crushes EC2's always-on cost. Weekend reporting jobs, nightly syncs, APIs that spike on Monday mornings — Lambda territory.

Microservices

Paired with API Gateway or Lambda Function URLs, each service is independently deployable, scalable, and priced. Teams own their functions without coordinating shared infrastructure.

Quick Prototyping

No AMI to configure, no security group rabbit hole, no SSH keys. Write the function, deploy, done. For MVPs and internal tools, this speed matters a lot.

Low-Scale Cost

At low request volumes, Lambda is almost always cheaper. A t3.micro costs ~$8-10/month whether it handles 1 request or 1 million. Lambda's free tier covers 1M requests and 400K GB-seconds monthly. For side projects, Lambda is effectively free.


When EC2 Wins

Long-Running Processes

Lambda's 15-minute limit is a hard wall. Video transcoding, large ETL jobs, ML training, heavy batch processing — these need EC2 (or containers).

Persistent Connections

Databases, WebSocket servers, message brokers, game servers — anything requiring persistent connections or in-memory state. Lambda's stateless model is fundamentally incompatible.

Sustained High Traffic

Lambda has a crossover point. At high, steady request volumes, EC2 becomes cheaper. Rough rule: if your Lambda would run >60-70% of the time, EC2 is likely cheaper.

Concrete example: Lambda averaging 500ms at 100 req/sec = 50 concurrent executions running all day. A few EC2 instances behind a load balancer will cost less and give more predictable latency.

Specialized Hardware

GPUs, specific CPU architectures, high-memory instances — EC2 has hundreds of instance types. Lambda offers limited choices with no GPU support.

Legacy Applications

Lifting and shifting a monolithic Java app or WordPress site? EC2 is the pragmatic choice. Refactoring for Lambda often isn't worth the cost.

Compliance Requirements

Some regulated industries need specific OS configs, OS-level audit logging, or network architectures that are easier on EC2 with full control.


Cost Comparison

Scenario: 10M requests/month, 200ms average, 128MB memory.

Lambda:

  • Requests: 10M x $0.0000002 = $2.00
  • Compute: 10M x 0.2s x 128MB/1024 x $0.0000166667/GB-s = ~$4.17
  • Total: ~$6.17/month

EC2 (t3.small):

  • On-demand: ~$15/month
  • Reserved (1-year): ~$10/month

Lambda wins at this volume. Push to 100M requests and Lambda hits ~$62 while EC2 stays at $15. The crossover depends on your specific workload, but it typically lands between 20-80% sustained utilization.


The Hybrid Approach

In practice, most production systems use both:

  • Lambda for the API layer, webhooks, event processing, scheduled jobs
  • EC2/ECS for stateful services, databases, long-running workers, latency-sensitive compute

Use each where it shines.


Quick Decision Checklist

Question If Yes →
Task runs longer than 15 minutes? EC2
Traffic is bursty and unpredictable? Lambda
Need persistent in-memory state? EC2
Event-driven (S3, SQS, API call)? Lambda
Need GPU or specialized hardware? EC2
Sustained utilization above ~70%? EC2
Want zero infrastructure management? Lambda
Running a legacy monolith? EC2

FAQ

Can Lambda and EC2 talk to each other? Yes. Lambda can call EC2 services over the network, write to EC2-hosted databases, and trigger Auto Scaling. They're complementary.

Are cold starts a real problem? They're real but often overstated. 100-500ms on the first request for most workloads. Provisioned Concurrency eliminates them at extra cost. For background work, cold starts don't matter at all.

Is Lambda always faster to develop with? For simple stateless functions, yes. For complex apps with local testing needs and environment parity issues, not necessarily. SAM, Serverless Framework, and CDK help, but local Lambda dev still isn't as simple as running a server.

What about containers (ECS/Fargate)? Fargate is a solid middle ground — more control than Lambda, less ops than raw EC2. If Lambda's limits are too restrictive but you want to minimize infrastructure work, Fargate is worth serious consideration.

Should new projects default to Lambda? For greenfield with uncertain traffic: Lambda is a reasonable default for stateless, event-driven stuff. It defers infrastructure decisions until you have actual load. But don't force Lambda where it doesn't fit — a 30-minute batch job should just run on EC2.


Bottom Line

Lambda isn't an EC2 replacement — it's a different tool for a different job.

Choose Lambda for event-driven, short-lived, variable-traffic workloads. It saves money and eliminates ops overhead for the right use cases.

Choose EC2 when you need control, sustained compute, long-running processes, or specialized hardware.

When in doubt: sketch your traffic patterns, run the cost math, and remember that the best architecture is the one your team can actually operate reliably.

Sources

Related Articles