Lambda with C#
Write, test and deploy C# Lambda functions on the dotnet10 runtime: plain handlers, the Lambda Annotations framework, a whole ASP.NET Core API inside Lambda, Native AOT, and the real options for cold starts including SnapStart and provisioned concurrency.
Assumes: .NET 10 LTS · Lambda runtime dotnet10 (Amazon Linux 2023) · Amazon.Lambda.Annotations 2.4.2 · Amazon.Lambda.Core 3.4.0 · Amazon.Lambda.AspNetCoreServer.Hosting 2.2.1 · Amazon.Lambda.Tools 7.0.0 · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this lesson you can:
- Explain the Lambda execution model — init, invoke, shutdown, execution-environment reuse and concurrency — and what it means for C# code (static clients,
HttpClient, DI containers). - Choose between four C# programming models: a class-library handler, an executable assembly with
RuntimeSupport, the Lambda Annotations framework and ASP.NET Core in Lambda. - Build and unit-test a function with Annotations, then deploy it behind an API Gateway HTTP API with the
dotnet10managed runtime on ARM64. - Measure cold starts and pick the right fix: memory, ARM64, ReadyToRun, Native AOT, SnapStart or provisioned concurrency — and know which combinations are impossible.
- State Lambda's key limits and costs and design around them.
Prerequisites
- AWS SDK for .NET v4 in depth and AWS clients and dependency injection.
- IAM in depth — execution roles and resource-based policies.
- Tools: .NET 10 SDK, AWS CLI v2 with
learn-sandbox, Amazon Lambda .NET CLI tools:dotnet tool install -g Amazon.Lambda.Tools(version 7.0.0 at the time of writing), optionally the Lambda templatesdotnet new install Amazon.Lambda.Templatesand Docker (for Native AOT builds).
Why this matters in banking
Not every bank workload is a busy API. Harbourline has many spiky or event-driven jobs: validating a payment file when it lands in S3, enriching a card authorisation event, sending a statement-ready notification, answering a partner's balance query a few hundred times a day. Running a container 24/7 for each of these wastes money and adds patching work. Lambda runs code only when an event arrives and bills per millisecond.
The traps are real, though. A team ports a payments API to Lambda, and the first customer request after a quiet period takes 3 seconds because of a .NET cold start. Another team creates a new AmazonDynamoDBClient inside the handler and exhausts sockets under load. A third gives every function the same broad role. And an auditor asks how a function that reads customer data is isolated, versioned and rolled back. This lesson addresses each of these.
The idea in plain language
AWS Lambda runs your function in response to events. You upload code, say how much memory it needs, and Lambda takes care of servers, scaling and patching the runtime. You pay per request and per GB-second of execution.
AWS's documentation now calls these Lambda Event Functions (previously simply "Lambda functions"), to distinguish them from the newer Lambda Web Functions, which run an HTTP server process directly. At the time of writing Web Functions support only Node.js, so for C# everything in this lesson uses Event Functions.
How a function runs:
- Init. The first time (or when scaling out), Lambda creates an execution environment: a micro-VM, the .NET runtime, your assembly loaded, your constructor and static initialisers run. This is the cold start.
- Invoke. Lambda calls your handler with the event. The environment handles one request at a time.
- Reuse. After the response, the environment is frozen and may be reused for the next event — warm start, no init. Anything you created during init (SDK clients,
HttpClient, configuration) is reused too. - Scale. If 50 requests arrive at once, Lambda creates up to 50 environments (subject to concurrency limits). Each has its own cold start.
- Shutdown. Idle environments are eventually discarded. You cannot control when.
Analogy: Lambda is a bank's pool of on-call contractors. When work arrives, a contractor is called in (cold start: they need to commute and set up their desk). If more work arrives while they are still there, they handle it immediately (warm start). Busy days bring in more contractors, each with their own commute. You pay only for the minutes they spend working — but setting up the desk takes longer for some trades (.NET) than others.
What problem Lambda solves
Lambda removes servers, idle cost and most scaling work for event-driven code. It integrates natively with more than 200 event sources — S3, SQS, EventBridge, DynamoDB Streams, API Gateway, Kinesis and others.
Key limits and facts (checked 2026-11-18):
| Item | Value |
|---|---|
| .NET managed runtime | dotnet10 on Amazon Linux 2023, deprecation scheduled 2028-11-14. dotnet8 was deprecated on 2026-11-10 |
| Architectures | x86_64 and arm64 (Graviton) for every supported runtime |
| Memory | 128 MB to 10,240 MB; CPU is allocated in proportion to memory |
| Timeout | up to 900 seconds (15 minutes) |
| Synchronous request/response payload | 6 MB each way |
/tmp storage | 512 MB to 10,240 MB |
| Deployment package | 50 MB zipped (direct upload) / 250 MB unzipped; container images up to 10 GB |
| Default concurrency | 1,000 concurrent executions per Region (a soft quota) |
| Free tier | 1 million requests and 400,000 GB-seconds per month |
| Price (us-east-1) | USD 0.20 per million requests; USD 0.0000166667 per GB-second on x86, USD 0.0000133334 on Arm |
Limitations to design around:
- Cold starts. .NET's JIT and assembly loading make cold starts longer than for interpreted languages, typically hundreds of milliseconds to a few seconds depending on package size and memory.
- One request per environment. Connection pools and in-memory caches are per environment, so 200 concurrent requests mean 200 sets of database connections. Use RDS Proxy or DynamoDB for relational load ⚠ beyond this lesson.
- 15-minute ceiling. Long batch jobs belong on Fargate, Step Functions or AWS Batch.
- No sticky local state. Do not rely on
/tmpor static fields surviving. - Initialisation is billed. Duration charges apply to init code outside the handler as well as the handler itself, so a heavy start-up costs money as well as latency.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Azure Functions (isolated worker) | Lambda dotnet10 | One function = one handler. No host.json; settings live on the function (memory, timeout, env vars) |
| Function triggers and bindings | Event source mappings (SQS, Kinesis, DynamoDB) and service integrations (S3, EventBridge, API Gateway) | No output bindings: call other services with the SDK |
[Function] + [HttpTrigger] attributes | Lambda Annotations [LambdaFunction] + [HttpApi] | Annotations is a source generator: it writes the handler wrapper and a CloudFormation/SAM template at build time |
| Consumption plan | On-demand Lambda | Lambda scales per request; no plan; free tier is per account |
| Premium plan "always ready" instances | Provisioned concurrency | Billed for every hour it is configured |
| Flex Consumption / snapshot-based start-up | SnapStart | Snapshot taken when a version is published |
| Azure Functions on ASP.NET Core integration | Amazon.Lambda.AspNetCoreServer.Hosting | Your whole Minimal API runs inside one function |
| Managed identity | Function execution role | Assumed automatically; the SDK finds credentials in environment variables |
| Application settings | Environment variables (encrypted at rest with KMS) | Limit of 4 KB total for all variables |
| Deployment slots | Versions and aliases with weighted routing | Canary via alias weights or CodeDeploy |
Architecture
Security-boundary view:
| Boundary | Control |
|---|---|
| Client → API Gateway | TLS, JWT authorizer (Cognito), throttling, optionally WAF (REST APIs and CloudFront) |
| API Gateway → function | Resource-based policy on the function: lambda:InvokeFunction allowed for that API's ARN only |
| Function → AWS services | Execution role, least privilege, resource ARNs |
| Function → private resources | Optional VPC attachment (ENIs in your subnets) |
| Configuration | Environment variables encrypted with KMS; secrets fetched at runtime, not stored in variables |
The four C# programming models
| Model | Handler string | When to use | Cold start |
|---|---|---|---|
| Class-library handler | Assembly::Namespace.Class::Method | Simple event handlers; classic templates | Medium |
Executable assembly (Amazon.Lambda.RuntimeSupport, LambdaBootstrapBuilder) | Assembly name | Full control over start-up; required for Native AOT and custom runtimes | Medium; lowest with Native AOT |
| Lambda Annotations | Generated, e.g. Assembly::Namespace.Class_Method_Generated::Method | Most new functions: DI, route and parameter binding, generated SAM template | Medium; works with Native AOT and SnapStart |
ASP.NET Core in Lambda (AddAWSLambdaHosting) | Assembly name | Porting an existing Minimal API or MVC app; one function serves many routes | Highest (full ASP.NET Core pipeline start-up) |
The module lab (labs/m03-accounts-api) uses the fourth model, so the same binary runs on Kestrel in Beanstalk and ECS, and inside Lambda:
builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi); // does nothing outside LambdaAddAWSLambdaHosting detects the Lambda environment (the AWS_LAMBDA_FUNCTION_NAME variable) and swaps Kestrel for a Lambda event translator; locally it does nothing. With LambdaEventSource.HttpApi it understands API Gateway HTTP API payload format 2.0. The function handler is simply the assembly name, Harbourline.Accounts.Api.
This lesson's complete code uses Annotations for a focused function, which is the better default for new event-driven code.
Step-by-step implementation
Create the project
dotnet new classlib -n Harbourline.Accounts.Functions -f net10.0, add the Annotations, Core, serializer and DynamoDB packages (see the project file below). Annotations needs GenerateRuntimeConfigurationFiles and, for Native AOT later, GenerateMain.
Write the function with dependency injection
A [LambdaStartup] class registers services once per execution environment. The function class takes dependencies in its constructor; methods are marked [LambdaFunction] and [HttpApi].
Unit-test without AWS
Because the function is a plain class, create it with a fake repository and call the method with a TestLambdaContext. No emulator required.
Create the log group and execution role
Create /aws/lambda/hl-m03-get-account with 7-day retention before the first invoke (Lambda would otherwise create it with no expiry). The execution role gets AWSLambdaBasicExecutionRole-equivalent log permissions for that group and dynamodb:GetItem on one table.
Package and deploy
dotnet lambda package builds a Release zip for linux-arm64. Create the function with runtime dotnet10, architecture arm64, 512 MB, 10-second timeout.
Front it with an HTTP API and test
Create an HTTP API with a route GET /accounts/{accountId} integrated with the function, and allow API Gateway to invoke it. Call the URL. In production add a JWT authorizer (Cognito) before any customer data is returned.
Measure cold starts, then try SnapStart
Read Init Duration from the REPORT log line. Publish a version with SnapStart on and compare Restore Duration.
AWS Console instructions
- Console → CloudWatch → Log groups → Create log group. Name
/aws/lambda/hl-m03-get-account, retention 1 week. - Console → IAM → Roles → Create role. Trusted entity AWS service → Lambda. Skip managed policies; after creation add an inline policy allowing
logs:CreateLogStreamandlogs:PutLogEventson the log group ARN anddynamodb:GetItemon the table ARN. - Console → Lambda → Create function → Author from scratch. Name
hl-m03-get-account, runtime .NET 10 (C#/PowerShell), architecture arm64, execution role Use an existing role. - Code → Upload from → .zip file and upload the package. Under Runtime settings → Edit, set the handler printed by the build (see below).
- Configuration → General configuration → Edit: memory 512 MB, timeout 10 s. Configuration → Environment variables:
TABLE_NAME=hl-m03-accounts. - Test tab → create an event from the API Gateway HTTP API template, set
pathParameters.accountIdto a seeded account ID, and run it. Expand Details to seeInit Duration. - Console → API Gateway → Create API → HTTP API → Build. Integration Lambda, function
hl-m03-get-account, routeGET /accounts/{accountId}, stage$defaultwith auto-deploy. The console adds the invoke permission for you. - SnapStart: Lambda → Configuration → General configuration → SnapStart: PublishedVersions, then Actions → Publish new version, and point an alias
liveat it.
AWS CLI
export AWS_PROFILE=learn-sandbox AWS_REGION=us-east-1
ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
FN=hl-m03-get-account
# 1. Log group with retention BEFORE the first invocation.
aws logs create-log-group --log-group-name /aws/lambda/$FN
aws logs put-retention-policy --log-group-name /aws/lambda/$FN --retention-in-days 7
# 2. Execution role, scoped to this function's log group and one table.
cat > lambda-trust.json <<'EOF'
{ "Version": "2012-10-17",
"Statement": [{ "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" }] }
EOF
aws iam create-role --role-name $FN-role --assume-role-policy-document file://lambda-trust.json
cat > lambda-policy.json <<EOF
{ "Version": "2012-10-17",
"Statement": [
{ "Effect": "Allow", "Action": ["logs:CreateLogStream", "logs:PutLogEvents"],
"Resource": "arn:aws:logs:us-east-1:$ACCOUNT:log-group:/aws/lambda/$FN:*" },
{ "Effect": "Allow", "Action": ["dynamodb:GetItem"],
"Resource": "arn:aws:dynamodb:us-east-1:$ACCOUNT:table/hl-m03-accounts" } ] }
EOF
aws iam put-role-policy --role-name $FN-role --policy-name runtime --policy-document file://lambda-policy.json
# 3. Build a Release zip for linux-arm64 (Amazon.Lambda.Tools).
dotnet lambda package --project-location src/Harbourline.Accounts.Functions \
--configuration Release --function-architecture arm64 --output-package artifacts/get-account.zip
# 4. Create the function. The handler name is generated by Annotations (see "Code explained").
aws lambda create-function --function-name $FN \
--runtime dotnet10 --architectures arm64 --memory-size 512 --timeout 10 \
--role arn:aws:iam::$ACCOUNT:role/$FN-role \
--handler 'Harbourline.Accounts.Functions::Harbourline.Accounts.Functions.AccountFunctions_GetAccount_Generated::GetAccount' \
--zip-file fileb://artifacts/get-account.zip \
--environment 'Variables={TABLE_NAME=hl-m03-accounts}' \
--tags Project=cea-lab,Lab=m03-lambda,Environment=learn,Owner=you
aws lambda wait function-active-v2 --function-name $FN
# 5. HTTP API "quick create": one route, Lambda proxy integration, $default stage.
API_ID=$(aws apigatewayv2 create-api --name hl-m03-accounts-http --protocol-type HTTP \
--target arn:aws:lambda:us-east-1:$ACCOUNT:function:$FN \
--route-key 'GET /accounts/{accountId}' --query ApiId --output text)
# Resource-based policy: only THIS API may invoke the function.
aws lambda add-permission --function-name $FN --statement-id apigw-invoke \
--action lambda:InvokeFunction --principal apigateway.amazonaws.com \
--source-arn "arn:aws:execute-api:us-east-1:$ACCOUNT:$API_ID/*/*/accounts/*"
curl -s "https://$API_ID.execute-api.us-east-1.amazonaws.com/accounts/ACC-0000000001"
# 6. Read cold-start metrics from the REPORT lines.
aws logs filter-log-events --log-group-name /aws/lambda/$FN --filter-pattern '"REPORT"' \
--query 'events[].message' --output text | tail -5
# 7. SnapStart: applies to published versions only.
aws lambda update-function-configuration --function-name $FN --snap-start ApplyOn=PublishedVersions
aws lambda wait function-updated-v2 --function-name $FN
VERSION=$(aws lambda publish-version --function-name $FN --query Version --output text)
aws lambda create-alias --function-name $FN --name live --function-version $VERSION
# Point the API at the alias instead of $LATEST in production (update the integration URI).Infrastructure as Code
using Amazon.CDK;
using Amazon.CDK.AWS.Apigatewayv2;
using Amazon.CDK.AWS.DynamoDB;
using Amazon.CDK.AWS.Lambda;
using Amazon.CDK.AWS.Logs;
using Amazon.CDK.AwsApigatewayv2Integrations;
using Constructs;
public sealed class LambdaStack : Stack
{
public LambdaStack(Construct scope, string id, IStackProps props) : base(scope, id, props)
{
var table = Table.FromTableName(this, "Accounts", "hl-m03-accounts");
var logGroup = new LogGroup(this, "Logs", new LogGroupProps
{
LogGroupName = "/aws/lambda/hl-m03-get-account",
Retention = RetentionDays.ONE_WEEK,
RemovalPolicy = RemovalPolicy.DESTROY,
});
var fn = new Function(this, "GetAccount", new FunctionProps
{
FunctionName = "hl-m03-get-account",
// Use Runtime.DOTNET_10 if your CDK version has it; this form works with any version.
Runtime = new Runtime("dotnet10", RuntimeFamily.DOTNET_CORE),
Architecture = Architecture.ARM_64,
MemorySize = 512,
Timeout = Duration.Seconds(10),
Handler = "Harbourline.Accounts.Functions::Harbourline.Accounts.Functions.AccountFunctions_GetAccount_Generated::GetAccount",
Code = Code.FromAsset("../../artifacts/get-account.zip"),
Environment = new Dictionary<string, string> { ["TABLE_NAME"] = table.TableName },
LogGroup = logGroup,
SnapStart = SnapStartConf.ON_PUBLISHED_VERSIONS,
});
table.GrantReadData(fn); // GetItem, Query, Scan, BatchGetItem … scoped to this table
// An alias pointing at a published version: SnapStart only applies to versions.
var alias = new Alias(this, "Live", new AliasProps { AliasName = "live", Version = fn.CurrentVersion });
var api = new HttpApi(this, "Api", new HttpApiProps { ApiName = "hl-m03-accounts-http" });
api.AddRoutes(new AddRoutesOptions
{
Path = "/accounts/{accountId}",
Methods = [Amazon.CDK.AWS.Apigatewayv2.HttpMethod.GET],
Integration = new HttpLambdaIntegration("GetAccountIntegration", alias),
});
_ = new CfnOutput(this, "Url", new CfnOutputProps { Value = api.Url! });
}
}GrantReadData is convenient but grants more than GetItem. For a strict least-privilege review, add an explicit PolicyStatement instead. Annotations also generates a serverless.template (SAM) you can deploy with dotnet lambda deploy-serverless or sam deploy if you prefer SAM to CDK.
Complete code
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<RootNamespace>Harbourline.Accounts.Functions</RootNamespace>
<!-- Lambda reads <assembly>.runtimeconfig.json to start the managed runtime. -->
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<!-- Precompile to native code at build time: faster JIT-free start-up for hot paths. -->
<PublishReadyToRun>true</PublishReadyToRun>
<AWSProjectType>Lambda</AWSProjectType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Amazon.Lambda.Annotations" Version="2.4.2" />
<!-- Required by Annotations for [HttpApi] functions (event and response types). -->
<PackageReference Include="Amazon.Lambda.APIGatewayEvents" Version="3.0.1" />
<PackageReference Include="Amazon.Lambda.Core" Version="3.4.0" />
<PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="3.0.1" />
<PackageReference Include="AWSSDK.DynamoDBv2" Version="4.1.0.2" />
<PackageReference Include="AWSSDK.Extensions.NETCore.Setup" Version="4.1.0.2" />
<!-- The generated handler builds a ServiceProvider, so the full DI package is needed. -->
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.15" />
</ItemGroup>
</Project>using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
namespace Harbourline.Accounts.Functions;
/// <summary>What the function returns. Money is decimal, never double.</summary>
public sealed record AccountSummary(string AccountId, string Currency, string Product, string Status, decimal Balance);
public interface IAccountReader
{
Task<AccountSummary?> GetAsync(string accountId, CancellationToken cancellationToken);
}
/// <summary>
/// Reads one item by primary key from the module's single-table layout (the same table the lab API uses):
/// pk = ACCOUNT#{accountId}, sk = PROFILE. Table name comes from configuration, never hard-coded.
/// </summary>
public sealed class DynamoDbAccountReader(IAmazonDynamoDB dynamoDb, string tableName) : IAccountReader
{
public async Task<AccountSummary?> GetAsync(string accountId, CancellationToken cancellationToken)
{
var response = await dynamoDb.GetItemAsync(new GetItemRequest
{
TableName = tableName,
Key = new Dictionary<string, AttributeValue>
{
["pk"] = new() { S = $"ACCOUNT#{accountId}" },
["sk"] = new() { S = "PROFILE" },
},
ProjectionExpression = "account_id, currency, product, #s, balance",
ExpressionAttributeNames = new Dictionary<string, string> { ["#s"] = "status" }, // status is a reserved word
}, cancellationToken);
// SDK v4: Item is null when the key does not exist.
if (response.Item is not { Count: > 0 } item) return null;
return new AccountSummary(
item["account_id"].S,
item["currency"].S,
item["product"].S,
item["status"].S,
decimal.Parse(item["balance"].N, System.Globalization.CultureInfo.InvariantCulture));
}
}using Amazon.DynamoDBv2;
using Amazon.Lambda.Annotations;
using Microsoft.Extensions.DependencyInjection;
namespace Harbourline.Accounts.Functions;
/// <summary>Runs once per execution environment (during init), not once per request.</summary>
[LambdaStartup]
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// One thread-safe SDK client per environment, reused across invocations.
services.AddAWSService<IAmazonDynamoDB>();
var tableName = Environment.GetEnvironmentVariable("TABLE_NAME")
?? throw new InvalidOperationException("TABLE_NAME is not set.");
services.AddSingleton<IAccountReader>(sp =>
new DynamoDbAccountReader(sp.GetRequiredService<IAmazonDynamoDB>(), tableName));
}
}using System.Text.RegularExpressions;
using Amazon.Lambda.Annotations;
using Amazon.Lambda.Annotations.APIGateway;
using Amazon.Lambda.Core;
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace Harbourline.Accounts.Functions;
public partial class AccountFunctions(IAccountReader reader)
{
[GeneratedRegex("^ACC-[0-9]{10}$")]
private static partial Regex AccountIdFormat();
/// <summary>GET /accounts/{accountId} through an API Gateway HTTP API.</summary>
[LambdaFunction(MemorySize = 512, Timeout = 10)]
[HttpApi(LambdaHttpMethod.Get, "/accounts/{accountId}")]
public async Task<IHttpResult> GetAccount(string accountId, ILambdaContext context)
{
// Validate before touching the database: reject anything that is not a Harbourline account id.
if (!AccountIdFormat().IsMatch(accountId))
{
return HttpResults.BadRequest(new { title = "Invalid account id", status = 400 });
}
// Leave headroom before the Lambda timeout so we can still return a clean error.
using var cts = new CancellationTokenSource(context.RemainingTime - TimeSpan.FromMilliseconds(500));
var account = await reader.GetAsync(accountId, cts.Token);
// Log the request id and outcome, never the balance or any personal data.
context.Logger.LogInformation($"GetAccount found={account is not null} requestId={context.AwsRequestId}");
return account is null
? HttpResults.NotFound(new { title = "Account not found", status = 404 })
: HttpResults.Ok(account);
}
}using Amazon.Lambda.Annotations.APIGateway;
using Amazon.Lambda.TestUtilities;
using Harbourline.Accounts.Functions;
using Xunit;
public class AccountFunctionsTests
{
private sealed class FakeReader : IAccountReader
{
public Task<AccountSummary?> GetAsync(string accountId, CancellationToken cancellationToken) =>
Task.FromResult(accountId == "ACC-0000000001"
? new AccountSummary(accountId, "GBP", "current", "open", 1250.75m)
: null);
}
private static readonly TestLambdaContext Context = new() { RemainingTime = TimeSpan.FromSeconds(10) };
[Fact]
public async Task Returns_200_for_existing_account()
{
var result = await new AccountFunctions(new FakeReader()).GetAccount("ACC-0000000001", Context);
Assert.Equal(System.Net.HttpStatusCode.OK, result.StatusCode);
}
[Fact]
public async Task Returns_404_for_unknown_account()
{
var result = await new AccountFunctions(new FakeReader()).GetAccount("ACC-9999999999", Context);
Assert.Equal(System.Net.HttpStatusCode.NotFound, result.StatusCode);
}
[Theory]
[InlineData("1; DROP TABLE")]
[InlineData("ACC-123")]
public async Task Returns_400_for_malformed_ids(string id)
{
var result = await new AccountFunctions(new FakeReader()).GetAccount(id, Context);
Assert.Equal(System.Net.HttpStatusCode.BadRequest, result.StatusCode);
}
}The test project references xunit.v3 4.0.3 and Amazon.Lambda.TestUtilities 4.3.0, with <OutputType>Exe</OutputType> and the Microsoft.Testing.Platform runner as described in CONVENTIONS.md.
Code explained line by line
Project file
GenerateRuntimeConfigurationFiles— producesHarbourline.Accounts.Functions.runtimeconfig.json, which the managed runtime needs to load the assembly.PublishReadyToRun— compiles IL to native code ahead of time (keeping IL as a fallback). It reduces JIT work during cold start at the cost of a larger package. Build for the target architecture (dotnet lambda package --function-architecture arm64does this).Amazon.Lambda.Annotations— a Roslyn source generator. At build time it writes a wrapper class per function (AccountFunctions_GetAccount_Generated), converts the API Gateway event into method parameters and yourIHttpResultback into a response, and updatesserverless.template.
Reader
IAmazonDynamoDBinjected, not created — one client per execution environment, reused across invocations. Creating clients per invocation wastes init time and sockets.ProjectionExpressionwith#s— fetch only needed attributes;statusis a DynamoDB reserved word, so it needs a placeholder.response.Item is not { Count: > 0 }— SDK v4 returnsnullfor a missing item's attribute map instead of an empty dictionary.decimal.Parse(..., InvariantCulture)— DynamoDB numbers are strings; parse them asdecimalwith an invariant culture so a server locale cannot change the decimal separator.
Startup
[LambdaStartup]— Annotations callsConfigureServicesonce during init. The DI container lives as long as the execution environment.TABLE_NAMEcheck — fail fast during init with a clear message rather than on the first request.
Function
[assembly: LambdaSerializer(...)]— System.Text.Json serializer for events and responses.[GeneratedRegex]— the regex is compiled at build time (no runtime regex compilation during cold start) and is trimming/AOT-safe.[LambdaFunction(MemorySize = 512, Timeout = 10)]— written into the generated SAM template. If you deploy with the CLI or CDK, the values there win.[HttpApi(LambdaHttpMethod.Get, "/accounts/{accountId}")]— the route; theaccountIdparameter is bound from the path by name.context.RemainingTime - 500 ms— a cancellation budget smaller than the Lambda timeout, so a slow DynamoDB call is cancelled and you can still return an error, instead of Lambda killing the invocation mid-flight.context.Logger.LogInformation— writes to CloudWatch Logs with the request ID. Never log balances, IBANs or names.HttpResults.Ok/NotFound/BadRequest— Annotations helpers that produce the correct HTTP API response shape.
Tests
- The function is a plain class: construct it with a fake, call the method, assert on
StatusCode. Business logic is tested without Lambda, Docker or AWS.
Cold starts: measure, then choose a fix
A REPORT log line looks like REPORT RequestId: … Duration: 41.12 ms Billed Duration: 42 ms Memory Size: 512 MB Max Memory Used: 92 MB Init Duration: 812.40 ms. Init Duration appears only on cold starts. With SnapStart you see Restore Duration instead.
| Technique | What it does | Cost | Constraints |
|---|---|---|---|
| More memory | CPU scales with memory, so init and JIT run faster | Higher GB-second price, but shorter duration often offsets it | Measure; there is a sweet spot |
| ARM64 | Graviton, about 20% cheaper per GB-second | Cheaper | Native dependencies must support arm64 |
| ReadyToRun | Less JIT at start-up | Bigger package | Build per architecture |
| Trim dependencies | Fewer assemblies to load | Free | Avoid reflection-heavy libraries in hot start-up paths |
| Native AOT | Compiles the whole app to a native executable; no JIT at all | Free | Uses the OS-only runtime provided.al2023, not dotnet10; must build on Amazon Linux (or in its container); reflection, dynamic code and some libraries do not work; use source-generated JSON |
| SnapStart | Lambda snapshots the initialised environment when you publish a version and restores from it | Cache charge per GB-second while the version is active (minimum 3 hours) and a restore charge per GB | Managed runtimes .NET 8 and later only — not OS-only runtimes, so not with Native AOT; published versions/aliases only; not with provisioned concurrency, EFS or /tmp above 512 MB; Annotations must be 1.6.0 or later; unique values created during init are duplicated across environments |
| Provisioned concurrency | Keeps N environments initialised all the time | Billed per hour configured, whether used or not | Not combinable with SnapStart; use auto scaling on schedules for business hours |
Pricing references (us-east-1, from the Lambda pricing page examples, checked 2026-11-18): SnapStart cache about USD 0.0000015046 per GB-second and restore about USD 0.0001397998 per GB.
Rules of thumb for Harbourline:
- Asynchronous work (SQS, S3, EventBridge): cold starts rarely matter. Use the managed runtime, ARM64, ReadyToRun.
- Customer-facing synchronous APIs with steady traffic: Fargate is often simpler and cheaper; if you choose Lambda, try SnapStart first, then provisioned concurrency for business hours.
- Latency-critical, small functions where you control all dependencies: Native AOT gives the lowest cold start and memory use.
SnapStart and uniqueness
Because many environments are restored from the same snapshot, anything generated during init is shared: random seeds, GUIDs, cached temporary credentials, timestamps and open connections. For a bank this matters for idempotency keys and nonces. Generate unique values inside the handler, not in constructors or static initialisers. Amazon.Lambda.Core offers runtime hooks (SnapshotRestore.RegisterBeforeSnapshot and RegisterAfterRestore) to close or refresh resources around the snapshot ⚠ VERIFY the exact API names in the version you use.
Native AOT in one paragraph
For Native AOT, set <PublishAot>true</PublishAot> and <AssemblyName>bootstrap</AssemblyName>, use Amazon.Lambda.RuntimeSupport (or Annotations with [assembly: LambdaGlobalProperties(GenerateMain = true)]), register a source-generated JsonSerializerContext for every event and response type, and deploy with runtime provided.al2023 and handler bootstrap. dotnet lambda package builds inside an Amazon Linux container when it detects PublishAot. Fix every trimming warning; with TreatWarningsAsErrors on, they fail the build, which is what you want.
Security considerations
⚠ Learning shortcut — not for production
The lab HTTP API has no authorizer, so anyone with the URL can request an account by ID, and it invokes $LATEST instead of an alias. In production: a JWT authorizer backed by a Cognito user pool (covered later in this module) with scope checks, the integration pointing at an alias of a published version, throttling limits on the stage, access logging to CloudWatch, and an authorisation check inside the function that the caller is allowed to see that account (protection against broken object-level authorisation, the top OWASP API risk).
- One role per function. Separate roles make least privilege reviewable; a shared role across functions accumulates permissions.
- Restrict who can invoke. The
add-permissioncall uses--source-arnwith the specific API and route, so another API cannot invoke your function. - Environment variables are not for secrets. They are encrypted at rest but visible to anyone with
lambda:GetFunctionConfiguration. Fetch secrets at runtime with caching (see the secrets lesson) or use the Parameters and Secrets Lambda Extension. - Code signing. AWS Signer with a Lambda code-signing configuration ensures only signed packages are deployed — useful evidence of software supply-chain control.
- Runtime updates. Lambda patches the
dotnet10runtime automatically by default; you still update your NuGet dependencies. Track the runtime deprecation date and upgrade before it. - VPC attachment only when the function must reach private resources (RDS, internal APIs); it adds ENIs and needs VPC endpoints or NAT for AWS APIs.
- Logs and personal data. Lambda writes everything on stdout to CloudWatch. Set retention, and never log full request bodies for customer endpoints.
Banking use case
Harbourline's Partner Gateway lets authorised fintechs query account balances under Open Banking-style consent. Traffic is bursty: a few calls per minute overnight, thousands per minute when a partner runs its morning sync. The team implements GET /accounts/{accountId} as an Annotations function on dotnet10 ARM64 behind an HTTP API with a JWT authorizer. A consent check in the function confirms that the calling partner's token carries a consent ID covering that account.
They measured cold starts at about 900 ms with ReadyToRun at 512 MB; after enabling SnapStart on the live alias, restore times dropped to a few hundred milliseconds ⚠ your numbers will differ — measure. Because the morning sync is predictable, a scheduled scaling action adds provisioned concurrency on a separate alias for 07:00–09:00 for the highest-volume partner. Each release publishes a new version, and CodeDeploy shifts 10% of traffic to it for 10 minutes with an alarm-based rollback.
Common mistakes
- Creating SDK clients or
HttpClientinside the handler → slow invocations, socket exhaustion → create once (DI singleton or static) and reuse. - Letting Lambda create the log group → no retention, logs forever → create it first with retention.
- Using
$LATESTin production integrations → no rollback point, no SnapStart → publish versions and use aliases. - Generating idempotency keys during init with SnapStart → duplicates across environments → generate in the handler.
- Combining SnapStart with Native AOT or provisioned concurrency → not supported → pick one strategy per function version.
- Timeout equal to the API Gateway integration timeout → API returns 503/504 while the function keeps running → keep function timeouts below the API's timeout and use
RemainingTimebudgets. - Wrong handler string →
Could not find the specified handler assembly→ copy the generated handler from the build output orserverless.template. - Building on Windows for Native AOT → wrong binary format → build in the Amazon Linux build container.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Could not find the specified handler assembly with the file name … | Handler string does not match assembly/type/method | Use the generated handler from serverless.template |
Runtime.ExitError on init | Exception in startup (missing env var, DI error) | Read the log stream; fail-fast messages show the cause |
Task timed out after 10.00 seconds | Slow downstream call, VPC without endpoints, cold start plus work | Add timeouts per call; check VPC egress; raise memory |
AccessDeniedException from DynamoDB | Execution role missing action or ARN | Fix the role's inline policy |
API returns {"message":"Internal Server Error"} | Function threw or returned a malformed response | Check the function logs; ensure the handler returns IHttpResult |
API returns 403 Forbidden / Missing Authentication Token | Route mismatch, or the invoke permission's source ARN does not match | Check route key and add-permission source ARN |
exec format error / Runtime.InvalidEntrypoint with Native AOT | Built for wrong OS/architecture or wrong runtime | Build in the Amazon Linux container; use provided.al2023 and handler bootstrap |
SnapStart version stuck in Pending or Failed | Init code failed during snapshot | Check the version's logs; init must succeed without per-request data |
Cost and cleanup
What this lesson costs: a few hundred test invocations at 512 MB and well under a second each fall entirely within the Lambda free tier (1 million requests and 400,000 GB-seconds per month). An HTTP API costs about USD 1.00 per million requests ⚠ VERIFY, so lab traffic is a fraction of a cent. SnapStart adds a cache charge while a SnapStart-enabled version exists (minimum 3 hours): for 512 MB that is about 0.5 GB × 10,800 s × USD 0.0000015046 ≈ USD 0.008, plus tiny restore charges. Label: free (cents if you try SnapStart).
Teardown:
export AWS_PROFILE=learn-sandbox AWS_REGION=us-east-1
FN=hl-m03-get-account
aws apigatewayv2 delete-api --api-id "$API_ID"
# Deleting the function deletes all versions and aliases, which stops SnapStart cache charges.
aws lambda delete-function --function-name $FN
aws logs delete-log-group --log-group-name /aws/lambda/$FN
aws iam delete-role-policy --role-name $FN-role --policy-name runtime
aws iam delete-role --role-name $FN-role
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab --query 'ResourceTagMappingList[].ResourceARN'Exercises
- 🟢 Guided: Build, test and deploy the Annotations function above. Invoke it 20 times through the HTTP API, then find the one
REPORTline withInit Duration. - 🟡 Challenge: Measure cold start at 256 MB, 512 MB, 1,024 MB and 1,769 MB on arm64 (force a cold start by changing an environment variable between runs). Plot init duration and cost per 1,000 cold invocations. Then enable SnapStart on a published version and compare.
- 🔴 Live problem: Ticket INC-5120: "After enabling SnapStart on the payment-initiation function, the fraud team sees duplicate
X-Request-Noncevalues across different customers' requests." Explain the root cause, the fix, and how you would test for it.
Assignment
Add a lambda/ folder to your portfolio repository with the Annotations function, its unit tests, and a COLD-STARTS.md table of your challenge measurements (memory, architecture, init/restore duration, cost per million cold invocations) and a one-paragraph recommendation for Harbourline's Partner Gateway.
Solutions
dotnet test first (no AWS needed). Then follow the CLI section: log group, role, dotnet lambda package, create-function, create-api, add-permission. The first call shows Init Duration in its REPORT line; the next 19 reuse the warm environment unless calls overlap (concurrent calls create extra environments, each with its own cold start). Why: each execution environment serves one request at a time, so concurrency equals the number of environments.
Typical pattern: init duration falls sharply from 256 MB to about 1,024 MB, then flattens; 1,769 MB gives a full vCPU. Because you pay GB-seconds, a larger memory size can cost the same or less if it shortens duration enough. SnapStart's restore duration is usually much lower and less sensitive to memory, but adds the cache charge per active version. Record that SnapStart needs a published version — invoking $LATEST shows no change. Why: CPU share is proportional to memory, and JIT plus assembly loading are CPU-bound.
The nonce generator (for example a Random instance seeded in a static field, or a pre-generated pool of GUIDs) was initialised during init. SnapStart snapshots memory after init, so every restored environment starts from the same state and produces the same sequence. Fix: generate nonces inside the handler with a cryptographically secure source (RandomNumberGenerator, Guid.CreateVersion7()), or re-seed in an after-restore hook. Test: publish a version, force several concurrent cold restores (for example 20 parallel requests after a config change), and assert that no two responses share a nonce. Also review all init-time state: cached credentials, timestamps and connection pools.
Knowledge check
Answer: The execution environment is reused across invocations. A client created during init (DI singleton or static) keeps its HTTP connections and resolved credentials, so warm invocations are faster and do not exhaust sockets.
Answer: No. SnapStart supports managed runtimes (.NET 8 and later), while Native AOT functions run on the OS-only runtime provided.al2023, which SnapStart does not support.
Answer: That the invocation was a cold start, and how long the init phase (runtime start, assembly load, constructors and static initialisers) took. It is absent on warm invocations.
Answer: ASP.NET Core in Lambda with Amazon.Lambda.AspNetCoreServer.Hosting — call AddAWSLambdaHosting(LambdaEventSource.HttpApi) and use the assembly name as the handler.
Answer: 900 seconds (15 minutes). Longer work belongs on ECS/Fargate, AWS Batch, or a Step Functions workflow that splits the job into shorter steps.
Interview questions
- "How do you reduce .NET cold starts on Lambda?" — Measure first (
Init Duration). Then: right-size memory, ARM64, ReadyToRun, trim start-up work and dependencies; SnapStart for managed runtimes; Native AOT for small, controlled functions; provisioned concurrency when you need guaranteed warm capacity and can pay for it. Mention the mutual exclusions. - "Annotations vs ASP.NET Core in Lambda?" — Annotations: one function per operation, small, fast, fine-grained IAM and scaling, generated template. ASP.NET Core: fastest way to port an existing API, but bigger cold start, one role for all routes and coarser metrics.
- "How would you deploy a Lambda change safely?" — Publish versions, route through an alias, shift traffic with CodeDeploy (canary or linear) and roll back on CloudWatch alarms; never point production at
$LATEST. - "Lambda or Fargate for a bank API?" — Lambda for spiky, event-driven or low-volume APIs; Fargate for steady traffic, long requests, websockets or when cold starts are unacceptable without paying for provisioned concurrency.
Certification practice
A .NET 10 Lambda function behind API Gateway has occasional 2-second responses after idle periods. The team wants to reduce these with the least ongoing cost and no code rewrite. The function uses the dotnet10 managed runtime and is invoked through an alias. What should they do?
A. Enable SnapStart for published versions and point the alias at a newly published version. B. Configure provisioned concurrency of 50 on the alias permanently. C. Rewrite the function in Native AOT and enable SnapStart. D. Increase the function timeout to 900 seconds.
Answer: A. SnapStart restores from a snapshot of the initialised environment and supports .NET managed runtimes on published versions. B works but bills continuously. C is invalid: Native AOT uses an OS-only runtime, which SnapStart does not support. D does not affect start-up time.
A function creates a new AmazonDynamoDBClient and HttpClient at the start of every invocation. Under load, latency rises and some calls fail with socket errors. What change follows Lambda best practice?
A. Increase memory to 10,240 MB. B. Create the clients once during initialisation (static or DI singleton) and reuse them across invocations. C. Set reserved concurrency to 1. D. Move the function into a VPC.
Answer: B. Execution environments are reused; initialising clients once reuses connections and credentials. A hides the symptom at high cost. C throttles the workload. D adds networking overhead and does not fix client reuse.
A bank must process uploaded payment files. Files arrive unpredictably, 0–200 per hour, and each takes 20–40 seconds to validate. The solution must minimise cost when idle and scale automatically. Which compute option fits best?
A. ECS on Fargate service with a desired count of 2. B. AWS Lambda triggered by S3 event notifications (optionally through SQS for buffering and retries). C. A single EC2 instance polling S3 every minute. D. Elastic Beanstalk web server environment.
Answer: B. Event-driven, well under 15 minutes per file, zero idle cost, automatic scaling; SQS adds buffering and retries. A and D cost money while idle. C is a single point of failure and polls inefficiently.
Completion checklist
- I can explain init, invoke and execution-environment reuse
- I built and unit-tested an Annotations function without AWS
- I deployed it on
dotnet10arm64 behind an HTTP API (free tier) - I measured a cold start and know which optimisations can be combined
- I deleted the API, function, log group and role
Key takeaways
- Lambda runs one request per execution environment; initialise once, reuse everywhere (clients, DI, configuration).
- For new C# functions, Annotations gives DI, routing and a generated template; ASP.NET Core in Lambda is the porting path.
- Measure
Init Duration, then choose: memory, ARM64, ReadyToRun, SnapStart (managed runtime, versions only), Native AOT (provided.al2023) or provisioned concurrency — they are not all combinable. - Production functions use versions and aliases, a role per function, an authorizer in front, and log groups with retention.
- Lambda is ideal for spiky and event-driven work; steady, latency-critical APIs are often better on Fargate.
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.
Elastic Beanstalk for .NET
Deploy an ASP.NET Core API to Elastic Beanstalk on the .NET 10 Amazon Linux 2023 platform, understand every resource Beanstalk creates for you, harden the environment, and know when the Windows/IIS platform is the right choice.
Configuration done right
Layer ASP.NET Core configuration from appsettings.json through environment variables to Systems Manager Parameter Store and AWS AppConfig, validate it at start-up, reload it safely, and roll out feature flags gradually with automatic rollback.