Compute options

Mid-level Always asked 7 min

On this page

The question

VMs, managed containers, managed Kubernetes or functions. How do you choose?

30-second answer

By how much I must control against how much I want to operate. VMs (virtual machines) give a full OS and bill every hour, with patching and scaling on me. Managed Kubernetes runs the control plane, but workloads, node pools and upgrades stay mine; it pays off for many services and a platform team. Managed containers, such as Cloud Run, take an image and scale it, even to zero. Functions run code per event, idle for free, within hard limits. I pick the most managed option the workload fits.

Understand it

Four compute options

Compare

Virtual machines: any OS, agent or kernel setting you like, and all the patching and scaling that comes with it. You pay for every hour, busy or idle.

View as text

Five facts per option, what you ship, what you run, how it scales, its cold start and what it bills for, above three gauges from 0 to 4: control, operations work and idle cost.

VMs: ships a VM image or a jar, scales minutes, a VM at a time. Control 4, ops work 4, idle cost 4 out of 4. Virtual machines: any OS, agent or kernel setting you like, and all the patching and scaling that comes with it. You pay for every hour, busy or idle.

Kubernetes: ships images + manifests, scales seconds per Pod. Control 3, ops work 3, idle cost 3 out of 4. Managed Kubernetes: the provider runs the control plane; you run the workloads, node pools and upgrades. One platform for many services, worth it when a team can own it.

Containers: ships a container image, scales seconds, to zero. Control 2, ops work 1, idle cost 1 out of 4. Managed containers, such as Cloud Run: give it an image and get a URL that scales with requests, even to zero. No nodes, no cluster, fewer knobs.

Functions: ships function code, scales per event, to zero. Control 1, ops work 1, idle cost 0 out of 4. Functions: code that runs per event, with nothing to pay while idle. The price is limits: run time caps, cold starts that hit the JVM hardest, and provider-specific triggers.

Five facts per option, what you ship, what you run, how it scales, its cold start and what it bills for, above three gauges from 0 to 4: control, operations work and idle cost.

VMs: ships a VM image or a jar, scales minutes, a VM at a time. Control 4, ops work 4, idle cost 4 out of 4. Virtual machines: any OS, agent or kernel setting you like, and all the patching and scaling that comes with it. You pay for every hour, busy or idle.

Kubernetes: ships images + manifests, scales seconds per Pod. Control 3, ops work 3, idle cost 3 out of 4. Managed Kubernetes: the provider runs the control plane; you run the workloads, node pools and upgrades. One platform for many services, worth it when a team can own it.

Containers: ships a container image, scales seconds, to zero. Control 2, ops work 1, idle cost 1 out of 4. Managed containers, such as Cloud Run: give it an image and get a URL that scales with requests, even to zero. No nodes, no cluster, fewer knobs.

Functions: ships function code, scales per event, to zero. Control 1, ops work 1, idle cost 0 out of 4. Functions: code that runs per event, with nothing to pay while idle. The price is limits: run time caps, cold starts that hit the JVM hardest, and provider-specific triggers.

Takeaway: From VMs to functions, each step trades control for less operations work and lower idle cost. Pick the highest step whose limits your workload can live with.

Pick the compute option for each workload

Build

Four workloads need a home. Give each the compute option that fits it, with the reason.

Drag a piece, or select it and then select a place.

  1. Empty
  2. Empty
  3. Empty
  4. Empty
View as text

Four rows, one per workload, each with an empty slot for the compute option that fits it. Four workloads need a home. Give each the compute option that fits it, with the reason.

Thumbnail per uploaded photo, spiky: Functions: per event, idle is free. Legacy app with a host-level agent: VMs: full control of the OS. 40 services, a platform team: Kubernetes: one platform for all. One Spring Boot API, team of three: Containers: image in, URL out.

Climb as high as the workload allows: functions for short events, managed containers by default, Kubernetes when a team runs a platform, VMs when you need the OS.

Four rows, one per workload, each with an empty slot for the compute option that fits it. Four workloads need a home. Give each the compute option that fits it, with the reason.

