Skip to Content
Cloud Engineering Academy
3. .NET Application Development on AWS

Hosting options for .NET on AWS compared

Compare EC2 (Linux and Windows), Elastic Beanstalk, ECS on Fargate, ECS on EC2 and Managed Instances, EKS, Lambda and ECS Express Mode for .NET workloads on cost, operations, scaling, cold starts and compliance, and know why App Runner is no longer an option for new accounts.

intermediate⏱ 2 h 🟢 FreeSAA-C03DVA-C03

Assumes: .NET 10 LTS · Lambda dotnet10 · Elastic Beanstalk .NET 10 on Amazon Linux 2023 · Amazon ECS (Fargate, EC2, Managed Instances, Express Mode) · Amazon EKS · Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lesson you can:

  • Describe each AWS compute option for .NET: EC2 (Linux and Windows), Elastic Beanstalk, ECS on Fargate, ECS on EC2 and ECS Managed Instances, EKS, Lambda and ECS Express Mode. Say what you manage and what AWS manages for each.
  • Explain why App Runner is not an option for new accounts and what AWS recommends instead.
  • Compare the options on monthly cost, operational burden, scaling behaviour, cold starts, legacy .NET Framework support and compliance evidence, and use a small C# cost model to reason about the numbers.
  • Pick a host for a given Harbourline workload and defend the choice in an architecture decision record.
  • Build an ASP.NET Core app that runs unchanged on Beanstalk, in a container and on Lambda, as the module project does.

Prerequisites

Why this matters in banking

Harbourline's first AWS workload was a statements portal on six Windows EC2 instances, because "that's what we had on-prem". Two years later the team spent one day a month patching, rotated AMIs by hand, paid for Windows licences on servers that were idle 70% of the time, and still failed an audit finding about inconsistent patch levels.

The second team chose EKS for a single API because "Kubernetes is the standard". They paid for a control plane and a platform engineer's time to run something ECS would have done with far less effort.

The third team put a payments-initiation API on Lambda without measuring cold starts. The 99th-percentile latency at 07:00, when traffic arrived after a quiet night, breached the mobile app's timeout.

None of those choices was wrong in every situation. Each was wrong for that workload. Hosting decisions lock in cost, operating effort and failure modes for years. Regulators increasingly ask firms to show they understand the operational resilience of important business services. Your hosting choice, and the evidence for why you made it, is part of that story.

The idea in plain language

All options run the same .NET code. They differ in how much of the stack you look after and how you pay:

  • EC2 — you rent a virtual machine. You manage the OS, patching, scaling and deployment. You pay per second while it runs.
  • Elastic Beanstalk — you upload your app, and Beanstalk creates and configures EC2 instances, a load balancer and scaling for you. They are still real EC2 resources in your account, and you still pay for them.
  • ECS on Fargate — you give AWS a container image and a CPU/memory size. AWS runs it with no servers for you to see. You pay per second for the vCPU and memory you asked for.
  • ECS on EC2 / ECS Managed Instances — the same container orchestration, running on EC2 instances that you manage (classic) or that AWS manages for you (Managed Instances).
  • EKS — managed Kubernetes. Powerful and portable, with the most concepts to learn and run.
  • Lambda — you give AWS a function. AWS runs it only when a request or event arrives. You pay per request and per millisecond of execution.
  • ECS Express Mode — one command turns a container image into a load-balanced, auto-scaling HTTPS service on Fargate, with sensible defaults. It is the recommended replacement for App Runner.

Analogy: think of hosting like premises for a bank branch. EC2 is buying a building: total control, and you fix the roof. Beanstalk is a serviced office the landlord fits out to a standard plan, but the lease is in your name. Fargate is a desk in a managed co-working space: you bring your team (the container), they handle the building. EKS is running your own co-working company. Lambda is a meeting room booked by the minute, which takes a moment to unlock the first time each morning.

What problem each option solves

EC2 (Linux or Windows)

  • For: full control, unusual OS requirements, licensed software tied to hosts, lift-and-shift of IIS apps, long-running stateful processes.
  • You manage: OS and patching (use Systems Manager Patch Manager), AMIs, scaling (Auto Scaling groups), deployment (CodeDeploy or your pipeline), log shipping, hardening.
  • .NET notes: .NET 10 on Linux with Kestrel behind an ALB is cheaper than Windows, with no licence cost. Windows Server instances include the licence in the hourly price. Legacy .NET Framework 4.x apps need Windows (EC2 or Beanstalk Windows).
  • Sharp edges: patch drift, snowflake servers, idle cost. Use IMDSv2, SSM Session Manager instead of RDP/SSH, and immutable AMIs.

