Container-backed APIs: ALB, NLB and VPC Link
Put an ASP.NET Core API running on ECS Fargate behind API Gateway without exposing it to the internet, using VPC links to private load balancers, and know when to skip API Gateway entirely.
Assumes: .NET 10 LTS · ASP.NET Core 10 · Amazon ECS on Fargate · Amazon.CDK.Lib 2.277.0 · Cdklabs.CdkNag 3.0.2 · AWS CLI v2 · Docker Compose · Region us-east-1. Verified against official sources on 2026-11-17.
Learning objectives
By the end of this lesson you can:
- Compare four ways to publish a container API: public ALB, HTTP API + VPC link, REST API + VPC link, and REST API to a public endpoint.
- Explain VPC link V2 (ALB, NLB, Cloud Map targets) and the legacy VPC link V1 (NLB only), including the November 2025 change that lets REST APIs reach ALBs directly.
- Design security groups, private DNS, TLS and health checks for a private integration.
- Deploy an HTTP API with IAM authorization, a VPC link and a private ALB in front of an ECS Fargate service with the CDK in C#, test it with a SigV4-signed curl, and destroy it within an hour.
- Decide when to skip API Gateway and use ALB with AWS WAF and JWT verification, and where ECS Express Mode fits now that App Runner is closed to new customers.
Prerequisites
- Amazon API Gateway: REST vs HTTP vs WebSocket
- Module 2: Networking — VPCs, subnets, security groups, load balancers, NAT
- Module 3: .NET on AWS — containers and ECS
- Tools: .NET 10 SDK, Docker Desktop (Linux containers), AWS CLI v2 (
learn-sandbox), Node.js + AWS CDK CLI, curl 7.75 or later (for--aws-sigv4)
Why this matters in banking
Harbourline's reconciliation service compares the day's ledger postings with the core banking system. It holds a connection pool to an on-premises database, takes 300–800 ms per call and runs all day, so it lives in a container on ECS Fargate rather than in Lambda. It must never be reachable from the internet, yet the nightly batch jobs and an internal operations portal need a stable, authenticated, throttled API. The answer is a private load balancer in private subnets, reached by API Gateway through a VPC link — and you need to know exactly which security group allows what, because an auditor will ask.
The idea in plain language
A load balancer spreads requests across healthy containers. An internal load balancer has only private IP addresses, so nothing on the internet can reach it.
API Gateway, however, runs outside your VPC. A VPC link is a bridge: API Gateway creates network interfaces (ENIs) in subnets you choose, with security groups you choose, and sends requests through them to your private load balancer or service. To your VPC, the traffic looks like it comes from those ENIs.
Analogy: the reconciliation service is a back office with no street door. The VPC link is a staffed internal corridor from the public reception (API Gateway) to the back office. Reception checks the visitor's badge (IAM or JWT), the corridor has its own door guard (the VPC link security group), and the back office only opens its door to people coming down that corridor (the ALB security group rule).
What problem the AWS service solves
Four ways to publish a container API
| Pattern | Path | Good for | Watch out |
|---|---|---|---|
| A. Public ALB, no API Gateway | Internet → ALB (+ WAF, + JWT verification) → Fargate | One API, browser apps, lowest moving parts | No usage plans, request validation or API keys; ALB bills hourly |
| B. HTTP API + VPC link | Internet or internal caller → HTTP API → VPC link → private ALB / NLB / Cloud Map → Fargate | Cheap per request, JWT or IAM auth, internal APIs | No WAF on the HTTP API, no caching or request validation |
| C. REST API + VPC link | Client → (WAF) REST API → VPC link → private ALB or NLB → Fargate | Public banking APIs needing WAF, usage plans, validation | Higher request price; VPC link V2 for ALB since Nov 2025 |
| D. REST/HTTP API → public ALB URL | Client → API Gateway → internet → public ALB | Rarely | The backend is internet-reachable and can be called around the gateway |
VPC link versions (checked 2026-11-17)
| VPC link V2 | VPC link V1 (legacy) | |
|---|---|---|
| Used by | HTTP APIs and REST APIs | REST APIs only |
| Targets | ALB, NLB, AWS Cloud Map (Cloud Map: HTTP APIs only) | NLB only |
| Created with | aws apigatewayv2 create-vpc-link | aws apigateway create-vpc-link |
| Security groups | Yes, chosen at creation | Not on the link itself |
| Mutability | Subnets and security groups cannot be changed; create a new link | — |
| Idle behaviour | After 60 days without traffic it becomes INACTIVE and its ENIs are deleted; the next request triggers re-provisioning that takes minutes | — |
| Ownership | Link, load balancer and API in the same account | Same |
Until November 2025, a REST API that needed a private ALB had to put an NLB in front of it. AWS now marks VPC link V1 as legacy and recommends V2 for new REST API private integrations, where you set connectionType to VPC_LINK, connectionId to the V2 link ID and integrationTarget to the ALB or NLB ARN.
Availability Zones matter. In us-east-1, VPC link V2 supports the zone IDs use1-az1, use1-az2, use1-az4, use1-az5 and use1-az6 — not use1-az3. Zone names (us-east-1a) map to different zone IDs in each account, so check with aws ec2 describe-availability-zones before choosing subnets.
Security groups, DNS, TLS and health checks
- Security groups. Chain them: the VPC link SG may send to the ALB SG on the listener port; the ALB SG accepts only from the VPC link SG; the task SG accepts only from the ALB SG on 8080. No
0.0.0.0/0anywhere on the private path. NLBs support security groups too, but only if you attach them when you create the NLB. - Private DNS. An internal ALB's DNS name resolves to private IPs. Give it a friendly name such as
recon.internal.harbourline.examplein a Route 53 private hosted zone for internal callers; API Gateway itself targets the listener ARN, not the DNS name. - TLS to the backend. By default the gateway talks HTTP to the private listener inside your VPC. For encryption in transit to the target, add an HTTPS listener with an ACM certificate and set the server name to verify:
tlsConfig.serverNameToVerify(HTTP APIs,secureServerNamein CDK) or anhttps://URI with the certificate's host name (REST APIs). The certificate must match that name ⚠ VERIFY whether private-CA certificates are accepted for your API type. - Health checks. API Gateway does not health-check; the load balancer does. Point the target group at
/health/ready(dependencies reachable) and keep/health/livefor the container. With no healthy targets, the ALB returns 503 and API Gateway passes it on. Short deregistration delays (15–30 s) make deployments faster; keep them longer than your slowest request. - Timeouts. The gateway's integration timeout still applies (HTTP API 30 s maximum; REST 29 s by default). The ALB idle timeout (60 s by default) is not the limiting factor.
When to skip API Gateway
Since November 2025 an ALB can verify JWTs itself: a jwt-validation action on an HTTPS listener rule checks the signature against a JWKS URL, requires iss and exp, validates nbf/iat when present, and can check up to 10 additional claims (for example a space-separated scope claim). Limits: RS256 only, JWKS response up to 150 KB and 10 keys. Together with AWS WAF on the ALB and the older authenticate-cognito / authenticate-oidc actions (browser sign-in with session cookies), a single API can go straight to an ALB.
Skip API Gateway when you have one or two APIs, steady traffic (the ALB's hourly price beats per-request pricing at high volume), and no need for usage plans, API keys, request validation, caching or a developer portal. Keep API Gateway when you publish many APIs or partner products, need per-client throttling, or want Lambda and containers behind one front door.
ECS Express Mode (and why not App Runner)
AWS App Runner is closed to new customers (announced 2026-03-31, effective 2026-04-30). The replacement for "give me a URL for this container" is Amazon ECS Express Mode (launched November 2025): from a container image it creates a Fargate service with canary deployments and target-tracking auto scaling (defaults: 60% CPU, 1–20 tasks), an ALB with an HTTPS listener on 443, an ACM certificate and an AWS-provided domain name, security groups, a CloudWatch log group and deployment alarms. Up to 25 Express Mode services in a VPC can share one ALB. Limits: canary is the only deployment type and you cannot swap the ALB for an NLB. Express Mode is great for internal tools and prototypes; for a regulated API you still want the explicit CDK below so every security group rule is reviewed.
Prices (us-east-1, checked 2026-11-17)
| Item | Price |
|---|---|
| Application Load Balancer | USD 0.0225 per hour + USD 0.008 per LCU-hour |
| Network Load Balancer | USD 0.0225 per hour + USD 0.006 per NLCU-hour |
| NAT gateway | USD 0.045 per hour + USD 0.045 per GB processed (rate shown on the VPC pricing page example; us-east-1 matches ⚠ VERIFY) |
| Public IPv4 address (the NAT gateway's) | USD 0.005 per hour |
| Fargate Linux/x86 | about USD 0.0405 per vCPU-hour + USD 0.0044 per GB-hour (ARM: 0.0324 + 0.0036), per second, 1-minute minimum |
| HTTP API requests | USD 1.00 per million |
| VPC link V2 | No separate charge found on the API Gateway pricing page ⚠ VERIFY |
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| App Service / Container Apps with a private endpoint | ECS Fargate service behind an internal ALB | You build the network path yourself (subnets, SGs, NAT) |
| APIM in internal VNet mode, or APIM v2 "connect to backends in a VNet" | API Gateway + VPC link | API Gateway stays outside your VPC; the VPC link places ENIs inside |
| Application Gateway (+ WAF) | ALB (+ AWS WAF) | ALB can also verify JWTs and run OIDC sign-in on HTTPS listeners |
| Azure Load Balancer (layer 4) | Network Load Balancer | NLB security groups only if attached at creation |
| Front Door with Private Link origins | CloudFront VPC origins or API Gateway + VPC link | Different products, same "no public backend" goal |
| Azure Private DNS zones | Route 53 private hosted zones | Associated with VPCs, not virtual networks |
| App Service "quick deploy a container" | ECS Express Mode (App Runner is closed to new customers) | Express Mode provisions an ALB and Fargate service in your account |
Architecture
Security-boundary view. Trust boundary 1 is API Gateway: IAM authorization, throttling and access logging happen before anything touches the VPC. Trust boundary 2 is the VPC link security group, the only source the ALB accepts. Trust boundary 3 is the task security group, which accepts only the ALB. Nothing in the private subnets has a public IP; outbound traffic leaves through the NAT gateway only (in production, add VPC endpoints for ECR, CloudWatch Logs and S3 so image pulls and logs never cross the internet, and restrict egress further with Network Firewall or a proxy — see Calling partner APIs safely).
Step-by-step implementation
Build and run the API locally (free)
Create the project from Complete code, then run the Docker Compose stack in the IaC tab. curl http://localhost:8080/v1/reconciliation/summary?bookingDate=2026-11-16 goes through the Caddy reverse proxy; the API container itself has no published port, just like a task in a private subnet.
Choose supported Availability Zones
Run aws ec2 describe-availability-zones --profile learn-sandbox --region us-east-1 --query "AvailabilityZones[].[ZoneName,ZoneId]" --output table and pick two zone names whose IDs are not use1-az3.
Deploy the stack (start the one-hour clock)
cdk deploy -c azs=us-east-1a,us-east-1b -c owner=<yourname> --profile learn-sandbox. CDK builds the image, pushes it to the CDK asset repository and creates about 40 resources in 8–12 minutes. The VPC link starts PENDING and becomes AVAILABLE after a few minutes.
Call the API with SigV4
Use the CLI section. Expect 403 without a signature and 200 with one. Then stop one task in the ECS console and watch the ALB keep serving from the other.
Destroy and verify
cdk destroy, then run the tag check. Note the time: you should be well under an hour.
AWS Console instructions
- API Gateway → VPC links: the V2 link shows status, subnets and security group. (The REST API console lists V1 and V2 links under the same menu.)
- API Gateway → APIs → hl-m04-l6-recon-api → Integrations: integration type Private resource, target ALB listener, VPC link
hl-m04-l6-link. - EC2 → Load Balancers → hl-m04-l6-alb: Scheme: internal; Security tab shows the single inbound rule from the VPC link SG. Target groups → Targets shows two healthy IP targets.
- EC2 → Network Interfaces: filter by the VPC link security group to see the ENIs API Gateway created.
- ECS → Clusters → hl-m04-l6-cluster → Services → hl-m04-l6-recon → Tasks: stop one task and watch the service replace it.
AWS CLI
P="--profile learn-sandbox --region us-east-1"
API_URL=$(aws cloudformation describe-stacks --stack-name hl-m04-l6 $P \
--query "Stacks[0].Outputs[?OutputKey=='ApiUrl'].OutputValue" --output text)
# 1. Unsigned request -> 403 from API Gateway (IAM authorization)
curl -i "$API_URL/v1/reconciliation/summary?bookingDate=2026-11-16"
# 2. Export short-lived SSO credentials into this shell and sign with SigV4
eval "$(aws configure export-credentials --profile learn-sandbox --format env)"
curl -s --aws-sigv4 "aws:amz:us-east-1:execute-api" \
--user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
-H "x-amz-security-token: $AWS_SESSION_TOKEN" \
"$API_URL/v1/reconciliation/summary?bookingDate=2026-11-16"
# 3. Inspect the VPC link and its state
aws apigatewayv2 get-vpc-links $P --query "Items[].[Name,VpcLinkId,VpcLinkStatus]" --output tableBuilding the same private integration by hand (HTTP API):
aws apigatewayv2 create-vpc-link $P --name hl-m04-l6-link \
--subnet-ids subnet-0aaa subnet-0bbb --security-group-ids sg-0link \
--tags Project=cea-lab,Lab=m04-l6,Environment=learn,Owner=alex
aws apigatewayv2 create-integration $P --api-id "$API_ID" \
--integration-type HTTP_PROXY --integration-method ANY \
--connection-type VPC_LINK --connection-id "$LINK_ID" \
--integration-uri "$ALB_LISTENER_ARN" --payload-format-version 1.0
aws apigatewayv2 create-route $P --api-id "$API_ID" \
--route-key "GET /v1/reconciliation/summary" \
--target "integrations/$INTEGRATION_ID" --authorization-type AWS_IAMREST API variant through VPC link V2 to the same ALB (no NLB needed):
aws apigateway put-integration $P --rest-api-id "$REST_ID" --resource-id "$RES_ID" \
--http-method GET --type HTTP_PROXY --integration-http-method GET \
--connection-type VPC_LINK --connection-id "$LINK_ID" \
--integration-target "$ALB_ARN" \
--uri "http://recon.internal.harbourline.example/v1/reconciliation/summary"For REST APIs the uri sets the Host header and, for https:// URIs, the name checked against the backend certificate.
Infrastructure as Code
using Amazon.CDK;
using Amazon.CDK.AWS.Apigatewayv2;
using Amazon.CDK.AWS.EC2;
using Amazon.CDK.AWS.ECS;
using Amazon.CDK.AWS.ECS.Patterns;
using Amazon.CDK.AWS.Logs;
using Amazon.CDK.AwsApigatewayv2Authorizers;
using Amazon.CDK.AwsApigatewayv2Integrations;
using Constructs;
using ElbHealthCheck = Amazon.CDK.AWS.ElasticLoadBalancingV2.HealthCheck;
namespace Harbourline.Lab46.Infra;
public sealed class PrivateContainerApiStack : Stack
{
public PrivateContainerApiStack(Construct scope, string id, IStackProps? props = null) : base(scope, id, props)
{
var azs = ((string?)Node.TryGetContext("azs"))?.Split(',')
?? throw new InvalidOperationException("Pass -c azs=<az1>,<az2> (zone IDs supported by VPC link V2).");
var vpc = new Vpc(this, "Vpc", new VpcProps
{
VpcName = "hl-m04-l6-vpc",
IpAddresses = IpAddresses.Cidr("10.40.0.0/16"),
AvailabilityZones = azs,
NatGateways = 1,
SubnetConfiguration = new[]
{
new SubnetConfiguration { Name = "public", SubnetType = SubnetType.PUBLIC, CidrMask = 24 },
new SubnetConfiguration { Name = "app", SubnetType = SubnetType.PRIVATE_WITH_EGRESS, CidrMask = 24 },
},
});
vpc.AddFlowLog("FlowLogs", new FlowLogOptions
{
Destination = FlowLogDestination.ToCloudWatchLogs(new LogGroup(this, "FlowLogGroup", new LogGroupProps
{
Retention = RetentionDays.ONE_WEEK,
RemovalPolicy = RemovalPolicy.DESTROY,
})),
});
var cluster = new Cluster(this, "Cluster", new ClusterProps { ClusterName = "hl-m04-l6-cluster", Vpc = vpc });
var appLogs = new LogGroup(this, "AppLogs", new LogGroupProps
{
LogGroupName = "/hl-m04-l6/recon-api",
Retention = RetentionDays.ONE_WEEK,
RemovalPolicy = RemovalPolicy.DESTROY,
});
var service = new ApplicationLoadBalancedFargateService(this, "Recon", new ApplicationLoadBalancedFargateServiceProps
{
Cluster = cluster,
ServiceName = "hl-m04-l6-recon",
LoadBalancerName = "hl-m04-l6-alb",
PublicLoadBalancer = false,
OpenListener = false,
ListenerPort = 80,
DesiredCount = 2,
MinHealthyPercent = 50,
Cpu = 256,
MemoryLimitMiB = 512,
TaskSubnets = new SubnetSelection { SubnetType = SubnetType.PRIVATE_WITH_EGRESS },
RuntimePlatform = new RuntimePlatform
{
CpuArchitecture = CpuArchitecture.X86_64,
OperatingSystemFamily = OperatingSystemFamily.LINUX,
},
TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions
{
Image = ContainerImage.FromAsset("../../src/Harbourline.Reconciliation.Api"),
ContainerPort = 8080,
LogDriver = LogDrivers.AwsLogs(new AwsLogDriverProps { LogGroup = appLogs, StreamPrefix = "recon" }),
},
});
service.TargetGroup.ConfigureHealthCheck(new ElbHealthCheck
{
Path = "/health/ready",
HealthyHttpCodes = "200",
Interval = Duration.Seconds(15),
});
service.TargetGroup.SetAttribute("deregistration_delay.timeout_seconds", "20");
var linkSg = new SecurityGroup(this, "VpcLinkSg", new SecurityGroupProps
{
Vpc = vpc,
SecurityGroupName = "hl-m04-l6-vpclink",
Description = "API Gateway VPC link ENIs",
AllowAllOutbound = false,
});
service.LoadBalancer.Connections.AllowFrom(linkSg, Port.Tcp(80), "HTTP from the API Gateway VPC link only");
var vpcLink = new VpcLink(this, "VpcLink", new VpcLinkProps
{
Vpc = vpc,
VpcLinkName = "hl-m04-l6-link",
Subnets = new SubnetSelection { SubnetType = SubnetType.PRIVATE_WITH_EGRESS },
SecurityGroups = new[] { linkSg },
});
var api = new HttpApi(this, "Api", new HttpApiProps
{
ApiName = "hl-m04-l6-recon-api",
CreateDefaultStage = false,
DefaultAuthorizer = new HttpIamAuthorizer(),
DefaultIntegration = new HttpAlbIntegration("AlbIntegration", service.Listener,
new HttpAlbIntegrationProps { VpcLink = vpcLink }),
});
var stage = new HttpStage(this, "DefaultStage", new HttpStageProps
{
HttpApi = api,
StageName = "$default",
AutoDeploy = true,
Throttle = new ThrottleSettings { RateLimit = 10, BurstLimit = 20 },
});
var accessLogs = new LogGroup(this, "ApiAccessLogs", new LogGroupProps
{
LogGroupName = "/hl-m04-l6/api-access",
Retention = RetentionDays.ONE_WEEK,
RemovalPolicy = RemovalPolicy.DESTROY,
});
((CfnStage)stage.Node.DefaultChild!).AccessLogSettings = new CfnStage.AccessLogSettingsProperty
{
DestinationArn = accessLogs.LogGroupArn,
Format = "{\"requestId\":\"$context.requestId\",\"caller\":\"$context.identity.caller\",\"route\":\"$context.routeKey\",\"status\":\"$context.status\",\"integrationError\":\"$context.integrationErrorMessage\"}",
};
new CfnOutput(this, "ApiUrl", new CfnOutputProps { Value = api.ApiEndpoint });
new CfnOutput(this, "InternalAlbDns", new CfnOutputProps { Value = service.LoadBalancer.LoadBalancerDnsName });
}
}using Amazon.CDK;
using Cdklabs.CdkNag;
using Harbourline.Lab46.Infra;
var app = new App();
var stack = new PrivateContainerApiStack(app, "hl-m04-l6", new StackProps
{
Env = new Amazon.CDK.Environment { Region = "us-east-1" },
});
Tags.Of(app).Add("Project", "cea-lab");
Tags.Of(app).Add("Lab", "m04-l6");
Tags.Of(app).Add("Environment", "learn");
Tags.Of(app).Add("Owner", (string?)app.Node.TryGetContext("owner") ?? "unknown");
// cdk-nag v3: the pack is a CDK validation plugin, and findings are acknowledged with the CDK Validations API.
Validations.Of(app).AddPlugins(new AwsSolutionsChecks(app, new NagPackProps { Verbose = true }));
Validations.Of(stack).Acknowledge(new[]
{
new Acknowledgment { Id = "AwsSolutions-ELB2", Reason = "One-hour lab; ALB access logs need an S3 bucket and are covered in API monitoring." },
new Acknowledgment { Id = "AwsSolutions-ECS4", Reason = "Container Insights adds metric cost; enabled in production." },
new Acknowledgment { Id = "AwsSolutions-IAM5", Reason = "CDK-generated execution role wildcard for log streams." },
});
app.Synth();Complete code
using System.Net;
using Microsoft.AspNetCore.HttpOverrides;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
builder.Services.AddHealthChecks();
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownIPNetworks.Add(System.Net.IPNetwork.Parse("10.40.0.0/16"));
});
var app = builder.Build();
app.UseForwardedHeaders();
app.UseExceptionHandler();
app.UseStatusCodePages();
app.MapHealthChecks("/health/live");
app.MapHealthChecks("/health/ready");
app.MapGet("/v1/reconciliation/summary", (DateOnly? bookingDate, HttpContext http, ILogger<Program> log) =>
{
if (bookingDate is null || bookingDate > DateOnly.FromDateTime(DateTime.UtcNow))
{
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["bookingDate"] = ["Provide a bookingDate (yyyy-MM-dd) that is not in the future."],
});
}
var correlationId = http.Request.Headers["X-Correlation-Id"].FirstOrDefault() ?? http.TraceIdentifier;
log.LogInformation("Reconciliation summary for {BookingDate} requested by {RemoteIp} ({CorrelationId})",
bookingDate, http.Connection.RemoteIpAddress, correlationId);
var summary = new ReconciliationSummary(
BookingDate: bookingDate.Value,
Currency: "GBP",
LedgerTotal: 1_284_550.75m,
CoreBankingTotal: 1_284_550.75m,
PostingsCompared: 18_204,
Breaks: 0);
http.Response.Headers["X-Correlation-Id"] = correlationId;
return Results.Ok(summary);
});
app.Run();
internal sealed record ReconciliationSummary(
DateOnly BookingDate, string Currency, decimal LedgerTotal, decimal CoreBankingTotal, int PostingsCompared, int Breaks);FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY Harbourline.Reconciliation.Api.csproj .
RUN dotnet restore
COPY . .
RUN dotnet publish -c Release -o /app --no-restore
FROM mcr.microsoft.com/dotnet/aspnet:10.0
WORKDIR /app
COPY --from=build /app .
USER $APP_UID
ENV ASPNETCORE_HTTP_PORTS=8080
EXPOSE 8080
ENTRYPOINT ["dotnet", "Harbourline.Reconciliation.Api.dll"]The project file is the standard dotnet new web output (net10.0, Nullable and TreatWarningsAsErrors enabled); add a .dockerignore with bin/ and obj/.
Code explained line by line
AddProblemDetails()+UseExceptionHandler()— errors leave the container as RFC 9457 problem documents, and API Gateway passes them through unchanged.ForwardedHeadersOptionswithKnownIPNetworks= the VPC CIDR — trustsX-Forwarded-Foronly from the ALB's private addresses, so the logged client IP is real and cannot be spoofed by an outside caller.MapHealthChecks("/health/live")/("/health/ready")— liveness and readiness; the ALB target group checks/health/ready. In the full service, readiness includes the core banking connection.DateOnly? bookingDate— minimal APIs bind?bookingDate=2026-11-16toDateOnly; a missing or future date gets a 400 validation problem.X-Correlation-Id— reused if the caller sent one, otherwise the trace identifier; echoed back for support tickets.ReconciliationSummarywithdecimaltotals — money staysdecimal.- Dockerfile: multi-stage build, runs as the non-root
$APP_UIDuser that the .NET images provide, listens on 8080. - CDK
VpcwithAvailabilityZones = azs— you choose zone names that map to VPC-link-supported zone IDs; one NAT gateway keeps the cost down. AddFlowLog— VPC flow logs with one-week retention, which banks expect on every VPC.ApplicationLoadBalancedFargateServicewithPublicLoadBalancer = falseandOpenListener = false— an internal ALB whose security group has no open ingress rule.ConfigureHealthCheck+deregistration_delay— readiness-based routing and quicker deployments.linkSgwithAllowAllOutbound = falseandConnections.AllowFrom(linkSg, Port.Tcp(80))— adds exactly one ingress rule on the ALB SG and the matching egress rule on the link SG.VpcLink— a V2 link in the private subnets with that SG; immutable once created.HttpIamAuthorizeras the default authorizer — every route requires a SigV4 signature from an IAM principal allowed to callexecute-api:Invoke.HttpAlbIntegration(..., service.Listener, VpcLink = vpcLink)— private integration to the listener ARN using payload format 1.0 (the only format for private integrations).HttpStagethrottle 10 rps / burst 20 and JSON access logs including$context.identity.caller— who called, what happened, why it failed.
Security considerations
⚠ Learning shortcut — not for production
The ALB listens on HTTP port 80 inside the VPC, tasks pull images through a NAT gateway, and ALB access logs are suppressed. Production: HTTPS listener with an ACM certificate and secureServerName on the integration, VPC interface endpoints for ECR, CloudWatch Logs and Secrets Manager (plus the S3 gateway endpoint) so tasks need no internet route, ALB access logs to an encrypted S3 bucket, Container Insights, and egress filtering.
- IAM authorization is the right default for internal machine callers: no secrets to distribute, CloudTrail-quality identities in access logs, and policies scoped to
arn:aws:execute-api:us-east-1:<account>:<api-id>/*/GET/v1/reconciliation/*. - Never expose the backend. If you ever use pattern D (gateway to a public ALB), anyone who discovers the ALB URL can bypass throttling and authorization.
- Security groups reference security groups, never CIDRs of the whole VPC.
- Encryption. Data between API Gateway and the VPC link travels on AWS's network, but your security policy may require TLS to the target; test that requirement with your security team, and note that many bank standards require it.
- Data protection. Reconciliation summaries are aggregate figures; if a route returns customer-level postings, apply UK GDPR minimisation and agree log retention with your DPO.
Banking use case
Harbourline deploys hl-recon-internal exactly like this lab, with an HTTPS listener, VPC endpoints instead of NAT, and a second VPC link in a separate account for the EU subsidiary. The operations portal's backend role has execute-api:Invoke on GET /v1/reconciliation/* only; the nightly job role also has POST /v1/reconciliation/runs. When the security team asks "who can reach this service?", the answer is one IAM policy, one security group rule and one access log group.
Common mistakes
- VPC link stuck in
FAILED/PENDING. Usually a subnet in an unsupported AZ (use1-az3) or a quota hit. Recreate with supported subnets (links are immutable). - 503 from the gateway, no requests in the app. No healthy targets: wrong health-check path, container port mismatch or task SG not allowing the ALB.
- Opening the ALB SG to
10.0.0.0/8"to make it work". Allow the VPC link SG only. - A VPC link that sat idle for two months. It goes
INACTIVE; the first requests fail while ENIs are re-created. Monitor link status for rarely used APIs. - Expecting WAF on the HTTP API. Not supported; use pattern C (REST API) or put WAF on an ALB in pattern A.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
403 Missing Authentication Token / Forbidden | Unsigned request or IAM policy lacks execute-api:Invoke | Sign with SigV4; check the resource ARN in the policy |
503 Service Unavailable | ALB has no healthy targets, or VPC link inactive | Check target health and VPC link status |
| 504/503 after about 30 s | Integration timeout | Speed up the backend or go asynchronous |
| Health checks failing | App listens on 80 but target group uses 8080, or /health/ready returns 503 | Align ASPNETCORE_HTTP_PORTS, container port and target group |
Tasks stuck in PENDING / image pull errors | No route to ECR (NAT missing or endpoints absent) | Check private route table → NAT, or add ECR/S3 endpoints |
cdk deploy fails building the image | Docker in Windows-containers mode or not running | Switch Docker Desktop to Linux containers |
Cost and cleanup
Label: cost: credits. Running the stack for one hour in us-east-1 costs roughly:
| Resource | One hour |
|---|---|
| Internal ALB (1 h + under 1 LCU) | about USD 0.03 |
| NAT gateway (1 h + under 1 GB) + its public IPv4 | about USD 0.05–0.10 |
| Two Fargate tasks, 0.25 vCPU / 0.5 GB, x86 | about USD 0.025 |
| HTTP API, CloudWatch Logs, ECR asset storage, VPC link | under USD 0.01 |
| Total | about USD 0.10–0.20 if destroyed within the hour |
Leaving it running for a month would cost roughly USD 70–90, mostly ALB and NAT. Free alternative: the Docker Compose tab reproduces the same "only the gateway is published" topology locally, and the CDK stack is a design-only artefact you can cdk synth without deploying.
cdk destroy --profile learn-sandbox --force
# Check for leftovers: VPC links, ENIs and load balancers
aws apigatewayv2 get-vpc-links --profile learn-sandbox --region us-east-1
aws elbv2 describe-load-balancers --profile learn-sandbox --region us-east-1 --query "LoadBalancers[].LoadBalancerName"
aws ec2 describe-nat-gateways --filter Name=state,Values=available --profile learn-sandbox --region us-east-1
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab \
--profile learn-sandbox --region us-east-1The CDK asset image stays in the cdk-*-container-assets-* ECR repository from bootstrapping (cents per month); delete the image there if you want zero storage.
Exercises
- 🟢 Guided: run the Compose stack, then deploy the CDK stack, call it with and without SigV4, stop one task, and destroy everything inside one hour.
- 🟡 Challenge: replace the NAT gateway with VPC endpoints (ECR API, ECR Docker, CloudWatch Logs as interface endpoints; S3 as a gateway endpoint) and
PRIVATE_ISOLATEDsubnets. Recalculate the hourly cost. - 🔴 Live problem: the security team requires AWS WAF and per-partner quotas on the reconciliation API so that two external auditors can call it. Redesign: which API type, which VPC link, what changes in the security groups, and what you tell the auditors about authentication.
Assignment
Add a docs/network-path.md to your portfolio repository with the Mermaid security-boundary diagram for your own container API, a table of every security group rule (source, destination, port, reason), the one-hour cost estimate, and the teardown commands. Include a screenshot-free description of how you proved the backend is not reachable from the internet.
Solutions
Without a signature the HTTP API returns 403 before touching the VPC. With curl --aws-sigv4 it returns the JSON summary. Stopping a task causes the ALB to mark it unhealthy (or deregister it); the other task keeps serving, and ECS starts a replacement because DesiredCount = 2. cdk destroy removes the VPC link first, then the ALB, service and VPC.
Interface endpoints cost about USD 0.01 per AZ per hour each (plus data). Three interface endpoints across two AZs = 6 × 0.01 = USD 0.06 per hour, slightly more than one NAT gateway for a short lab, but in production they remove the internet path entirely, which is usually the deciding factor. Set SubnetType.PRIVATE_ISOLATED, NatGateways = 0, and add vpc.AddInterfaceEndpoint for EcrDockerEndpoint, Ecr, CloudWatchLogs plus vpc.AddGatewayEndpoint for S3 (image layers are served from S3).
Move to a Regional REST API (WAF and usage plans exist only there) with a VPC link V2 pointing straight at the existing internal ALB — no NLB required since November 2025. Security groups stay the same pattern: the new link's SG is the only source the ALB accepts. Authentication: API keys only identify the auditors for quotas; real authentication is OAuth 2.0 client credentials with scopes (or mTLS on a custom domain), plus IAM if they are AWS principals. Document it in the ADR.
Knowledge check
Answer: HTTP API: ALB, NLB and AWS Cloud Map services. REST API: ALB and NLB (via integrationTarget). VPC link V1 is legacy and NLB-only.
Answer: Create a new VPC link with the new security group, repoint the integrations, then delete the old link. V2 links are immutable.
Answer: VPC link V2 supports specific zone IDs (not use1-az3), and zone names map to different IDs per account.
Answer: The token signature against a JWKS URL, mandatory iss and exp, nbf/iat when present, and up to 10 configured claims. It requires an HTTPS listener and RS256 tokens; the JWKS must be at most 150 KB and 10 keys.
Answer: Amazon ECS Express Mode (or ECS on Fargate directly). App Runner closed to new customers on 2026-04-30.
Interview questions
- "How do you expose a private container service through API Gateway?" — Internal ALB or NLB in private subnets, VPC link V2 with its own security group, ALB SG allowing only the link SG, IAM or JWT authorization and throttling on the API, access logs, and TLS to the target if policy requires it.
- "When would you not use API Gateway in front of containers?" — One or two high-volume APIs without per-client plans: ALB with WAF and JWT verification is simpler and cheaper per request.
- "What changed for REST API private integrations in 2025?" — VPC link V2 can target ALBs directly, so the NLB-in-front-of-ALB pattern is no longer needed; V1 is legacy.
- "How do you prove a backend is not internet-reachable?" — Internal scheme, no public IPs, security groups that reference only the link SG, route tables, and a negative test from outside; Reachability Analyzer for evidence.
- "What replaced App Runner for new projects?" — ECS Express Mode, which provisions Fargate, an HTTPS ALB, a certificate, scaling and canary deployments in your account.
Certification practice
A bank runs an API on ECS Fargate behind an internal Application Load Balancer. It must be exposed to partners with AWS WAF and per-partner quotas, and the ALB must stay internal. Which solution has the least operational overhead?
A. HTTP API with a VPC link to the ALB and WAF on the HTTP API stage B. Regional REST API with a VPC link V2 targeting the ALB, usage plans per partner, and WAF on the REST API stage C. Make the ALB internet-facing and attach WAF to it, with usage plans on the ALB D. REST API with a VPC link V1 to a new NLB that forwards to the ALB
Answer: B. REST APIs support WAF and usage plans, and VPC link V2 reaches ALBs directly. A: HTTP APIs cannot have WAF. C: ALBs have no usage plans, and the ALB must stay internal. D works but adds an NLB to operate; it is the legacy pattern.
An auditor finds that an internal ALB behind an API Gateway VPC link allows inbound port 80 from 10.0.0.0/8. What is the most precise fix?
A. Allow inbound only from the VPC CIDR B. Allow inbound only from the security group attached to the VPC link C. Remove all inbound rules; VPC links bypass security groups D. Add a network ACL denying 10.0.0.0/8
Answer: B. Referencing the VPC link's SG allows exactly the API Gateway ENIs. A still allows every workload in the VPC. C is false: the ALB SG is evaluated. D would also block the VPC link.
After a deployment, an HTTP API with a private ALB integration returns 503 for every request. The ECS service shows tasks repeatedly starting and stopping. What should the developer check first?
A. The HTTP API payload format version B. The target group health check path and port versus the container's listening port C. The Lambda function's reserved concurrency D. The API's CORS configuration
Answer: B. Failing health checks leave the ALB without healthy targets (503) and make ECS replace tasks. A is fixed at 1.0 for private integrations. C is irrelevant. D affects browsers only.
Completion checklist
- I can draw the four publishing patterns and say when each fits
- I ran the free Compose version and saw that only the gateway is published
- I deployed, tested (403 unsigned, 200 signed) and destroyed the CDK stack within an hour
- I can list every security group rule on the private path and why it exists
- The tag check returned nothing after cleanup
Key takeaways
- VPC link V2 is the modern bridge for both HTTP and REST APIs; V1 (NLB only) is legacy.
- Chain security groups: link SG → ALB SG → task SG; never open CIDR ranges.
- API Gateway does not health-check; the load balancer does, and a 503 usually means no healthy targets.
- ALB + WAF + JWT verification can replace API Gateway for simple, high-volume APIs.
- App Runner is closed to new customers; ECS Express Mode or explicit ECS on Fargate replace it.
Further reading
- Set up VPC links V2 in API Gateway
- Set up a private integration (REST APIs)
- Create private integrations for HTTP APIs
- Build scalable REST APIs using API Gateway private integration with ALB
- Verify JWTs using an Application Load Balancer
- Resources created by Amazon ECS Express Mode services
- Announcing Amazon ECS Express Mode
- Elastic Load Balancing pricing · Amazon VPC pricing · AWS Fargate pricing
- Related: Service-to-service communication · Module 2: Networking
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.
Lambda integrations for API Gateway
Connect .NET 10 Lambda functions to REST and HTTP APIs: proxy vs custom integrations, payload format 1.0 vs 2.0, ASP.NET Core on Lambda, error mapping, timeouts and cold starts, then build Lab 4.2 (HTTP API + Lambda + Cognito JWT authorizer with scopes).
Lambda authorizers: custom authorisation in front of your API
Write, test and deploy a C# Lambda authorizer that validates JWTs with cached JWKS keys, returns cache-safe IAM policies and passes the customer ID to the backend.