Thumbnail per uploaded photo, spiky: Functions: per event, idle is free. Legacy app with a host-level agent: VMs: full control of the OS. 40 services, a platform team: Kubernetes: one platform for all. One Spring Boot API, team of three: Containers: image in, URL out.

Climb as high as the workload allows: functions for short events, managed containers by default, Kubernetes when a team runs a platform, VMs when you need the OS.

Takeaway: Start from the least you must manage: functions for short, spiky events, managed containers for a typical service, managed Kubernetes for many services and a platform team, VMs only for OS-level needs.

Which compute option, asking what you must control from the topIf the workload needs a custom OS, kernel setting or host agent, use virtual machines. Otherwise, if it is short and event-driven, under the function time limit, use functions. Otherwise, if many services share a platform team, use managed Kubernetes. Otherwise use managed containers.yesnoyesnoyesnoNeeds its own OS,kernel or host agent?Virtual machinesShort andevent-driven,under the time limit?FunctionsMany services anda platform team?ManagedKubernetesManaged containers
Which compute option, asking what you must control from the topIf the workload needs a custom OS, kernel setting or host agent, use virtual machines. Otherwise, if it is short and event-driven, under the function time limit, use functions. Otherwise, if many services share a platform team, use managed Kubernetes. Otherwise use managed containers.yesnoyesnoyesnoNeeds its own OS,kernel or host agent?Virtual machinesShort andevent-driven,under the time limit?FunctionsMany services anda platform team?ManagedKubernetesManaged containers
Which compute option? Ask what you must control, from the top
OptionAWS (Amazon Web Services)AzureGCP (Google Cloud Platform)
Virtual machinesEC2 (Elastic Compute Cloud)Virtual MachinesCompute Engine
Managed containersECS (Elastic Container Service) on Fargate, App RunnerContainer AppsCloud Run
Managed KubernetesEKS (Elastic Kubernetes Service)AKS (Azure Kubernetes Service)GKE (Google Kubernetes Engine)
FunctionsLambdaAzure FunctionsCloud Run functions

In code

gcloud run deploy orders \
  --image europe-docker.pkg.dev/acme/apps/orders:1.4.2 \
  --region europe-west1 \
  --cpu 1 --memory 1Gi \
  --concurrency 80 \
  --min-instances 0 --max-instances 20 \
  --set-env-vars SPRING_PROFILES_ACTIVE=prod
# Service URL: https://orders-<hash>-ew.a.run.app
Managed containers: one command turns an image into a URL that scales to zero
# eksctl create cluster -f shop.yaml
apiVersion: eksctl.io/v1alpha5
kind: ClusterConfig
metadata:
  name: shop
  region: eu-west-1
  version: "1.31"
managedNodeGroups:
  - name: general
    instanceType: m7g.large
    minSize: 3
    maxSize: 12
    availabilityZones: [eu-west-1a, eu-west-1b, eu-west-1c]
Managed Kubernetes: the control plane is the provider's, the node groups are still yours
# Cloud Run, App Service and similar platforms pass the port in an environment variable
server.port=${PORT:8080}
# Scaling in sends SIGTERM, then kills the instance about 10 s later on Cloud Run
server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=8s
On a platform that scales instances in and out, listen where it says and stop cleanly
// Wrong: every invocation builds a client, its connection pool and its credential lookup again
public String handleRequest(S3Event event, Context ctx) {
 Wrong     S3Client s3 = S3Client.create();
    return resize(s3, event);
}

// Right: built once during init, on the cold start, and reused while the environment stays warm
 Right private static final S3Client S3_CLIENT = S3Client.builder()
 Right         .httpClient(UrlConnectionHttpClient.create())
 Right         .build();

public String handleRequest(S3Event event, Context ctx) {
    return resize(S3_CLIENT, event);
}
Functions: build expensive clients once per execution environment, not once per call
A cold start and a warm start of the same functionThe first event finds no ready execution environment, so the platform creates one, starts the JVM and runs the static initialization before the handler, which can take seconds for Java. A second event a moment later reuses the warm environment and only runs the handler, in milliseconds.Execution environmentPlatformEvent sourceevent 1create environment, start JVMstatic init: clients, confighandler result (cold: seconds)event 2, a moment laterreuse the warm environmenthandler result (warm: milliseconds)
A cold start and a warm start of the same functionThe first event finds no ready execution environment, so the platform creates one, starts the JVM and runs the static initialization before the handler, which can take seconds for Java. A second event a moment later reuses the warm environment and only runs the handler, in milliseconds.Execution environmentPlatformEvent sourceevent 1create environment, start JVMstatic init: clients, confighandler result (cold: seconds)event 2, a moment laterreuse the warm environmenthandler result (warm: milliseconds)
A cold start and a warm start of the same function