AWS Elastic Beanstalk

  • For: teams who want App Service-like simplicity on EC2, Windows/IIS apps, and quick lift-and-shift of ASP.NET apps without containers.
  • Platforms: .NET 10 on Amazon Linux 2023 (Kestrel behind nginx, with a platform branch per .NET major version), and Windows Server with IIS platforms for .NET Framework and .NET ⚠ VERIFY the current Windows Server versions offered.
  • You manage: application versions, environment configuration, platform updates (managed updates can apply them in a maintenance window).
  • It creates: EC2 instances, an Auto Scaling group, optionally an ALB, security groups and CloudWatch alarms. They are visible, and billed, in your account. Beanstalk itself has no additional charge.
  • Sharp edges: environment changes can replace instances; config drift between console edits and IaC; slower deployments than containers.

Amazon ECS on AWS Fargate

  • For: most new HTTP APIs and workers. It is Harbourline's default for container workloads.
  • You manage: the container image, task definition (CPU, memory, roles, environment), service (desired count, deployment settings) and the ALB.
  • AWS manages: servers, OS patching of the hosts, capacity.
  • Billing: per second, with a one-minute minimum for Linux, for the vCPU and memory requested. Graviton (arm64) is about 20% cheaper per vCPU-hour than x86. Windows containers are supported on ECS with Fargate at a higher price plus an OS licence fee per vCPU-hour, with a five-minute minimum.
  • Sharp edges: no host access for agents that need it; tasks in private subnets need a NAT gateway or VPC endpoints to reach ECR, CloudWatch and other AWS APIs.

Amazon ECS on EC2, and ECS Managed Instances

  • ECS on EC2 (Auto Scaling group capacity provider): you run the container instances yourself. It is cheaper at steady high utilisation, and needed for GPUs, specific instance types or daemons. You patch the instances.
  • ECS Managed Instances: a newer capacity provider type where ECS launches and manages EC2 instances for you, including patching and replacement, while you choose instance requirements and purchase options (On-Demand, Spot, Capacity Reservations). It sits between Fargate (no instances at all) and classic ECS on EC2 (you manage everything). Check the current pricing model on the ECS pricing page ⚠ VERIFY.

Amazon EKS (overview)

  • For: organisations that have standardised on Kubernetes, need its ecosystem (operators, service mesh, Helm charts), or run multi-cloud and on-premises clusters with one toolchain.
  • Billing: a control-plane charge per cluster-hour (USD 0.10 per hour in standard support, about USD 73 per month), plus the compute (EC2, Fargate or EKS Auto Mode).
  • Sharp edges: many more concepts (pods, deployments, ingress controllers, IRSA or Pod Identity, cluster upgrades every few months). For a single .NET API this is usually overhead without benefit. In this course, EKS is a design-only topic.

