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

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.

intermediate⏱ 2 h 🟢 FreeDVA-C03SAA-C03

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 dotnet10 managed 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 templates dotnet new install Amazon.Lambda.Templates and 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:

  1. 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.
  2. Invoke. Lambda calls your handler with the event. The environment handles one request at a time.
  3. 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.
  4. Scale. If 50 requests arrive at once, Lambda creates up to 50 environments (subject to concurrency limits). Each has its own cold start.
  5. 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):

ItemValue
.NET managed runtimedotnet10 on Amazon Linux 2023, deprecation scheduled 2028-11-14. dotnet8 was deprecated on 2026-11-10
Architecturesx86_64 and arm64 (Graviton) for every supported runtime
Memory128 MB to 10,240 MB; CPU is allocated in proportion to memory
Timeoutup to 900 seconds (15 minutes)
Synchronous request/response payload6 MB each way
/tmp storage512 MB to 10,240 MB
Deployment package50 MB zipped (direct upload) / 250 MB unzipped; container images up to 10 GB
Default concurrency1,000 concurrent executions per Region (a soft quota)
Free tier1 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 /tmp or 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 equivalentWhat's different
Azure Functions (isolated worker)Lambda dotnet10One function = one handler. No host.json; settings live on the function (memory, timeout, env vars)
Function triggers and bindingsEvent source mappings (SQS, Kinesis, DynamoDB) and service integrations (S3, EventBridge, API Gateway)No output bindings: call other services with the SDK
[Function] + [HttpTrigger] attributesLambda Annotations [LambdaFunction] + [HttpApi]Annotations is a source generator: it writes the handler wrapper and a CloudFormation/SAM template at build time
Consumption planOn-demand LambdaLambda scales per request; no plan; free tier is per account
Premium plan "always ready" instancesProvisioned concurrencyBilled for every hour it is configured
Flex Consumption / snapshot-based start-upSnapStartSnapshot taken when a version is published
Azure Functions on ASP.NET Core integrationAmazon.Lambda.AspNetCoreServer.HostingYour whole Minimal API runs inside one function
Managed identityFunction execution roleAssumed automatically; the SDK finds credentials in environment variables
Application settingsEnvironment variables (encrypted at rest with KMS)Limit of 4 KB total for all variables
Deployment slotsVersions and aliases with weighted routingCanary via alias weights or CodeDeploy

Architecture

Security-boundary view:

BoundaryControl
Client → API GatewayTLS, JWT authorizer (Cognito), throttling, optionally WAF (REST APIs and CloudFront)
API Gateway → functionResource-based policy on the function: lambda:InvokeFunction allowed for that API's ARN only
Function → AWS servicesExecution role, least privilege, resource ARNs
Function → private resourcesOptional VPC attachment (ENIs in your subnets)
ConfigurationEnvironment variables encrypted with KMS; secrets fetched at runtime, not stored in variables

The four C# programming models

ModelHandler stringWhen to useCold start
Class-library handlerAssembly::Namespace.Class::MethodSimple event handlers; classic templatesMedium
Executable assembly (Amazon.Lambda.RuntimeSupport, LambdaBootstrapBuilder)Assembly nameFull control over start-up; required for Native AOT and custom runtimesMedium; lowest with Native AOT
Lambda AnnotationsGenerated, e.g. Assembly::Namespace.Class_Method_Generated::MethodMost new functions: DI, route and parameter binding, generated SAM templateMedium; works with Native AOT and SnapStart
ASP.NET Core in Lambda (AddAWSLambdaHosting)Assembly namePorting an existing Minimal API or MVC app; one function serves many routesHighest (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:

labs/m03-accounts-api/src/Harbourline.Accounts.Api/Program.cs (excerpt)
builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi); // does nothing outside Lambda

AddAWSLambdaHosting 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

  1. Console → CloudWatch → Log groups → Create log group. Name /aws/lambda/hl-m03-get-account, retention 1 week.
  2. Console → IAM → Roles → Create role. Trusted entity AWS service → Lambda. Skip managed policies; after creation add an inline policy allowing logs:CreateLogStream and logs:PutLogEvents on the log group ARN and dynamodb:GetItem on the table ARN.
  3. 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.
  4. Code → Upload from → .zip file and upload the package. Under Runtime settings → Edit, set the handler printed by the build (see below).
  5. Configuration → General configuration → Edit: memory 512 MB, timeout 10 s. Configuration → Environment variables: TABLE_NAME=hl-m03-accounts.
  6. Test tab → create an event from the API Gateway HTTP API template, set pathParameters.accountId to a seeded account ID, and run it. Expand Details to see Init Duration.
  7. Console → API Gateway → Create API → HTTP API → Build. Integration Lambda, function hl-m03-get-account, route GET /accounts/{accountId}, stage $default with auto-deploy. The console adds the invoke permission for you.
  8. SnapStart: Lambda → Configuration → General configuration → SnapStart: PublishedVersions, then Actions → Publish new version, and point an alias live at 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

