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.
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-arm64and run it, unchanged, on the Lambdadotnet10managed runtime. - Explain how
AddAWSLambdaHostinglets 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 readInit Durationfrom theREPORTlog 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:Pathbecomes 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 lab | What's different |
|---|---|---|
| Azure Functions (isolated worker) with the ASP.NET Core integration | Lambda dotnet10 + AddAWSLambdaHosting | You choose the event source (HttpApi, RestApi, ALB); the function handler string is the assembly name |
| Functions Consumption plan cold start | Lambda init phase (Init Duration) | Reported on every cold REPORT line; memory also sets CPU |
| Premium plan pre-warmed instances | Provisioned concurrency (not used here) | Billed per hour configured |
| API Management consumption tier | API Gateway HTTP API | Cheaper and simpler than REST APIs; JWT authorizers built in, no usage plans or API keys |
| Application Insights live metrics | CloudWatch Logs, REPORT lines, Logs Insights | You query log fields such as @initDuration |
| Deployment slots | Versions and aliases | SnapStart 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.
| File | Role in this lab |
|---|---|
src/Harbourline.Accounts.Api/Program.cs | Line builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi) makes the app Lambda-aware |
src/.../Harbourline.Accounts.Api.csproj | OutputType is Exe and SelfContained is false: Lambda starts the assembly as an executable on the managed runtime |
infra/cdk/.../LambdaStack.cs | CDK stack HlM03-Lambda: log groups, function, HTTP API, throttling, cdk-nag acknowledgments |
infra/terraform/lambda.tf | The same host in Terraform (names end in -tf) |
events/get-account-v2.json | A sample HTTP API payload 2.0 event for aws lambda invoke |
tests/.../ConfigurationAndLambdaTests.cs | Replays that event's method, path and headers through the real pipeline |
tools/latency-probe.cs | First-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.slnxExpected: 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.jsonThe 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 15mFind 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 200Expect 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 REPORTLook 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 asaws 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 →$defaultshows 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:
| Setting | First request | Init Duration | Warm p50 | Bill per 1M requests (compute only) |
|---|---|---|---|---|
| 512 MB, JIT | slowest | highest | similar | smallest per second, longest duration |
| 1024 MB, JIT | middle | middle | similar | middle |
| 2048 MB, JIT | fastest | lowest | similar | highest per second, shortest duration |
| 1024 MB, ReadyToRun | faster than JIT at 1024 | lower than JIT at 1024 | similar | similar |
| 1024 MB, SnapStart | restore time, if it works for this model | Restore Duration instead | similar | plus cache and restore charges |
Record your real figures in the project page's comparison table.
What the stack configures (and why)
Setting in LambdaStack.cs | Purpose |
|---|---|
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 = 1024 | Graviton is cheaper per GB-second; 1024 MB gives .NET enough CPU for a reasonable init |
Timeout = 15 s | Longer than a cold start plus one DynamoDB call, shorter than anything a client would wait for |
LogGroup created first, ONE_WEEK retention | A group Lambda creates itself never expires |
ParameterStore__Path environment variable | The app loads /hl-m03/accounts-api/* at start-up (adds to init time) |
AccountsApiPermissions.GrantReadOnly | The same table and parameter statements as the Fargate task role and Beanstalk instance role |
HTTP API with HttpLambdaIntegration | Payload 2.0, $default route and stage |
| Stage throttle 10 requests per second, burst 20 | A 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 integrationLatency | Separates 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.
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.
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:
{
"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:
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
AddAWSLambdaHosting(LambdaEventSource.HttpApi)registers a replacement for Kestrel only when the environment variableAWS_LAMBDA_FUNCTION_NAMEis present. Locally and in containers it is a no-op, which is why one binary serves three hosts.LambdaEventSource.HttpApiselects payload format 2.0 parsing. UseRestApifor REST APIs andApplicationLoadBalancerfor an ALB target group; a mismatch produces 500s with a deserialisation error in the logs.OutputTypeExein the project file makes the build produce a runnable assembly. With thedotnet10managed runtime andHandler = "Harbourline.Accounts.Api", Lambda starts that assembly, which opens the Lambda runtime loop instead of listening on a port.AddAwsConfigurationSourcesruns beforebuilder.Build(), so it happens in the init phase.optional: falsemeans a failed Parameter Store call stops the start-up, which is what you want for a security-relevant key.UsePlatformPortonly reads thePORTvariable. Lambda sets none, so it does nothing.- 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. AddSerilog(... WriteTo.Console(RenderedCompactJsonFormatter))writes JSON lines to stdout; Lambda forwards stdout to the function's log group.CorrelationIdMiddlewareprefers a safeX-Correlation-IDheader (the event supplies one) and otherwise uses theRoot=part ofX-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-policieson 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
dotnet10runtime for you; you still own NuGet updates. Track the runtime's deprecation date (2028-11-14 fordotnet10) 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-arm64when the function isarm64. - 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 Durationacross 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 deploysilently reverts them, or you forget they differ from the stack → treat CLI changes as experiments and restore.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
{"message":"Internal Server Error"} from the API | Exception 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 mismatch | Create /hl-m03/accounts-api/Pseudonymisation/Key (step 2) |
AccessDeniedException ... ssm:GetParametersByPath | IAM resource does not match the configured path | Both must be /hl-m03/accounts-api/; check the role's inline policy |
Runtime.InvalidEntrypoint | Published for the wrong architecture | Republish with -r linux-arm64 and redeploy |
Runtime.ExitError right after init | Unhandled exception in Program.cs | The log stream shows the stack trace; fix the cause |
Task timed out after 15.00 seconds | Cold start plus slow downstream, or the DynamoDB table missing | Check the table exists in us-east-1 and the role allows it; raise memory |
403 Forbidden through the API but invoke works | Invoke permission's source ARN does not match | Redeploy the stack; the permission is created by the integration |
CDK says Skipping HlM03-Lambda | publish/lambda folder missing | Run the publish command in step 3 |
No Init Duration ever appears | Every request is warm | Wait ~15 minutes, or change the memory setting to force new environments |
InvalidParameterValueException on --snap-start | Runtime or architecture not supported for SnapStart in your account/Region ⚠ VERIFY | Check the supported-runtimes page; skip experiment C |
| Probe prints 429 | Stage throttle (10 req/s) hit | The probe is sequential and normally stays under it; check for other clients |
Cost and cleanup
| Resource | Cost for this lab |
|---|---|
| Lambda requests and duration | Within 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 API | USD 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 standard | Cents 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 andMax 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. UpdateLambdaStack.cs(orlambda.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 Durationof 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
Typical pattern: Init Duration falls as memory rises, with diminishing returns beyond the point where the init phase is no longer CPU-bound, while Max Memory Used stays far below the setting (this API needs a few hundred MB). Choose the smallest size after which the improvement per extra GB-second is small. Show the cost calculation: compute cost per request is memory in GB multiplied by billed seconds multiplied by the per-GB-second price. If 2048 MB halves the duration, compute cost is about the same as 1024 MB while latency is better; if it only shaves ten percent, 1024 MB wins. State that the answer is specific to this code, this Region and this day.
VER=$(aws lambda publish-version --function-name hl-m03-accounts-api --query Version --output text)
aws lambda create-alias --function-name hl-m03-accounts-api --name live --function-version $VERThe HTTP API integration must use the alias ARN (arn:aws:lambda:us-east-1:<account>:function:hl-m03-accounts-api:live) as its integration URI, and the function's resource policy must allow the API to invoke that qualified ARN (a permission with --qualifier live). In CDK, new Alias(...) with Version = function.CurrentVersion and new HttpLambdaIntegration("Live", alias); in Terraform, aws_lambda_alias plus integration_uri set to the alias invoke_arn and aws_lambda_permission with qualifier. The access log's integrationLatency and the REPORT lines for the version prove traffic reaches it. SnapStart is enabled on the function and takes effect for versions published afterwards. Why aliases: a version is immutable, so a rollback is repointing an alias, and canary shifts weight between two versions.
Facts: the problem appears after a quiet period (no environments exist) and at the first burst (new environments must be created), and a 2.5 s init plus network and API Gateway does not explain 5 to 6 s by itself, so check for more than one cold start in the chain (a second concurrent environment, or the first request also waiting on Parameter Store or DynamoDB connection set-up). Investigate: Logs Insights for @initDuration by hour; the access log's integrationLatency; whether the first request triggers one environment or several (concurrent first requests each cold-start). Options, cheapest first: raise memory (measure), ReadyToRun, SnapStart on an alias, a scheduled warm-up call before 08:00 (cheap but not reliable: it warms one environment, not many), scheduled provisioned concurrency for 07:55 to 09:00 (billed for the hours configured), or moving this partner's traffic to the always-on Fargate host. Explain that only provisioned concurrency and SnapStart address concurrent cold starts directly, and that they cannot be combined on the same version.
Knowledge check
Answer: AddAWSLambdaHosting swaps Kestrel for a Lambda event translator only when it detects the Lambda environment (AWS_LAMBDA_FUNCTION_NAME). Elsewhere it does nothing, so Kestrel serves HTTP as usual. The endpoints, middleware and DI registrations are identical.
Answer: Init Duration is only the function's start-up (runtime start plus your Program.cs), reported in the cold REPORT line. The probe's first request also includes your network, TLS to API Gateway, API Gateway's own processing and the function's invocation time. Always compare like with like.
Answer: Billing is memory multiplied by billed duration. More memory also means more CPU, so a CPU-bound start-up or request can finish in less than half the time. If duration more than halves, cost per request falls. If it does not, cost rises. Measure.
Answer: The snapshot is taken when a version is published and restored for new environments, so it cannot apply to the mutable $LATEST. Anything unique created during init (random seeds, idempotency keys, nonces) is copied into every restored environment, so generate such values inside the request path.
Answer: The timeout bounds a stuck invocation (and its cost) and should be below what the caller waits for. The throttle bounds how fast anyone, including an attacker, can invoke an unauthenticated lab API, which limits cost exposure.
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
A .NET API on AWS Lambda behind an API Gateway HTTP API shows high latency for the first request after idle periods. The team wants to reduce start-up latency without paying for always-on capacity. Which option fits? A. Provisioned concurrency. B. Lambda SnapStart on a published version or alias, where the runtime supports it. C. A larger API Gateway timeout. D. A Lambda function URL instead of the HTTP API. Answer: B. SnapStart restores environments from a snapshot taken at publish time and has no hourly capacity charge (it has cache and restore charges). A keeps environments initialised and bills for the configured hours. C does not change start-up time. D removes API Gateway but does not change Lambda's init phase.
An internal API receives about 3,000 requests in a ten-minute window each night and is idle otherwise. Which hosting choice is the most cost-effective that still meets a relaxed latency target? A. An ECS service on Fargate with a load balancer running all day. B. AWS Lambda behind an API Gateway HTTP API. C. A dedicated EC2 instance. D. An EKS cluster with a managed node group. Answer: B. Pay-per-request compute with no idle cost fits an extremely spiky, mostly idle workload. A, C and D incur hourly charges all day (a load balancer, a task or instance, a control plane).
A Lambda function must read items from one DynamoDB table. Which approach follows least privilege? A. Attach AdministratorAccess to the execution role. B. Put an IAM user's access keys in environment variables. C. Grant dynamodb:GetItem and dynamodb:Query on the table's ARN to the execution role. D. Make the table public.
Answer: C. The execution role is the function's identity and should carry only the actions and resources it needs. A is over-privileged; B uses long-lived credentials visible in configuration; D is not an option for DynamoDB and would be wrong anyway.
Completion checklist
- The tests pass (71 passed, 1 skipped) and I know what
LambdaEventTestsdoes and does not prove - The function runs on
dotnet10arm64 and answers through the HTTP API and throughaws lambda invoke - I read
Init Durationfrom aREPORTline 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;
AddAWSLambdaHostingis the seam. - A cold start is the sum of runtime start, your
Program.csand any configuration calls; measure it withInit 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
- Building Lambda functions with C# — runtimes and deprecation dates
- Improving startup performance with Lambda SnapStart
- AWS Lambda pricing
- Amazon API Gateway pricing
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.
Lab 3.3: push to ECR and deploy to Fargate behind an ALB
Create a private ECR repository with immutable tags and scan on push, push an arm64 image of the Accounts API, deploy it with CDK to ECS on Fargate in private subnets behind an Application Load Balancer, test it, then destroy everything within the hour.
Lab 3.5: Parameter Store and Secrets Manager with caching and rotation
Layer configuration from appsettings, environment variables and Parameter Store, change a feature flag without a restart, read a pseudonymisation key from Secrets Manager through the client-side cache, rotate it, and see exactly when the API notices.