AWS Lambda

  • For: event-driven work (S3 uploads, SQS messages, EventBridge schedules), spiky or low-traffic APIs, glue code, scheduled jobs.
  • .NET 10: the dotnet10 managed runtime (available since January 2026), container images, or custom runtimes with Native AOT. A whole ASP.NET Core app can run in Lambda through Amazon.Lambda.AspNetCoreServer.Hosting, the approach the module project uses.
  • Billing: per request plus per GB-second of execution. The always-free tier includes 1 million requests and 400,000 GB-seconds per month.
  • Sharp edges: cold starts (the first request on a new execution environment pays for runtime start and your app's startup, which is noticeable for .NET without Native AOT or SnapStart), a 15-minute maximum duration, payload limits, and API Gateway integration timeouts. Connection pools to relational databases need RDS Proxy.

Amazon ECS Express Mode

  • For: "give me an HTTPS URL for this container" with production-shaped defaults. It is the AWS-recommended path for teams who would have used App Runner.
  • Creates: a Fargate service in the default cluster (or one you name), a task definition, an ALB with an HTTPS listener and an ACM certificate, security groups, target-tracking auto scaling on CPU (target 60%), a log group, a deployment alarm, and canary deployments. You get a URL of the form https://<service>.ecs.<region>.on.aws/.
  • Defaults to know: 1 vCPU and 2 GB per task, container port 80 (set containerPort to 8080 for the .NET images), health check path / (set it to /health/ready), and the default VPC with public subnets and public IPs on tasks unless you pass your own subnets. If you pass private subnets, it creates an internal ALB.
  • Billing: no extra charge beyond the resources it creates. Up to 25 Express Mode services in a VPC can share one ALB, which lowers the cost per service.
  • Sharp edges: the deployment strategy and load balancer configuration cannot be changed afterwards. Teams that need rolling or blue/green deployments should create a standard ECS service instead.

AWS App Runner: closed to new customers

App Runner stopped accepting new customers on 30 April 2026. Existing customers can keep using it, but AWS does not plan new features. Do not design new Harbourline workloads on it. Use ECS Express Mode for the same "image in, URL out" experience, or a standard ECS service on Fargate when you need more control.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Azure Virtual Machines / IIS on Windows ServerEC2 (Windows or Linux) + ALBLinux + Kestrel avoids Windows licence cost; Systems Manager replaces RDP-based admin
Azure App Service (Windows/Linux)Elastic Beanstalk, or ECS Express Mode for containersBeanstalk's EC2 instances and ALB are visible, editable and billed in your account; App Service hides its workers
App Service deployment slotsBeanstalk blue/green (swap environment URLs), ECS rolling or blue/green deploymentsNo single "slot" concept; you get the same outcome with environments, target groups or ECS deployment controllers
Azure Container AppsECS on Fargate (and Express Mode)ECS is AWS-native and integrates with IAM task roles. Container Apps' scale-to-zero has no direct ECS equivalent; Lambda covers that niche
AKSEKSSimilar managed Kubernetes. EKS charges for the control plane; AKS's free tier does not
Azure Functions (consumption / flex)Lambda (dotnet10)Lambda has one handler per function, or a whole ASP.NET Core app behind API Gateway. Cold starts behave similarly; Native AOT and SnapStart are the AWS mitigations
WebJobs / Windows ServicesWorker Service on Fargate, Lambda + EventBridge SchedulerSchedules live outside the app as managed rules
Azure Spring Apps / other retired PaaSApp Runner (closed to new customers)Plan for service retirement: prefer core, broadly used services for important workloads

Architecture

Harbourline's decision tree for a new .NET workload:

What you manage versus what AWS manages:

The further right you go, the less you manage, and the less you can control. Compliance teams care about both sides: fewer components to patch is good evidence, but so is being able to explain exactly what runs where.

Security-boundary view: in every option the workload identity is an IAM role (instance profile, task role or function execution role), and the network boundary is your VPC (Lambda runs outside your VPC unless you attach it). Fargate and Lambda isolate each task or execution environment in its own micro-VM (Firecracker) ⚠ VERIFY current isolation documentation for Fargate. On EC2 and ECS on EC2, containers on the same instance share a kernel. That matters when a security review asks about multi-tenant isolation.

Comparison in numbers

EC2 (Linux)Beanstalk (AL2023)ECS FargateECS Express ModeEKSLambda
Unit of deploymentAMI / packageZip or containerContainer imageContainer imageContainer imageZip, container, or AOT binary
You patch the OSYesPlatform updates (can be managed)NoNoNode OS (unless Fargate or Auto Mode)No
Scale-to-zeroNoNoNo (min 1 task for a service)NoNoYes
Typical scale-out speedMinutes (new instances)MinutesTens of seconds to a minuteSame as FargateSeconds (pods) to minutes (nodes)Milliseconds to seconds per new environment
Cold start concernNoNoOnly on scale-outOnly on scale-outOnly on scale-outYes, per new execution environment
Max request durationUnlimitedUnlimitedUnlimited (ALB idle timeout applies)SameUnlimited15 minutes (API Gateway: about 30 s for HTTP APIs)
.NET Framework 4.xWindowsWindows/IIS platformWindows containers (ECS only)No (Linux)Windows nodesNo
Extra platform chargeNoneNoneNoneNoneControl plane per hourNone
Effort for a 3-person .NET teamHighMediumLow–mediumLowHighLow (plus cold-start tuning)

What one small API costs per month

The model below (complete code in the next section) prices a small Harbourline API in us-east-1 with on-demand list prices checked on 2026-11-18. Assumptions: 2 Fargate tasks of 0.25 vCPU / 0.5 GB on arm64, one NAT gateway, one ALB averaging 1 LCU, Lambda at 1,024 MB on arm64. Output for 2 million requests a month at 80 ms:

OptionUSD / month
Lambda (arm64) + HTTP API, no VPC4.53
Beanstalk single t4g.small, no ALB, public12.26
ECS Express Mode, defaults (public tasks, ALB)43.98
ECS Fargate arm64 ×2 + ALB + 1 NAT gateway69.76
EKS + Fargate ×2 + ALB + 1 NAT gateway142.76

At 30 million requests a month at 120 ms, Lambda rises to about USD 84, while the container options do not change (two small tasks would need more capacity at that load, so in practice they would grow too). The lessons:

  • Fixed costs dominate small APIs. The ALB (~USD 22) and a NAT gateway (~USD 33) cost more than the Fargate tasks. Share ALBs across services (listener rules, or Express Mode sharing), and use VPC endpoints or a shared egress VPC instead of a NAT gateway per workload.
  • Lambda wins at low and spiky volume, then crosses over. Where the lines cross depends on duration and memory. Measure, do not guess.
  • The cheapest row is not the bank's answer. A single public Beanstalk instance has no redundancy across Availability Zones and no private networking. It suits a sandbox demo, not a customer-facing service.
  • EKS's control plane is a fixed tax that only pays off when many workloads share a cluster.

The model excludes data transfer, logs, WAF, the free tier and credits. Use the AWS Pricing Calculator for real estimates (see the pricing calculator lab).

Step-by-step implementation

Write down the workload's shape

For the workload you are hosting, record: request pattern (steady, spiky, event-driven), p95/p99 latency target, longest request, .NET version, Windows dependencies, data stores and their connection model, team skills, and compliance constraints (data residency, isolation, evidence).

Walk the decision tree

Use the diagram above. If two options remain, prefer the one with fewer moving parts you operate.

Price it with the model, then the calculator

Run the cost model with your traffic numbers. Then build a proper estimate in the AWS Pricing Calculator, including logs, data transfer and the environments you need (dev, test, production).

Keep the code host-agnostic

Use the patterns from the reference Accounts API: configuration from environment variables, logs to stdout, the port from the platform, no file-system state, and AddAWSLambdaHosting (a no-op outside Lambda). You can then change host without changing code, which is the module project.

Record the decision

Write an ADR: context, options considered, decision, consequences, and the trigger to revisit (for example "if traffic exceeds 50 million requests a month, re-evaluate Lambda against Fargate").

AWS Console instructions

You do not need to deploy anything for this lesson. To see the options side by side:

  • Console → Elastic Beanstalk → Create application → Platform. Open the Platform list and note the .NET on Amazon Linux 2023 and Windows Server IIS platform branches. Cancel before creating.
  • Console → ECS → Express mode (left navigation). Look at the creation form: image, roles, CPU, memory, port, health check path and Additional configurations (cluster, subnets, scaling). Cancel before creating.
  • Console → Lambda → Create function → Runtime. Confirm .NET 10 appears in the runtime list. Cancel.
  • Console → App Runner. You will see the availability notice. There is nothing to create for new customers.

AWS CLI

# Elastic Beanstalk: which .NET platform branches exist right now?
aws elasticbeanstalk list-available-solution-stacks --profile learn-sandbox --region us-east-1 \
  --query "SolutionStacks[?contains(@, '.NET')]"

# ECS Express Mode: the whole service in one call (OPTIONAL, costs money while it runs).
# Prerequisites: an image in ECR (next lessons), ecsTaskExecutionRole and
# ecsInfrastructureRoleForExpressServices created as in the AWS getting-started guide.
ACCOUNT=$(aws sts get-caller-identity --query Account --output text --profile learn-sandbox)
aws ecs create-express-gateway-service --profile learn-sandbox --region us-east-1 \
  --service-name hl-m03-accounts-express \
  --execution-role-arn arn:aws:iam::$ACCOUNT:role/ecsTaskExecutionRole \
  --infrastructure-role-arn arn:aws:iam::$ACCOUNT:role/ecsInfrastructureRoleForExpressServices \
  --primary-container "{\"image\":\"$ACCOUNT.dkr.ecr.us-east-1.amazonaws.com/hl-m03-accounts-api:v1\",\"containerPort\":8080,\"environment\":[{\"name\":\"ASPNETCORE_ENVIRONMENT\",\"value\":\"Production\"}]}" \
  --cpu 0.25 --memory 0.5 --cpu-architecture ARM64 \
  --health-check-path /health/ready \
  --scaling-target '{"minTaskCount":1,"maxTaskCount":2}' \
  --tags key=Project,value=cea-lab key=Lab,value=m03-hosting key=Environment,value=learn \
  --monitor-resources

# Watch it, then DELETE it when you are done.
aws ecs describe-express-gateway-service --service-arn <service-arn> --profile learn-sandbox --region us-east-1
aws ecs delete-express-gateway-service --service-arn <service-arn> --profile learn-sandbox --region us-east-1

The --cpu/--memory units, the --tags shorthand and the delete command name follow the ECS CLI conventions; check them with aws ecs create-express-gateway-service help before running ⚠ VERIFY. AWS's examples use --cpu 2 --memory 4 for 2 vCPU and 4 GB. The reference API's container must also be reachable without authentication for this test, which the lab handles with a learning-shortcut flag (see the lab README).

Infrastructure as Code

The module project deploys one codebase to three hosts from one CDK app. Each stack is independent, so you can deploy and destroy them one at a time.

labs/m03-accounts-api/infra/cdk/Harbourline.Accounts.Infra/Program.cs (excerpt)
var shared = new SharedStack(app, "HlM03-Shared", new StackProps { Env = env });      // DynamoDB table used by all hosts
var registry = new RegistryStack(app, "HlM03-Registry", new StackProps { Env = env }); // ECR repository
var fargate = new FargateStack(app, "HlM03-Fargate", new FargateStackProps
{
    Env = env,
    TableName = SharedStack.TableName,
    RepositoryName = RegistryStack.RepositoryName,
    ImageTag = imageTag,
});
fargate.AddStackDependency(shared);
fargate.AddStackDependency(registry);

// Beanstalk and Lambda stacks are added only when their build output exists
// (publish/beanstalk.zip and publish/lambda/), so each host can be deployed on its own.

Tags.Of(app).Add("Project", "cea-lab");
Tags.Of(app).Add("Lab", "m03-accounts-api");
Validations.Of(app).AddPlugins(new AwsSolutionsChecks(app, new NagPackProps { Verbose = true })); // cdk-nag

Each host stack makes host-specific choices in one place:

StackKey choices in the lab
BeanstalkStack.csSingle-instance environment (no ALB, to save cost), .NET 10 AL2023 solution stack passed as context
FargateStack.csarm64 tasks of 0.25 vCPU / 0.5 GB, private subnets, ALB health check on /health/ready, circuit breaker with rollback
LambdaStack.csdotnet10 runtime, arm64, 1,024 MB, HTTP API

Complete code

1. One binary, three hosts

The reference API (labs/m03-accounts-api/src/Harbourline.Accounts.Api) runs unchanged on Beanstalk, Fargate and Lambda because of three small pieces:

Program.cs (excerpt from the reference API)
// 3. Hosting: the same binary runs on Kestrel (Beanstalk, ECS, local) or inside Lambda.
builder.UsePlatformPort();
builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi); // does nothing outside Lambda
builder.Services.AddTrustedForwardedHeaders(builder.Configuration);
Hosting/HostingExtensions.cs (excerpt from the reference API)
/// <summary>
/// Elastic Beanstalk's nginx proxy forwards to the port in the PORT variable (default 5000).
/// Containers use ASPNETCORE_HTTP_PORTS (8080 in the official images); Lambda needs no port.
/// </summary>
public static WebApplicationBuilder UsePlatformPort(this WebApplicationBuilder builder)
{
    var port = Environment.GetEnvironmentVariable("PORT");
    var explicitUrls = builder.Configuration["ASPNETCORE_URLS"] ?? builder.Configuration["urls"];
    if (int.TryParse(port, out var p) && p is > 0 and < 65536 && string.IsNullOrEmpty(explicitUrls))
    {
        builder.WebHost.UseUrls($"http://0.0.0.0:{p}");
    }
    return builder;
}