LambdaStack.cs
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

src/Harbourline.Accounts.Functions/Harbourline.Accounts.Functions.csproj
<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>
src/Harbourline.Accounts.Functions/AccountReader.cs
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));
    }
}
src/Harbourline.Accounts.Functions/Startup.cs
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));
    }
}
src/Harbourline.Accounts.Functions/AccountFunctions.cs
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);
    }
}
tests/Harbourline.Accounts.Functions.Tests/AccountFunctionsTests.cs
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

  1. GenerateRuntimeConfigurationFiles — produces Harbourline.Accounts.Functions.runtimeconfig.json, which the managed runtime needs to load the assembly.
  2. 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 arm64 does this).
  3. 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 your IHttpResult back into a response, and updates serverless.template.

Reader

  1. IAmazonDynamoDB injected, not created — one client per execution environment, reused across invocations. Creating clients per invocation wastes init time and sockets.
  2. ProjectionExpression with #s — fetch only needed attributes; status is a DynamoDB reserved word, so it needs a placeholder.
  3. response.Item is not { Count: > 0 } — SDK v4 returns null for a missing item's attribute map instead of an empty dictionary.
  4. decimal.Parse(..., InvariantCulture) — DynamoDB numbers are strings; parse them as decimal with an invariant culture so a server locale cannot change the decimal separator.

Startup

  1. [LambdaStartup] — Annotations calls ConfigureServices once during init. The DI container lives as long as the execution environment.
  2. TABLE_NAME check — fail fast during init with a clear message rather than on the first request.

Function

  1. [assembly: LambdaSerializer(...)] — System.Text.Json serializer for events and responses.
  2. [GeneratedRegex] — the regex is compiled at build time (no runtime regex compilation during cold start) and is trimming/AOT-safe.
  3. [LambdaFunction(MemorySize = 512, Timeout = 10)] — written into the generated SAM template. If you deploy with the CLI or CDK, the values there win.
  4. [HttpApi(LambdaHttpMethod.Get, "/accounts/{accountId}")] — the route; the accountId parameter is bound from the path by name.
  5. 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.
  6. context.Logger.LogInformation — writes to CloudWatch Logs with the request ID. Never log balances, IBANs or names.
  7. HttpResults.Ok/NotFound/BadRequest — Annotations helpers that produce the correct HTTP API response shape.

Tests

  1. 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.

TechniqueWhat it doesCostConstraints
More memoryCPU scales with memory, so init and JIT run fasterHigher GB-second price, but shorter duration often offsets itMeasure; there is a sweet spot
ARM64Graviton, about 20% cheaper per GB-secondCheaperNative dependencies must support arm64
ReadyToRunLess JIT at start-upBigger packageBuild per architecture
Trim dependenciesFewer assemblies to loadFreeAvoid reflection-heavy libraries in hot start-up paths
Native AOTCompiles the whole app to a native executable; no JIT at allFreeUses 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
SnapStartLambda snapshots the initialised environment when you publish a version and restores from itCache charge per GB-second while the version is active (minimum 3 hours) and a restore charge per GBManaged 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 concurrencyKeeps N environments initialised all the timeBilled per hour configured, whether used or notNot 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-permission call uses --source-arn with 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 dotnet10 runtime 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 HttpClient inside 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 $LATEST in 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 RemainingTime budgets.
  • Wrong handler string → Could not find the specified handler assembly → copy the generated handler from the build output or serverless.template.
  • Building on Windows for Native AOT → wrong binary format → build in the Amazon Linux build container.

Troubleshooting

SymptomLikely causeFix
Could not find the specified handler assembly with the file name …Handler string does not match assembly/type/methodUse the generated handler from serverless.template
Runtime.ExitError on initException in startup (missing env var, DI error)Read the log stream; fail-fast messages show the cause
Task timed out after 10.00 secondsSlow downstream call, VPC without endpoints, cold start plus workAdd timeouts per call; check VPC egress; raise memory
AccessDeniedException from DynamoDBExecution role missing action or ARNFix the role's inline policy
API returns {"message":"Internal Server Error"}Function threw or returned a malformed responseCheck the function logs; ensure the handler returns IHttpResult
API returns 403 Forbidden / Missing Authentication TokenRoute mismatch, or the invoke permission's source ARN does not matchCheck route key and add-permission source ARN
exec format error / Runtime.InvalidEntrypoint with Native AOTBuilt for wrong OS/architecture or wrong runtimeBuild in the Amazon Linux container; use provided.al2023 and handler bootstrap
SnapStart version stuck in Pending or FailedInit code failed during snapshotCheck 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 REPORT line with Init 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-Nonce values 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

Knowledge check

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

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 dotnet10 arm64 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.

On this page