AWS TCET

Learn/Architecture

Architecture · 15 min read · August 2026

Compute Paths: EC2, Lambda, and When to Choose Which

Always-on virtual machines versus event-driven functions, using the same decision language AWS uses in its compute docs.

Source. Amazon EC2 User Guide · AWS Lambda Developer Guide · Compute decision guidance

Abstract & theoretical context

EC2 gives you a virtual server you patch, size, and keep running. Lambda runs your function in response to events, bills duration, and hides the instance. AWS positions EC2 for long-running processes, custom kernels, and sticky servers; Lambda for short, stateless handlers behind API Gateway, S3, or EventBridge. Campus projects usually start on Lambda for APIs and EC2 only when they need a persistent GPU, a daemon, or software AWS does not package as a runtime. This note is the chapter's compute chooser, grounded in official service characteristics — not vendor slogans.

Models, formulas & variables

  1. 1. EC2 cost sketch

    cost ≈ instance_hours × (on-demand | reserved | spot price) + EBS + data transfer

    • — Stopped instances still pay for EBS. Terminated instances do not.
    • — Spot can reclaim capacity; do not put the only copy of state on Spot without a plan.
  2. 2. Lambda cost sketch

    cost ≈ requests × price_per_request + GB-seconds × memory_setting

    • — Timeout max is 15 minutes. Cold starts matter for spiky student traffic.
    • — Memory setting also scales CPU — raise memory before rewriting the algorithm.

Reference implementation

Copy into a sandbox account. Pin Region ap-south-1 unless the lab says otherwise.

handler.py

AWS Lambda · Python 3.12

import json

def lambda_handler(event, context):
    name = (event.get("queryStringParameters") or {}).get("name", "builder")
    return {
        "statusCode": 200,
        "headers": {"Content-Type": "application/json"},
        "body": json.dumps({"ok": True, "hello": name, "requestId": context.aws_request_id}),
    }

Lab procedure

  1. 01From the EC2 console, note instance family, vCPU, and network performance — do not pick t2 leftover types by habit.
  2. 02Create a Lambda with the handler above, 128 MB memory, 5s timeout, and a dedicated execution role.
  3. 03Invoke with a test event and read CloudWatch Logs. Confirm you did not use the root account.
  4. 04Write a one-line decision: persistent process → EC2 (or ECS/Fargate); HTTP burst → Lambda.
  5. 05Add a budget alarm before any 24/7 instance is left running after the lab.

Key insights

  • Lambda is not cheaper if you keep it warm 24/7 with huge memory — measure.
  • EC2 in one AZ is not highly available. Pair with an ALB and a second AZ when you outgrow a demo.
  • Fargate sits between them: containers without SSH, still longer-running than Lambda.

Account & lab requirements

IAM permission for lambda:CreateFunction and ec2:RunInstances in a sandbox. Stop or terminate lab instances the same day.

More in Architecture