2. A cost model you can run

Save this as a console project (dotnet new console -n Harbourline.HostingCost -f net10.0) and replace Program.cs. It needs no packages and no AWS account. The numbers in the table above come from running it.

Program.cs
using System.Globalization;

// A deliberately simple monthly cost model for ONE small API, us-east-1, on-demand prices.
// It is a teaching aid, not a quote: check the AWS Pricing Calculator before any decision.
// Usage: dotnet run -- [requestsPerMonth] [avgDurationMs]
var requests = args.Length > 0 ? double.Parse(args[0], CultureInfo.InvariantCulture) : 2_000_000;
var durationMs = args.Length > 1 ? double.Parse(args[1], CultureInfo.InvariantCulture) : 80;

var s = new Scenario(RequestsPerMonth: requests, AvgDurationMs: durationMs, LambdaMemoryMb: 1024,
    Tasks: 2, VcpuPerTask: 0.25, GbPerTask: 0.5, NatGateways: 1, NatGbPerMonth: 5);

Console.WriteLine($"Scenario: {s.RequestsPerMonth:N0} requests/month, {s.AvgDurationMs} ms average, us-east-1, on-demand");
Console.WriteLine();
Console.WriteLine($"{"Option",-44} {"USD / month",12}");
Console.WriteLine(new string('-', 57));
foreach (var (name, cost) in CostModel.All(s))
{
    Console.WriteLine($"{name,-44} {cost,12:N2}");
}
Console.WriteLine();
Console.WriteLine("Excludes: data transfer out, CloudWatch Logs, DynamoDB, WAF, free tier and credits.");

