Skip to Content
Cloud Engineering Academy
4. API Development & Integration

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.

advanced⏱ 2 h 🟡 Low costSAA-C03DVA-C03SCS-C03

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

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

PatternPathGood forWatch out
A. Public ALB, no API GatewayInternet → ALB (+ WAF, + JWT verification) → FargateOne API, browser apps, lowest moving partsNo usage plans, request validation or API keys; ALB bills hourly
B. HTTP API + VPC linkInternet or internal caller → HTTP API → VPC link → private ALB / NLB / Cloud Map → FargateCheap per request, JWT or IAM auth, internal APIsNo WAF on the HTTP API, no caching or request validation
C. REST API + VPC linkClient → (WAF) REST API → VPC link → private ALB or NLB → FargatePublic banking APIs needing WAF, usage plans, validationHigher request price; VPC link V2 for ALB since Nov 2025
D. REST/HTTP API → public ALB URLClient → API Gateway → internet → public ALBRarelyThe backend is internet-reachable and can be called around the gateway
VPC link V2VPC link V1 (legacy)
Used byHTTP APIs and REST APIsREST APIs only
TargetsALB, NLB, AWS Cloud Map (Cloud Map: HTTP APIs only)NLB only
Created withaws apigatewayv2 create-vpc-linkaws apigateway create-vpc-link
Security groupsYes, chosen at creationNot on the link itself
MutabilitySubnets and security groups cannot be changed; create a new link—
Idle behaviourAfter 60 days without traffic it becomes INACTIVE and its ENIs are deleted; the next request triggers re-provisioning that takes minutes—
OwnershipLink, load balancer and API in the same accountSame

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/0 anywhere 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.example in 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, secureServerName in CDK) or an https:// 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/live for 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)

ItemPrice
Application Load BalancerUSD 0.0225 per hour + USD 0.008 per LCU-hour
Network Load BalancerUSD 0.0225 per hour + USD 0.006 per NLCU-hour
NAT gatewayUSD 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/x86about USD 0.0405 per vCPU-hour + USD 0.0044 per GB-hour (ARM: 0.0324 + 0.0036), per second, 1-minute minimum
HTTP API requestsUSD 1.00 per million
VPC link V2No separate charge found on the API Gateway pricing page ⚠ VERIFY

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
App Service / Container Apps with a private endpointECS Fargate service behind an internal ALBYou 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 linkAPI 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 BalancerNLB security groups only if attached at creation
Front Door with Private Link originsCloudFront VPC origins or API Gateway + VPC linkDifferent products, same "no public backend" goal
Azure Private DNS zonesRoute 53 private hosted zonesAssociated 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

  1. 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.)
  2. API Gateway → APIs → hl-m04-l6-recon-api → Integrations: integration type Private resource, target ALB listener, VPC link hl-m04-l6-link.
  3. 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.
  4. EC2 → Network Interfaces: filter by the VPC link security group to see the ENIs API Gateway created.
  5. 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 table

Building 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_IAM

REST 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

infra/Harbourline.Lab46.Infra/PrivateContainerApiStack.cs
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 });
    }
}
infra/Harbourline.Lab46.Infra/Program.cs
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

src/Harbourline.Reconciliation.Api/Program.cs
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);
src/Harbourline.Reconciliation.Api/Dockerfile
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

  1. AddProblemDetails() + UseExceptionHandler() — errors leave the container as RFC 9457 problem documents, and API Gateway passes them through unchanged.
  2. ForwardedHeadersOptions with KnownIPNetworks = the VPC CIDR — trusts X-Forwarded-For only from the ALB's private addresses, so the logged client IP is real and cannot be spoofed by an outside caller.
  3. 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.
  4. DateOnly? bookingDate — minimal APIs bind ?bookingDate=2026-11-16 to DateOnly; a missing or future date gets a 400 validation problem.
  5. X-Correlation-Id — reused if the caller sent one, otherwise the trace identifier; echoed back for support tickets.
  6. ReconciliationSummary with decimal totals — money stays decimal.
  7. Dockerfile: multi-stage build, runs as the non-root $APP_UID user that the .NET images provide, listens on 8080.
  8. CDK Vpc with AvailabilityZones = azs — you choose zone names that map to VPC-link-supported zone IDs; one NAT gateway keeps the cost down.
  9. AddFlowLog — VPC flow logs with one-week retention, which banks expect on every VPC.
  10. ApplicationLoadBalancedFargateService with PublicLoadBalancer = false and OpenListener = false — an internal ALB whose security group has no open ingress rule.
  11. ConfigureHealthCheck + deregistration_delay — readiness-based routing and quicker deployments.
  12. linkSg with AllowAllOutbound = false and Connections.AllowFrom(linkSg, Port.Tcp(80)) — adds exactly one ingress rule on the ALB SG and the matching egress rule on the link SG.
  13. VpcLink — a V2 link in the private subnets with that SG; immutable once created.
  14. HttpIamAuthorizer as the default authorizer — every route requires a SigV4 signature from an IAM principal allowed to call execute-api:Invoke.
  15. HttpAlbIntegration(..., service.Listener, VpcLink = vpcLink) — private integration to the listener ARN using payload format 1.0 (the only format for private integrations).
  16. HttpStage throttle 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

SymptomLikely causeFix
403 Missing Authentication Token / ForbiddenUnsigned request or IAM policy lacks execute-api:InvokeSign with SigV4; check the resource ARN in the policy
503 Service UnavailableALB has no healthy targets, or VPC link inactiveCheck target health and VPC link status
504/503 after about 30 sIntegration timeoutSpeed up the backend or go asynchronous
Health checks failingApp listens on 80 but target group uses 8080, or /health/ready returns 503Align ASPNETCORE_HTTP_PORTS, container port and target group
Tasks stuck in PENDING / image pull errorsNo route to ECR (NAT missing or endpoints absent)Check private route table → NAT, or add ECR/S3 endpoints
cdk deploy fails building the imageDocker in Windows-containers mode or not runningSwitch Docker Desktop to Linux containers

Cost and cleanup

Label: cost: credits. Running the stack for one hour in us-east-1 costs roughly:

ResourceOne hour
Internal ALB (1 h + under 1 LCU)about USD 0.03
NAT gateway (1 h + under 1 GB) + its public IPv4about USD 0.05–0.10
Two Fargate tasks, 0.25 vCPU / 0.5 GB, x86about USD 0.025
HTTP API, CloudWatch Logs, ECR asset storage, VPC linkunder USD 0.01
Totalabout 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-1

The 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_ISOLATED subnets. 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

Knowledge check

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

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

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