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

Lab 3.4: run the Accounts API on Lambda (dotnet10) behind an HTTP API

Publish the same ASP.NET Core Accounts API for linux-arm64, deploy it to the Lambda dotnet10 runtime behind an API Gateway HTTP API, replay a real HTTP API event, read cold starts from the REPORT lines, and compare memory sizes, ReadyToRun and SnapStart.

intermediate⏱ 1 h 15 min🟢 FreeDVA-C03SAA-C03

Assumes: .NET 10 LTS · Lambda dotnet10 (arm64) · Amazon.Lambda.AspNetCoreServer.Hosting 2.2.1 · Amazon.CDK.Lib 2.277.0 · Terraform 1.14 with AWS provider 6.x · AWS CLI v2 · Region us-east-1 · labs/m03-accounts-api. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lab you can:

  • Publish an ASP.NET Core app framework-dependent for linux-arm64 and run it, unchanged, on the Lambda dotnet10 managed runtime.
  • Explain how AddAWSLambdaHosting lets one binary serve Kestrel on Beanstalk and ECS and API Gateway events on Lambda.
  • Deploy a function and an HTTP API with CDK (C#) or Terraform, with least-privilege roles, log retention and a throttle.
  • Replay an API Gateway payload 2.0 event with aws lambda invoke, and read Init Duration from the REPORT log lines and with a Logs Insights query.
  • Run a small, honest cold-start experiment (memory size, ReadyToRun, SnapStart) and say what you can and cannot conclude from it.
  • Tear everything down and prove nothing is left.

Prerequisites

  • Lambda with C# — the four programming models and the cold-start table this lab puts to work
  • Configuration done right — how ParameterStore:Path becomes configuration
  • Lab 3.2 is helpful (the same API, in a container); Lab 3.3 is not required
  • AWS CLI v2 signed in: aws sso login --profile learn-sandbox; export AWS_PROFILE=learn-sandbox AWS_REGION=us-east-1
  • .NET 10 SDK, Node.js LTS and the CDK CLI (npm install -g aws-cdk), and an account bootstrapped once (cdk bootstrap aws://<account>/us-east-1)

Why this matters in banking

Harbourline's partner and back-office APIs have very uneven traffic: a trickle overnight, a burst when a batch job or a partner sync starts. A host that costs nothing when idle and scales to the burst is attractive, but the price is the cold start: the first request after a quiet period, or each new concurrent environment, pays for starting the runtime and your application. An engineer who has never measured one will either dismiss Lambda ("too slow") or adopt it blindly ("serverless is free"). This lab gives you your own numbers, from your own code, so the architecture decision in the module project rests on evidence.

The idea in plain language

Lambda runs your code only when a request arrives, in a short-lived sandbox called an execution environment. The first request to a new environment pays an init phase (start the .NET runtime, load assemblies, run your Program.cs up to the point where the app is ready). Later requests to the same environment skip it and are warm. When traffic drops, environments are discarded; when it rises, more are created, and each one is a cold start.

An HTTP API (API Gateway v2) is the front door: it terminates TLS, applies throttling, and turns each HTTP request into a JSON event (payload format 2.0) that it hands to the function. Amazon.Lambda.AspNetCoreServer.Hosting converts that event into an ordinary HttpContext and your endpoints run as usual, so the same compiled app also runs on Kestrel behind nginx (Beanstalk) or an ALB (Fargate).

Analogy: a Fargate service is a branch with a cashier always at the counter, paid by the hour. Lambda is a pop-up counter staffed only when a customer arrives. The first customer after a quiet spell waits while the counter is set up (cold start); the next ones are served immediately (warm) until the counter is packed away again.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalent in this labWhat's different
Azure Functions (isolated worker) with the ASP.NET Core integrationLambda dotnet10 + AddAWSLambdaHostingYou choose the event source (HttpApi, RestApi, ALB); the function handler string is the assembly name
Functions Consumption plan cold startLambda init phase (Init Duration)Reported on every cold REPORT line; memory also sets CPU
Premium plan pre-warmed instancesProvisioned concurrency (not used here)Billed per hour configured
API Management consumption tierAPI Gateway HTTP APICheaper and simpler than REST APIs; JWT authorizers built in, no usage plans or API keys
Application Insights live metricsCloudWatch Logs, REPORT lines, Logs InsightsYou query log fields such as @initDuration
Deployment slotsVersions and aliasesSnapStart and canary shifts work on published versions only

Architecture

Security boundary view. The internet reaches only the HTTP API. The function has no inbound network path other than the API's invoke permission. The function's execution role allows three things: write its own log group, read one table (and its indexes), read one Parameter Store path. There is no VPC attachment, so there is no NAT gateway to pay for and no ENI start-up delay; the price is that the function cannot reach private resources (a Module 2 decision when you need RDS).

What is already in the lab folder

You write no application code in this lab. Everything below is in labs/m03-accounts-api and is covered by its tests.

FileRole in this lab
src/Harbourline.Accounts.Api/Program.csLine builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi) makes the app Lambda-aware
src/.../Harbourline.Accounts.Api.csprojOutputType is Exe and SelfContained is false: Lambda starts the assembly as an executable on the managed runtime
infra/cdk/.../LambdaStack.csCDK stack HlM03-Lambda: log groups, function, HTTP API, throttling, cdk-nag acknowledgments
infra/terraform/lambda.tfThe same host in Terraform (names end in -tf)
events/get-account-v2.jsonA sample HTTP API payload 2.0 event for aws lambda invoke
tests/.../ConfigurationAndLambdaTests.csReplays that event's method, path and headers through the real pipeline
tools/latency-probe.csFirst-request time plus p50/p95/p99

Step-by-step

All commands run from labs/m03-accounts-api in Git Bash unless noted.

Run the tests (no AWS needed)

dotnet test --solution AccountsApi.slnx

Expected: 71 passed, 1 skipped (the skipped one is the optional real-AWS smoke test). One of the passing tests, LambdaEventTests, loads events/get-account-v2.json, builds the request it describes and sends it through the real app. If you later edit the route, that test tells you the sample event is stale before Lambda does.

Deploy the shared table, seed it and create the key parameter

export AWS_PROFILE=learn-sandbox AWS_REGION=us-east-1
cd infra/cdk && cdk deploy HlM03-Shared -c owner=<your-name> && cd ../..
for f in seed/batch-*.json; do aws dynamodb batch-write-item --request-items "file://$f"; done
aws ssm put-parameter --name /hl-m03/accounts-api/Pseudonymisation/Key --type SecureString \
  --value "$(openssl rand -hex 32)" \
  --tags Key=Project,Value=cea-lab Key=Lab,Value=m03-accounts-api Key=Environment,Value=learn Key=Owner,Value=<your-name>

Each batch-write-item should print "UnprocessedItems": {}. The parameter is required: outside Development the API refuses to start without a pseudonymisation key, and the function would die in its init phase with a message that names the missing setting.

Publish for Lambda

dotnet publish src/Harbourline.Accounts.Api -c Release -r linux-arm64 --self-contained false -o publish/lambda
du -sh publish/lambda

-r linux-arm64 selects the architecture of the function (Graviton). --self-contained false means the runtime is not in your package: Lambda provides dotnet10, which keeps the package small and lets AWS patch the runtime for you. The folder is a few tens of megabytes, far below the 250 MB unzipped limit for a function package.

Deploy the Lambda stack

cd infra/cdk
cdk diff HlM03-Lambda -c owner=<your-name>
cdk deploy HlM03-Lambda -c owner=<your-name>
cd ../..

Read the cdk diff output before approving: you should see one function, its execution role with three statements, two log groups, the HTTP API with its integration and stage, and the invoke permission. The output HlM03-Lambda.ApiUrl is the endpoint. If CDK complains that it is skipping HlM03-Lambda, the publish/lambda folder does not exist yet (step 3).

Call it two ways

API=$(aws cloudformation describe-stacks --stack-name HlM03-Lambda \
  --query "Stacks[0].Outputs[?OutputKey=='ApiUrl'].OutputValue" --output text)

# 1. Through the HTTP API, like a client would
curl -i $API/v1/accounts/ACC-0000000001
curl -i $API/health/ready

# 2. Straight into the function with the sample event, skipping API Gateway
aws lambda invoke --function-name hl-m03-accounts-api \
  --payload fileb://events/get-account-v2.json out.json
cat out.json

The second call returns an HTTP response expressed as JSON: statusCode, headers, body (a string) and isBase64Encoded. That is the contract API Gateway expects from the function; AspNetCoreServer builds it from what your endpoint wrote. Look for "statusCode":200 and the header x-correlation-id that the sample event supplied.

Read the logs and the first cold start

aws logs tail /hl-m03/accounts-api/lambda --since 15m

Find the lines that start with REPORT. A cold request shows an Init Duration; warm ones do not. The application's own lines are compact JSON (Serilog), and request lines carry CorrelationId. Now ask Logs Insights for the pattern over the last hour:

QID=$(aws logs start-query --log-group-name /hl-m03/accounts-api/lambda \
  --start-time $(date -d '-1 hour' +%s) --end-time $(date +%s) \
  --query-string 'filter @type = "REPORT" | stats count() as invocations, count(@initDuration) as coldStarts, avg(@initDuration) as avgInitMs, max(@initDuration) as maxInitMs, avg(@duration) as avgMs, max(@maxMemoryUsed / 1000 / 1000) as maxMemMB' \
  --query queryId --output text)
sleep 5
aws logs get-query-results --query-id $QID

@initDuration, @duration and @maxMemoryUsed are fields Logs Insights discovers automatically in Lambda REPORT lines. maxMemMB tells you whether 1024 MB is generous or tight.

Measure: cold first request, then warm percentiles

# Wait about 15 minutes of silence (or redeploy) so the first request is a cold start.
dotnet run tools/latency-probe.cs -- $API 200

Expect a first request several times slower than the warm p50, and warm numbers dominated by network round trip to us-east-1 from where you sit. The probe is sequential on purpose: it measures latency, not throughput, and cannot accidentally load-test (and bill) the function. Write down: first request, p50, p95, p99, and the Init Duration of the cold REPORT line. The first request time includes API Gateway, TLS and your network; Init Duration is only the function's start-up: you will see both, and they differ.

Experiment A: memory is CPU

For .NET, more memory means more CPU, so the init phase and JIT compilation finish sooner. Each memory change creates fresh environments, so the next request is cold.

for MEM in 512 1024 2048; do
  aws lambda update-function-configuration --function-name hl-m03-accounts-api --memory-size $MEM > /dev/null
  aws lambda wait function-updated --function-name hl-m03-accounts-api
  echo "== $MEM MB =="
  dotnet run tools/latency-probe.cs -- $API 50 | head -2
done
aws logs tail /hl-m03/accounts-api/lambda --since 5m --filter-pattern "REPORT" | grep -E "Init Duration|Memory Size"

Put your results in a table (see "Expected output" for the shape). More memory is billed per GB-second, but if the same work finishes in less than half the time the bill can fall. The only way to know for your code is to measure, which is what you just did. After the experiment, set the memory back (--memory-size 1024) or run cdk deploy to restore the stack's definition.

Experiment B: ReadyToRun

ReadyToRun (R2R) precompiles your assemblies to native code ahead of time, so less must be JIT-compiled during start-up.

dotnet publish src/Harbourline.Accounts.Api -c Release -r linux-arm64 --self-contained false \
  -p:PublishReadyToRun=true -o publish/lambda
du -sh publish/lambda
cd infra/cdk && cdk deploy HlM03-Lambda -c owner=<your-name> && cd ../..

The package grows (native code is added next to the IL). Wait for the new version to settle, then repeat step 7 and compare Init Duration with your baseline. If the build fails with a missing runtime pack or crossgen error, your machine could not cross-compile for arm64: build inside mcr.microsoft.com/dotnet/sdk:10.0 instead ⚠ VERIFY cross-targeting from Windows x64 to linux-arm64 on your SDK version.

Experiment C (optional): SnapStart ⚠ VERIFY

SnapStart takes a snapshot of the initialised environment when you publish a version and restores new environments from it. The Lambda documentation lists ".NET 8 and later" among the supported managed runtimes, and the module treats that as including dotnet10; confirm on your function before you rely on it. Whether it works with this particular executable-assembly ASP.NET Core model (rather than a plain handler or Annotations) is also something to verify by trying it ⚠ VERIFY.

aws lambda update-function-configuration --function-name hl-m03-accounts-api \
  --snap-start ApplyOn=PublishedVersions
aws lambda wait function-updated --function-name hl-m03-accounts-api
VER=$(aws lambda publish-version --function-name hl-m03-accounts-api --query Version --output text)
aws lambda wait function-active-v2 --function-name hl-m03-accounts-api --qualifier $VER
aws lambda get-function-configuration --function-name hl-m03-accounts-api --qualifier $VER \
  --query "SnapStart"

# Invoke the PUBLISHED VERSION (SnapStart never applies to $LATEST)
aws lambda invoke --function-name hl-m03-accounts-api --qualifier $VER \
  --payload fileb://events/get-account-v2.json out.json
aws logs tail /hl-m03/accounts-api/lambda --since 5m | grep REPORT

Look for Restore Duration instead of Init Duration. The HTTP API still points at $LATEST, so this experiment invokes the version directly; wiring the API to an alias is the production step (Exercise 🟡). Delete the experiment's cost with the teardown below: each published version with SnapStart bills a snapshot-cache charge for a minimum of 3 hours.

Tear down

See Cost and cleanup. This lab is cheap, but leaving published SnapStart versions or a forgotten parameter is the sort of residue the tag check exists to catch.

AWS Console instructions

  • Function: Console → Lambda → Functions → hl-m03-accounts-api. The Configuration tab shows memory, timeout, architecture and environment variables (note there are no secrets there). Monitor → View CloudWatch logs opens the log group.
  • Test event: Test tab → create event → paste the content of events/get-account-v2.json → Test. The execution result shows the same response as aws lambda invoke.
  • Cold starts: Console → CloudWatch → Logs → Logs Insights → select /hl-m03/accounts-api/lambda → paste the query from step 6.
  • HTTP API: Console → API Gateway → APIs → hl-m03-accounts-api → Stages → $default shows the throttle; Monitor shows request counts; the access log group is under the stage's logging settings.

Expected output

$ curl -i $API/health/ready
HTTP/2 200
content-type: application/json
x-correlation-id: 1-67a3f2c1-0f1e2d3c4b5a69788796a5b4

{"status":"Healthy","checks":{"repository":"Healthy"},"durationMs":31.2}

$ dotnet run tools/latency-probe.cs -- $API 200
Target       : https://abc123.execute-api.us-east-1.amazonaws.com/v1/accounts/ACC-0000000001
First request:   (cold: several times the warm p50)
Warm requests: 200 (0 non-2xx)
  p50   ...
  p95   ...

The numbers are intentionally blank: they depend on your network, your Region distance and the day. What you should see is the shape:

SettingFirst requestInit DurationWarm p50Bill per 1M requests (compute only)
512 MB, JITslowesthighestsimilarsmallest per second, longest duration
1024 MB, JITmiddlemiddlesimilarmiddle
2048 MB, JITfastestlowestsimilarhighest per second, shortest duration
1024 MB, ReadyToRunfaster than JIT at 1024lower than JIT at 1024similarsimilar
1024 MB, SnapStartrestore time, if it works for this modelRestore Duration insteadsimilarplus cache and restore charges

Record your real figures in the project page's comparison table.

What the stack configures (and why)

Setting in LambdaStack.csPurpose
Runtime("dotnet10", RuntimeFamily.DOTNET_CORE)Named explicitly so the stack compiles on CDK versions that lack a DOTNET_10 constant (the module's known workaround) ⚠ VERIFY on your CDK version
Handler = "Harbourline.Accounts.Api"Executable-assembly model: the handler is just the assembly name, not Assembly::Type::Method
Architecture.ARM_64, MemorySize = 1024Graviton is cheaper per GB-second; 1024 MB gives .NET enough CPU for a reasonable init
Timeout = 15 sLonger than a cold start plus one DynamoDB call, shorter than anything a client would wait for
LogGroup created first, ONE_WEEK retentionA group Lambda creates itself never expires
ParameterStore__Path environment variableThe app loads /hl-m03/accounts-api/* at start-up (adds to init time)
AccountsApiPermissions.GrantReadOnlyThe same table and parameter statements as the Fargate task role and Beanstalk instance role
HTTP API with HttpLambdaIntegrationPayload 2.0, $default route and stage
Stage throttle 10 requests per second, burst 20A leaked URL cannot run up a bill; reserved concurrency is not used because new accounts often have a low concurrency quota
Access log format with integrationLatencySeparates API Gateway overhead from function time

Why the init phase includes Parameter Store

AddAwsConfigurationSources calls Parameter Store before the app starts, so every cold start pays one GetParametersByPath round trip (tens of milliseconds, plus the SDK's own first-call overhead). That is a deliberate trade: configuration is correct from the first request. If you measure and find it matters, SnapStart, the Parameters and Secrets Lambda extension, or baking non-secret settings into environment variables are the levers. Do not drop the Parameter Store read to win a benchmark.

Infrastructure as Code

The lab ships both. They create equivalent resources; do not deploy both at once unless you want to compare them.

infra/cdk/Harbourline.Accounts.Infra/LambdaStack.cs (excerpt)
var function = new Function(this, "ApiFunction", new FunctionProps
{
    FunctionName = "hl-m03-accounts-api",
    Runtime = new Runtime("dotnet10", RuntimeFamily.DOTNET_CORE),
    Handler = "Harbourline.Accounts.Api",          // assembly name
    Code = Code.FromAsset(props.PublishDirectory), // publish/lambda
    Architecture = Architecture.ARM_64,
    MemorySize = 1024,
    Timeout = Duration.Seconds(15),
    LogGroup = logGroup,
    Environment = new Dictionary<string, string>
    {
        ["ASPNETCORE_ENVIRONMENT"] = "Production",
        ["Repository__Provider"] = "DynamoDb",
        ["Repository__TableName"] = props.TableName,
        ["ParameterStore__Path"] = AccountsApiPermissions.ParameterPath,
        ["Auth__Mode"] = "Disabled",                        // ⚠ learning shortcut
        ["Auth__AllowDisabledOutsideDevelopment"] = "true", // ⚠ learning shortcut
    },
});
AccountsApiPermissions.GrantReadOnly(function.Role!, this, props.TableName);

var api = new HttpApi(this, "HttpApi", new HttpApiProps
{
    ApiName = "hl-m03-accounts-api",
    DefaultIntegration = new HttpLambdaIntegration("LambdaIntegration", function),
});

Complete code

The part of Program.cs that makes this work is one line; the rest of the file is the shared API.

src/Harbourline.Accounts.Api/Program.cs (excerpt)
builder.AddAwsConfigurationSources();                            // Parameter Store, AppConfig (optional)
builder.UsePlatformPort();                                       // Beanstalk PORT, ignored in Lambda
builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi); // does nothing outside Lambda
builder.Services.AddTrustedForwardedHeaders(builder.Configuration);

The event the lab replays:

events/get-account-v2.json (abridged)
{
  "version": "2.0",
  "routeKey": "$default",
  "rawPath": "/v1/accounts/ACC-0000000001",
  "rawQueryString": "",
  "headers": { "x-correlation-id": "lab-3-4-event-0001" },
  "requestContext": {
    "http": { "method": "GET", "path": "/v1/accounts/ACC-0000000001", "protocol": "HTTP/1.1", "sourceIp": "203.0.113.10" },
    "requestId": "lab-3-4-request",
    "stage": "$default"
  },
  "isBase64Encoded": false
}

And the test that keeps it honest:

tests/Harbourline.Accounts.Api.Tests/ConfigurationAndLambdaTests.cs (excerpt)
public class LambdaEventTests(AccountsApiFactory factory) : IClassFixture<AccountsApiFactory>
{
    [Fact]
    public async Task The_sample_http_api_event_describes_a_request_the_api_answers_with_200()
    {
        var file = Path.Combine(AppContext.BaseDirectory, "events", "get-account-v2.json");
        using var json = JsonDocument.Parse(await File.ReadAllTextAsync(file, Ct));
        var root = json.RootElement;
        // ... build method, path and query from the event, copy the correlation header ...
        var response = await factory.CreateClient().SendAsync(request, Ct);

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        Assert.Equal("lab-3-4-event-0001", response.Headers.GetValues("X-Correlation-ID").Single());
    }
}

Note what this test does not prove: it does not run the Lambda runtime or the event translator. That part is the package's job, and you verify it for real in step 5 with aws lambda invoke.

Code explained line by line

  1. AddAWSLambdaHosting(LambdaEventSource.HttpApi) registers a replacement for Kestrel only when the environment variable AWS_LAMBDA_FUNCTION_NAME is present. Locally and in containers it is a no-op, which is why one binary serves three hosts.
  2. LambdaEventSource.HttpApi selects payload format 2.0 parsing. Use RestApi for REST APIs and ApplicationLoadBalancer for an ALB target group; a mismatch produces 500s with a deserialisation error in the logs.
  3. OutputType Exe in the project file makes the build produce a runnable assembly. With the dotnet10 managed runtime and Handler = "Harbourline.Accounts.Api", Lambda starts that assembly, which opens the Lambda runtime loop instead of listening on a port.
  4. AddAwsConfigurationSources runs before builder.Build(), so it happens in the init phase. optional: false means a failed Parameter Store call stops the start-up, which is what you want for a security-relevant key.
  5. UsePlatformPort only reads the PORT variable. Lambda sets none, so it does nothing.
  6. The AddAWSService<IAmazonDynamoDB> client is a singleton. In Lambda this matters more than elsewhere: it is created once per environment and reused by every invocation that environment serves.
  7. AddSerilog(... WriteTo.Console(RenderedCompactJsonFormatter)) writes JSON lines to stdout; Lambda forwards stdout to the function's log group.
  8. CorrelationIdMiddleware prefers a safe X-Correlation-ID header (the event supplies one) and otherwise uses the Root= part of X-Amzn-Trace-Id.

Security considerations

⚠ Learning shortcut — not for production

The HTTP API has no authorizer and the app runs with authentication disabled through an explicit override, so anyone with the URL can read fictional accounts. The stage throttles at 10 requests per second so a leaked URL cannot run up a bill, and the stack is destroyed the same hour. Production: a JWT authorizer (Cognito) on the API plus Auth__Mode=Cognito in the app (defence in depth), the integration pointed at an alias, AWS WAF in front where the API type supports it, code signing for packages, and a per-function role reviewed like any other permission set.

  • The execution role is the application's identity. There are no keys in the package or environment. Check it: aws iam list-role-policies on the function's role shows statements for one table and one parameter path only.
  • Environment variables are visible to anyone with lambda:GetFunctionConfiguration. They hold names and switches here, never secrets. Lab 3.5 puts the key in Parameter Store and shows the Secrets Manager route.
  • Throttle and concurrency are cost controls and security controls. A denial-of-wallet attack needs no vulnerability, only a public URL.
  • Logs contain what you log. The API logs a pseudonymous customer reference, never the raw id. Retention is seven days here; your bank's records policy decides the real figure.
  • Runtime patching. Lambda patches the dotnet10 runtime for you; you still own NuGet updates. Track the runtime's deprecation date (2028-11-14 for dotnet10) in your backlog.

Banking use case

Harbourline's overnight reconciliation partner calls the Accounts API in a burst of about two thousand requests between 02:00 and 02:10 and almost never otherwise. Running a Fargate task and an ALB for ten busy minutes a day costs the same as running them all day. On Lambda the bank pays for those ten minutes, and the only visible cost is a few slow first requests at 02:00. The team decides whether that is acceptable by reading their own Init Duration figures from a lab like this, and by checking the partner's client timeout, not by quoting a blog post.

Common mistakes

  • Publishing for the wrong architecture → Runtime.InvalidEntrypoint → publish with -r linux-arm64 when the function is arm64.
  • Zipping the folder instead of its contents (when deploying by hand) → handler not found → files must be at the root of the archive. CDK and Terraform do this for you.
  • Judging Lambda by one cold request → a single sample says nothing about p99 → take at least a few dozen cold starts, or read Init Duration across a day with Logs Insights.
  • Comparing hosts from different networks → you measure your Wi-Fi → run the probe from the same machine and place against each host.
  • Letting Lambda create the log group → logs kept forever → create it first with retention.
  • Setting reserved concurrency to protect the bill on a new account → deployment error about unreserved capacity → use the stage throttle and budgets instead.
  • Leaving experiment memory settings in place → the next cdk deploy silently reverts them, or you forget they differ from the stack → treat CLI changes as experiments and restore.

Troubleshooting

SymptomLikely causeFix
{"message":"Internal Server Error"} from the APIException in start-up (usually configuration)aws logs tail /hl-m03/accounts-api/lambda --since 10m; look for the message that names the missing setting
Log shows Configure Pseudonymisation:Key ...Parameter missing or path mismatchCreate /hl-m03/accounts-api/Pseudonymisation/Key (step 2)
AccessDeniedException ... ssm:GetParametersByPathIAM resource does not match the configured pathBoth must be /hl-m03/accounts-api/; check the role's inline policy
Runtime.InvalidEntrypointPublished for the wrong architectureRepublish with -r linux-arm64 and redeploy
Runtime.ExitError right after initUnhandled exception in Program.csThe log stream shows the stack trace; fix the cause
Task timed out after 15.00 secondsCold start plus slow downstream, or the DynamoDB table missingCheck the table exists in us-east-1 and the role allows it; raise memory
403 Forbidden through the API but invoke worksInvoke permission's source ARN does not matchRedeploy the stack; the permission is created by the integration
CDK says Skipping HlM03-Lambdapublish/lambda folder missingRun the publish command in step 3
No Init Duration ever appearsEvery request is warmWait ~15 minutes, or change the memory setting to force new environments
InvalidParameterValueException on --snap-startRuntime or architecture not supported for SnapStart in your account/Region ⚠ VERIFYCheck the supported-runtimes page; skip experiment C
Probe prints 429Stage throttle (10 req/s) hitThe probe is sequential and normally stays under it; check for other clients

Cost and cleanup

ResourceCost for this lab
Lambda requests and durationWithin the monthly free allowance (1 million requests, 400,000 GB-seconds; a few hundred requests at 1 GB use well under 100 GB-seconds)
HTTP APIUSD 1.00 per million requests: a few hundred requests cost a fraction of a cent (its own free allowance applies only to the first 12 months of new customers)
CloudWatch Logs, DynamoDB on demand, Parameter Store standardCents at most
SnapStart (experiment C only)A cache charge per published version for at least 3 hours, plus a restore charge per GB: about USD 0.02 for one 1 GB version ⚠ VERIFY current prices

Label: free for the core lab; experiment C is cents. Free alternative: do steps 1, 3 and 6 against the local app (dotnet run, dotnet run tools/latency-probe.cs -- http://localhost:5080 200) to see the warm baseline, and read the stack with cdk synth without deploying.

cd infra/cdk
cdk destroy HlM03-Lambda HlM03-Shared -c owner=<your-name> --force
aws ssm delete-parameter --name /hl-m03/accounts-api/Pseudonymisation/Key
rm -rf ../../publish ../../out.json

# Confirm nothing tagged for this lab remains (deleted resources can take minutes to disappear)
aws resourcegroupstaggingapi get-resources \
  --tag-filters Key=Project,Values=cea-lab Key=Lab,Values=m03-accounts-api \
  --query "ResourceTagMappingList[].ResourceARN"
aws lambda list-functions --query "Functions[?starts_with(FunctionName, 'hl-m03')].FunctionName"

If you used Terraform: terraform destroy -var owner=<your-name> from infra/terraform. Deleting the function also deletes its versions and aliases, which ends any SnapStart cache charge. If publish/ is gone before you destroy, use aws cloudformation delete-stack --stack-name HlM03-Lambda.

Exercises

  • 🟢 Guided: Run Experiment A (512, 1024, 2048 MB). Build a table of Init Duration, first request time and Max Memory Used. Say which size you would choose for this API and why.
  • 🟡 Challenge: Move production-style traffic to a version and alias. Publish a version, create an alias live, point the HTTP API integration at the alias ARN, and prove with the access log that requests reach that version. Then enable SnapStart on that version and compare. Update LambdaStack.cs (or lambda.tf) so the alias is code, not a CLI step.
  • 🔴 Live problem: The reconciliation partner reports that every morning at 08:00 their first few requests take 5 to 6 seconds and then everything is fast. Your dashboard shows Init Duration of about 2.5 seconds for those requests. List what you check and what you would change, in order, and what each option costs.

Assignment

Add a COLD-START-REPORT.md to your portfolio repository: your environment (Region, memory, architecture, package size), a table with at least four configurations (memory sizes, ReadyToRun, optional SnapStart) showing first-request time, Init Duration, warm p50/p95/p99 and the compute cost for one million requests (calculated, not guessed), and a recommendation for the overnight-burst use case with the evidence that supports it.

Solutions

Knowledge check

Interview questions

  • How do you decide between Lambda and Fargate for an API? Traffic shape (spiky or idle versus steady), latency sensitivity to the first request, execution time limits, existing frameworks, and cost at the expected request volume. I would measure cold starts and compute a break-even rather than choose on principle.
  • What can you do about .NET cold starts? More memory, ARM64, ReadyToRun, trimming dependencies, SnapStart on versions or aliases, provisioned concurrency for predictable peaks, or Native AOT for small functions where you control the dependencies. Each has a cost or a constraint, so I measure first.
  • Why put an alias in front of a function? Aliases give stable ARNs for integrations and permissions, make rollback a pointer change, and allow weighted traffic shifting for canaries.

Certification practice

Completion checklist

  • The tests pass (71 passed, 1 skipped) and I know what LambdaEventTests does and does not prove
  • The function runs on dotnet10 arm64 and answers through the HTTP API and through aws lambda invoke
  • I read Init Duration from a REPORT line and from a Logs Insights query
  • I ran at least the memory experiment and wrote down my own numbers
  • I destroyed the stacks, deleted the parameter and the tag query returned nothing

Key takeaways

  • One ASP.NET Core binary can serve Kestrel and Lambda; AddAWSLambdaHosting is the seam.
  • A cold start is the sum of runtime start, your Program.cs and any configuration calls; measure it with Init Duration, not with a stopwatch on your laptop.
  • For .NET on Lambda, memory is CPU: test sizes, and compute cost from duration, not from the per-second price alone.
  • Aliases and versions are what make SnapStart, canaries and rollback possible.
  • Throttles, timeouts and log retention are part of the design of a public function, not extras.

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