public sealed record Scenario(
    double RequestsPerMonth, double AvgDurationMs, int LambdaMemoryMb,
    int Tasks, double VcpuPerTask, double GbPerTask, int NatGateways, double NatGbPerMonth);

public static class Prices
{
    // us-east-1 on-demand list prices, checked 2026-11-18 (verify before reuse).
    public const double HoursPerMonth = 730;
    public const double FargateArmVcpuHour = 0.03238, FargateArmGbHour = 0.00356;
    public const double AlbHour = 0.0225, AlbLcuHour = 0.008;
    public const double NatHour = 0.045, NatPerGb = 0.045;
    public const double LambdaPerMillionRequests = 0.20, LambdaArmGbSecond = 0.0000133334;
    public const double HttpApiPerMillion = 1.00;
    public const double EksClusterHour = 0.10;
    public const double Ec2T4gSmallHour = 0.0168;
    public const double PublicIpv4Hour = 0.005;
}

public static class CostModel
{
    public static IEnumerable<(string Name, double Cost)> All(Scenario s)
    {
        var nat = s.NatGateways * Prices.NatHour * Prices.HoursPerMonth + s.NatGbPerMonth * Prices.NatPerGb;
        var fargate = s.Tasks * Prices.HoursPerMonth *
            (s.VcpuPerTask * Prices.FargateArmVcpuHour + s.GbPerTask * Prices.FargateArmGbHour);
        var alb = Prices.HoursPerMonth * (Prices.AlbHour + 1 * Prices.AlbLcuHour); // assume ~1 LCU average

        var gbSeconds = s.RequestsPerMonth * (s.AvgDurationMs / 1000) * (s.LambdaMemoryMb / 1024.0);
        var lambda = s.RequestsPerMonth / 1e6 * Prices.LambdaPerMillionRequests + gbSeconds * Prices.LambdaArmGbSecond;
        var httpApi = s.RequestsPerMonth / 1e6 * Prices.HttpApiPerMillion;

        yield return ("Lambda (arm64) + HTTP API, no VPC", lambda + httpApi);
        yield return ("Beanstalk single t4g.small, no ALB, public", Prices.Ec2T4gSmallHour * Prices.HoursPerMonth);
        // Express Mode defaults: default VPC, public subnets, a public IPv4 address per task, no NAT gateway.
        yield return ("ECS Express Mode, defaults (public tasks)", fargate + alb + s.Tasks * Prices.PublicIpv4Hour * Prices.HoursPerMonth);
        yield return ("ECS Fargate arm64 x2 + ALB + 1 NAT gateway", fargate + alb + nat);
        yield return ("EKS + Fargate x2 + ALB + 1 NAT gateway", fargate + alb + nat + Prices.EksClusterHour * Prices.HoursPerMonth);
    }
}