Solve it

A Java function’s first request takes 6 seconds. Fix the cold start

An order-export function on AWS Lambda, written with Spring Cloud Function on Java 21 with 512 MB of memory, answers warm requests in 40 ms, but after every quiet period the first request takes about 6 seconds and the caller’s 5-second timeout fails it. Explain the cause and choose a fix, with its cost.

  1. Measure where the time goes. The Lambda REPORT log line shows an Init Duration of about 5.5 s: the time to start the JVM (Java Virtual Machine), load classes and build the Spring context before the handler runs once.
  2. Take the free wins. More memory also means more CPU, so 2,048 MB often halves init. Drop unused starters, and stop the JIT (just-in-time) compiler at tier 1 with JAVA_TOOL_OPTIONS, which suits short-lived code.
  3. Snapshot the initialized environment. SnapStart runs init once per published version and restores a snapshot on a cold start, cutting it to well under a second. Re-create anything that must be unique, such as random seeds, after restore.
  4. Compare the paid alternatives. Provisioned concurrency keeps environments warm but bills all day. A managed container with one minimum instance costs the same idea in another form. GraalVM native image is fastest, with a harder build.
  5. Check. Invoke after 30 idle minutes and read Restore Duration instead of Init Duration; alert on p99 latency against the 5-second timeout, not on the average.
Resources:
  OrderExportFunction:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: java21
      Handler: org.springframework.cloud.function.adapter.aws.FunctionInvoker::handleRequest
      MemorySize: 2048
      Timeout: 30
      AutoPublishAlias: live
      SnapStart:
        ApplyOn: PublishedVersions
      Environment:
        Variables:
          JAVA_TOOL_OPTIONS: -XX:+TieredCompilation -XX:TieredStopAtLevel=1
          SPRING_CLOUD_FUNCTION_DEFINITION: exportOrders
AWS SAM (Serverless Application Model): more memory, tier-1 JIT and SnapStart on published versions

How to answer

  • Name the trade-off, control against operations work and idle cost.
  • Map each option to a product, such as EC2 (Elastic Compute Cloud), Cloud Run, EKS (Elastic Kubernetes Service) and Lambda.
  • Containers are the portable middle; the same image runs on Cloud Run, Kubernetes or a VM.
  • State function limits, such as a 15-minute cap on Lambda, cold starts and payload size.

Common mistakes

  • Choosing Kubernetes for one small service because it is the industry standard.
  • Claiming functions are always cheaper, without asking about steady load.

Follow-up questions

What is a cold start, and why does it hurt Java the most?

A cold start is the delay when a request finds no ready instance, so the platform must create one: start a micro-VM or container, start the runtime, and run the app's initialization before the handler. It happens on scale-out and after idle periods with scale to zero. The JVM (Java Virtual Machine) adds class loading and interpreted code before the JIT warms up, and frameworks such as Spring build a context at startup, so seconds are common.

  • Warm requests reuse the environment and skip all of it.
  • Fixes are snapshots such as SnapStart, native images, lighter frameworks, more memory or a minimum warm instance.
  • Measure the p99, because the average hides cold starts.

See it in the infographic: Four compute options

Which workloads fit functions badly?

Long-running jobs past the time cap, 15 minutes on Lambda; steady high traffic, where per-call billing costs more than containers; latency-critical paths that cannot absorb cold starts; work needing local state, large memory, GPUs or long-lived connections such as WebSockets; and high-concurrency calls into a relational database, where each copy opens its own connections and exhausts the pool. They fit short, stateless, event-driven and spiky work.

  • Put a connection proxy, such as RDS (Relational Database Service) Proxy, between many function copies and a database.
  • Split long jobs into steps, or run them as container jobs.
  • Watch fan-out costs, since retries and recursive triggers multiply invocations.