Run it with your own numbers: dotnet run -- 30000000 120.

Code explained line by line

Host-agnostic hosting (reference API)

  1. UsePlatformPort() reads the PORT environment variable that Elastic Beanstalk's Linux .NET platform uses to tell the app where nginx will forward traffic. It only binds to it if nothing else (ASPNETCORE_URLS, urls) was set explicitly. In containers, ASPNETCORE_HTTP_PORTS=8080 from the base image applies instead. In Lambda, no port is used at all.
  2. AddAWSLambdaHosting(LambdaEventSource.HttpApi) comes from Amazon.Lambda.AspNetCoreServer.Hosting. When the process runs inside Lambda (detected from Lambda's environment variables), it replaces Kestrel with a bridge that turns API Gateway HTTP API events into HttpContext requests. Everywhere else it does nothing, so the same Program.cs serves all hosts.
  3. AddTrustedForwardedHeaders(...) is the baseline from the previous lesson. On Beanstalk the proxy is nginx on the same instance (loopback). On Fargate it is the ALB (VPC range). Both are configured.

Cost model

  1. Scenario captures the workload: request volume, average duration, Lambda memory, number and size of tasks, NAT gateways and NAT data.
  2. Prices holds list prices as named constants with the date they were checked. In real work you would read them from the AWS Price List API or a reviewed configuration file, never scattered literals.
  3. nat = hourly charge × 730 hours + data processed. NAT gateways are a fixed cost that surprises most teams.
  4. fargate = tasks × hours × (vCPU × vCPU price + GB × GB price). That is exactly how Fargate bills, per second in reality.
  5. alb = hourly charge + an assumed average of 1 LCU. A busy ALB uses more LCUs. Check ConsumedLCUs in CloudWatch.
  6. gbSeconds = requests × seconds per request × GB of memory. Lambda bills memory × duration, so a 1,024 MB function running 80 ms uses 0.08 GB-seconds per call.
  7. lambda + httpApi are the per-request costs. There is no idle cost, which is why Lambda wins at low volume.
  8. Express Mode uses the Fargate + ALB cost plus public IPv4 addresses for tasks in public subnets (its default). With private subnets it would need a NAT gateway or VPC endpoints like the Fargate row.
  9. EKS adds the control-plane hour charge to the Fargate row.

Security considerations

⚠ Learning shortcut — not for production

The lab's Beanstalk environment is a single public instance with no load balancer, and Express Mode's defaults put tasks in public subnets with public IP addresses. Both are fine for a one-hour experiment and wrong for a banking service. Production: load-balanced across at least two Availability Zones, workloads in private subnets, internet-facing traffic only through an ALB (or API Gateway) with AWS WAF, and egress controlled through NAT or VPC endpoints.

  • Identity is always a role. Instance profile (EC2, Beanstalk), task role (ECS), execution role (Lambda). Never access keys in environment properties.
  • Patching evidence differs by host. EC2: Patch Manager compliance reports. Beanstalk: managed platform updates and the platform version history. Fargate: AWS patches the host. You rebuild your image to patch the container OS (next lesson). Lambda: managed runtime updates; container-image functions need rebuilding.
  • Isolation. Fargate tasks and Lambda execution environments do not share a kernel with other tenants' workloads. Containers on shared EC2 instances do. Some bank risk assessments require the former for sensitive workloads.
  • Network exposure. Lambda without VPC attachment reaches AWS services over AWS's network and the internet. Attach it to a VPC with VPC endpoints when it must reach private resources or when policy requires egress control.
  • Closed or maintenance-mode services (App Runner for new customers) are a supplier risk. Prefer core services for important business services and record the dependency in your third-party risk register.

Banking use case

Harbourline's architecture board applies the decision tree to four real (fictional) workloads:

WorkloadShapeDecisionWhy
Accounts API (mobile and web)Steady traffic 06:00–23:00, p99 under 300 ms, .NET 10ECS on Fargate behind ALB, private subnets, arm64, min 2 tasks across AZsPredictable latency, no cold starts, low ops; Savings Plans cover the baseline
Statement PDF generatorNightly batch, 2 hours, CPU-heavyECS on Fargate task started by EventBridge Scheduler (no service)Longer than Lambda's 15 minutes; pay only while it runs
Card-transaction file intakePartner drops files to S3 a few times a dayLambda (dotnet10), S3 event → SQS → LambdaEvent-driven, idle most of the day, scales with file bursts
Legacy branch-reporting portalASP.NET Web Forms on .NET Framework 4.8Beanstalk Windows/IIS, load-balanced, plus a porting plan with AWS Transform for .NET (see this module's overview)Cannot run on Linux today; Beanstalk removes most server toil

Each decision is recorded as an ADR with a revisit trigger. The operational resilience team links the ADRs to the impact tolerances for each important business service. Whether that meets a specific regulatory expectation is for Harbourline's risk and compliance functions to judge.

Common mistakes

  • Choosing by familiarity ("we always used VMs") → patching toil and idle cost → walk the decision tree with the workload's real shape.
  • Choosing by fashion (EKS for one API) → platform cost and complexity with no benefit → ECS until there is a real Kubernetes need.
  • Ignoring fixed costs (ALB and NAT per environment) → a "tiny" service costs USD 70 a month per environment → share ALBs, use VPC endpoints, consolidate non-production environments.
  • Putting latency-critical APIs on Lambda without measuring cold starts → p99 breaches after quiet periods → measure, then use Native AOT, SnapStart, provisioned concurrency or Fargate.
  • Starting new work on App Runner from an old tutorial → blocked for new accounts → ECS Express Mode or ECS on Fargate.
  • Assuming Beanstalk is "serverless" → surprise EC2 and ALB bills → it creates real resources; terminate environments you are not using.
  • Using Express Mode's defaults for regulated workloads → public subnets and public task IPs → pass private subnets and your own security groups at creation (they cannot be changed later for the load balancer).

Troubleshooting

SymptomLikely causeFix
Beanstalk environment "Severe", 502 from nginxApp not listening on the port nginx forwards toRespect the PORT variable (as UsePlatformPort does) or configure the proxy port
Fargate tasks stop with CannotPullContainerErrorNo route to ECR from private subnets (no NAT, no VPC endpoints) or the execution role lacks ECR permissionsAdd a NAT gateway or ECR/S3/Logs VPC endpoints; attach AmazonECSTaskExecutionRolePolicy
Express Mode creation fails with an assume-role errorIAM roles created seconds ago have not propagatedWait about a minute and retry
Express Mode service never becomes healthyHealth check path / returns 404, or the container port is still 80Set --health-check-path /health/ready and containerPort 8080
Lambda p99 high only in the morningCold starts after idle periodsNative AOT, SnapStart, provisioned concurrency, or a different host
App Runner console says it is not availableAccount is a new customer after 30 April 2026Use ECS Express Mode
Unexpected EC2 charges after a Beanstalk testEnvironment still runningTerminate the environment; delete the application versions bucket objects if no longer needed

Cost and cleanup

The lesson itself is free: the cost model and console browsing create nothing.

If you ran the optional Express Mode command, it bills for the Fargate task, the ALB and public IPv4 addresses while it runs. With one 0.25 vCPU arm64 task, that is roughly USD 0.04 per hour, so under USD 0.05 for a one-hour test, plus a few cents of logs. Delete it straight away:

aws ecs delete-express-gateway-service --service-arn <service-arn> --profile learn-sandbox --region us-east-1 --monitor-resources

# Confirm nothing from this lesson remains.
aws resourcegroupstaggingapi get-resources --tag-filters Key=Lab,Values=m03-hosting \
  --region us-east-1 --profile learn-sandbox --query "ResourceTagMappingList[].ResourceARN"
aws elbv2 describe-load-balancers --profile learn-sandbox --region us-east-1 --query "LoadBalancers[].LoadBalancerName"

Express Mode removes the ALB when no Express services remain in the VPC. Confirm the load balancer list is empty, and remove any leftover CloudWatch log group (/aws/ecs/default/...) if you want a completely clean account.

Exercises

  • 🟢 Guided: Run the cost model for three volumes: 200,000, 2 million and 50 million requests a month at 80 ms. Find, to the nearest million, the volume where Lambda + HTTP API costs the same as Fargate ×2 + ALB + NAT.
  • 🟡 Challenge: Extend the model with a "shared ALB" option (one ALB shared by N services, cost divided by N) and a "VPC endpoints instead of NAT" option (interface endpoints for ECR API, ECR Docker, CloudWatch Logs and STS, each priced per AZ-hour plus per GB; use two AZs). Look up the endpoint price on the VPC pricing page.
  • 🔴 Live problem: The Payments team wants to host a new "confirmation of payee" API: synchronous, called during every payment set-up, p99 under 250 ms, traffic peaks at 09:00 and 13:00 and is near zero overnight, and it calls a partner over mTLS. They are split between Lambda and Fargate. Recommend a host and write the ADR's "consequences" and "revisit when" sections.

Assignment

Write the ADR for Harbourline's Accounts API hosting decision in your portfolio repository (docs/adr/0001-accounts-api-hosting.md). Use the module project: deploy the API to Beanstalk, Fargate and Lambda (one at a time, destroying each), measure p50/p95 latency and cold start with the lab's latency probe, record the monthly cost estimate for each, and state your decision with its revisit trigger.

Solutions

Knowledge check

Interview questions

  • "How would you host a new .NET 10 API on AWS?" — Default to ECS on Fargate behind an ALB in private subnets, arm64, two or more tasks across AZs, task role for permissions, image in ECR. Choose Lambda instead for event-driven or very spiky low-volume work. Choose Beanstalk or EC2 Windows only for .NET Framework. Record the decision as an ADR.
  • "Lambda or containers for an API?" — Depends on traffic shape, latency target, request duration and connection model. Lambda for spiky or low volume with tolerance for cold starts (or with AOT/SnapStart/provisioned concurrency). Containers for steady traffic, tight p99, long requests, pooled connections. Model the cost at expected volume, including API Gateway.
  • "When is EKS justified?" — When Kubernetes is an organisation standard with a platform team, when you need its ecosystem, or for portability across environments. Not for one or two services.
  • "What happened to App Runner?" — It closed to new customers on 30 April 2026. Existing customers can keep using it, with no new features planned. The recommended alternative is ECS Express Mode. The lesson: prefer core services and track supplier risk for important workloads.

Certification practice

Completion checklist

  • I can say what I manage and what AWS manages for each hosting option
  • I know why App Runner is not an option for new accounts, and what replaces it
  • I ran the cost model and can explain which fixed costs dominate small APIs
  • I walked the decision tree for at least two workloads
  • I deleted any Express Mode service I created and checked for leftover load balancers

Key takeaways

  • ECS on Fargate is Harbourline's default for new .NET services: low operations, predictable latency, IAM task roles.
  • Lambda wins for event-driven and low or spiky traffic. Measure cold starts and include API Gateway in the cost.
  • Beanstalk and EC2 Windows remain for .NET Framework and lift-and-shift, with a porting plan.
  • ECS Express Mode replaces App Runner for "image to URL". Override its public-subnet defaults for banking workloads.
  • Fixed costs (ALB, NAT, EKS control plane) often matter more than compute for small APIs. Record every hosting decision as an ADR with a revisit trigger.

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page