See it in the infographic: Pick the compute option for each workload

How does managed Kubernetes differ from a managed container service such as Cloud Run or Fargate?

Both run your container images. Managed Kubernetes gives the full Kubernetes API: you write manifests, run controllers and operators, manage node pools or pay for an autopilot mode, plan version upgrades and own the security of what runs on the cluster. A managed container service hides the cluster: you deploy an image with a few settings, such as CPU, memory, concurrency and scaling limits, and the provider runs everything else. Less flexibility, far less to operate.

  • Kubernetes wins on ecosystem, portability and fine control over scheduling and networking.
  • Managed containers win on time to production and operations cost for few services.
  • Both bill differently, nodes against CPU-seconds, so compare at your real load.

See it in the infographic: Four compute options

A Spring Boot function on Lambda takes 6 seconds on its first request. What do you try, in order?

First measure Init Duration in the REPORT log. Then the cheap fixes: more memory, since it also buys CPU; fewer dependencies and lazy initialization; tier-1 JIT through JAVA_TOOL_OPTIONS; clients built once in static fields. Then SnapStart, which restores an initialized snapshot in well under a second. If that is not enough, provisioned concurrency, a container with a warm minimum instance, or a GraalVM native image, each with its own cost.

  • Measure before changing anything, and track p99 after each change.
  • SnapStart needs published versions and care with uniqueness after restore.
  • Provisioned concurrency removes cold starts but bills for idle capacity.

See it in the infographic: Four compute options

How do the four compute options bill you, and how does that change the design?

VMs bill per second or hour while running, whatever the load, so you right-size, autoscale and reserve capacity for the baseline. Managed Kubernetes bills its nodes plus a control plane fee, so bin-packing Pods onto fewer nodes matters. Managed containers bill CPU and memory per second of request handling, often scaling to zero. Functions bill per invocation and per millisecond of memory, so idle is free but every retry and every slow dependency costs money.

  • Steady load favors reserved or committed capacity; spiky load favors pay per use.
  • Egress, load balancers and logs can cost more than the compute itself.
  • Tag resources and review the bill per service; cost is a design input.

See it in the infographic: Four compute options

Your API serves 2,000 requests a second all day. Functions or containers?

Containers. Under steady high load a function bills for every call and every millisecond, and each concurrent request needs its own execution environment, while a container serves many requests at once on capacity you pay for anyway. Functions win on spiky or low traffic; at constant load, reserved or right-sized containers usually cost several times less.

When is managed Kubernetes worth its complexity?

When you run many services, need its ecosystem, such as operators, service meshes or GitOps, want the same platform across clouds or on-premises, and have people to own upgrades and security. For a handful of services, managed containers deliver the same deploys and autoscaling without a cluster to run.

Check yourself

1. A nightly report takes about 40 minutes to generate. Which option is the poor fit?
Show answers
  • AWS Lambda functions: Correct. Lambda stops an invocation at 15 minutes.
  • A managed container job, such as Cloud Run jobs: Incorrect. Container jobs run for hours and bill only while running.
  • A scheduled VM that starts, runs the report and stops: Incorrect. It works, with more setup; nothing caps its run time.
2. Which two options can scale to zero and cost almost nothing while no requests arrive?
Show answers
  • Managed containers and functions: Correct. Both bill for use and can run no instance at all when idle.
  • VMs and managed Kubernetes: Incorrect. Running VMs and cluster nodes bill every hour, idle or not.
  • Managed Kubernetes and functions: Incorrect. A cluster keeps its nodes and control plane fee while idle.
3. A Lambda handler creates a new database connection pool inside handleRequest on every call. What is the main effect?
Show answers
  • Every call pays the setup cost, and the database runs out of connections under load: Correct. Init work belongs in static fields, reused while the environment is warm.
  • None; Lambda caches the pool between calls automatically: Incorrect. Only objects kept outside the handler survive between calls.
  • Only the first call is slower: Incorrect. Code inside the handler runs on every call, warm or cold.