Skip to Content
Cloud Engineering Academy
13. Microsoft-to-AWS Migration

Azure Functions to AWS Lambda

Translate Azure Functions triggers, bindings, hosting plans and Durable Functions into Lambda event source mappings, SDK calls, concurrency settings and Step Functions, and port a queue-triggered payment function to a Lambda handler with partial batch failure handling.

intermediate⏱ 1 h 30 min🟢 FreeDVA-C03SAA-C03SAP-C03

Assumes: .NET 10 LTS (Lambda dotnet10 runtime) · Amazon.Lambda.Core · Amazon.Lambda.SQSEvents · AWS SDK for .NET v4 · AWS CDK v2 (C#) · Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lesson you can:

  • Map Azure Functions triggers (HTTP, timer, queue, Service Bus, Blob, Event Grid, Cosmos DB change feed) to the AWS trigger that replaces each.
  • Explain why Azure bindings become explicit SDK calls (or event source mappings) on Lambda, and what that costs and gains.
  • Write a Lambda handler in C# for an SQS-triggered function with partial batch failure reporting.
  • Choose between AWS Step Functions and Lambda durable functions as the replacement for Azure Durable Functions.
  • Compare Azure hosting plans with Lambda concurrency, provisioned concurrency and cold-start options.

Prerequisites

  • Hosting side by side
  • Lambda with C# for the full Lambda programming model
  • SQS in depth, helpful for batch and visibility timeout behaviour
  • Tools: .NET 10 SDK, Docker (for tests), AWS CLI v2 with learn-sandbox for the optional deploy

Why this matters in banking

Harbourline has about forty Azure Functions: a nightly statement trigger, a queue consumer that books card authorisations, a Blob-triggered file importer, and a Durable Functions workflow that approves large payments. They look small, so migration plans give them a week. Then the team finds that a Functions queue trigger silently retries and poison-queues messages, a Blob trigger polls, and the approval workflow stores its state in an Azure Storage account the code never mentions. On Lambda each of these behaviours exists but is configured elsewhere. A function that "worked" can double-book a payment if retries are not made idempotent.

Functions are the place where migrations lose duplicate-detection and ordering guarantees without noticing. This lesson names every behaviour you must carry across.

The idea in plain language

Both products run a small piece of code when something happens, and bill you for the time it runs. Differences are in how the "something happens" part is wired.

  • In Azure Functions, the host is a runtime that polls the queue or storage account for you and calls your method. Triggers start the function; bindings hand your method inputs and outputs (a blob, a queue message) as parameters, so you rarely call a storage SDK yourself.
  • In AWS Lambda, a separate AWS service does the polling or event routing: an event source mapping (for SQS, Kinesis, DynamoDB Streams), an EventBridge rule, an S3 event notification or an API Gateway / function URL invokes your handler with an event object. Your code reads the event and, for outputs, calls the AWS SDK (or returns a value).

Analogy: Azure Functions is a receptionist who opens the post, unpacks parcels and puts them on your desk (bindings). Lambda is a mailroom with a rule book (event source mappings): it delivers the envelope to your desk, but if you want to send a parcel out, you walk to the post office (the SDK) yourself.

What problem the AWS service solves

Lambda is for short, event-driven work that scales from zero to thousands of concurrent invocations with no servers. Honest limits to know before moving a function:

LimitValueWhy it matters
Maximum run time per invocation15 minutesAzure Consumption plans have shorter limits, but Premium and Dedicated can run longer; long jobs move to Step Functions, ECS or Batch
Memory128 MB to 10,240 MB; CPU scales with memoryYou tune cost and speed with one setting
Synchronous payload6 MB request and responseLarge files go through S3, not through the event
ConcurrencyDefault account limit per Region (raise by request); reserved and provisioned concurrency availableOne function can starve another unless you reserve capacity ⚠ VERIFY the current default
PackageZip or container image up to 10 GBContainer images ease large .NET dependencies

The .NET managed runtime for Lambda is dotnet10 (generally available since 2026-01-08), so a .NET 10 function needs no custom runtime.

Microsoft / Azure comparison

You know (Azure Functions)AWS equivalentWhat's different
HTTP triggerFunction URL or API Gateway (HTTP/REST API) invoking LambdaAPI Gateway adds authorisers, throttling and keys; a function URL is a bare HTTPS endpoint with IAM or no auth
Timer trigger (CRON)EventBridge Scheduler or an EventBridge rule on a scheduleThe schedule is a separate resource; it does not live in your function code
Storage Queue / Service Bus queue triggerSQS event source mappingAWS polls for you; you set batch size, batching window, concurrency and ReportBatchItemFailures
Service Bus topic subscription triggerSNS topic subscribed to SQS or Lambda, or an EventBridge ruleFilter rules live on the subscription
Blob triggerS3 event notification to Lambda, SQS or EventBridgeS3 pushes events; Azure's older Blob trigger polls
Event Grid triggerEventBridge rule targeting LambdaSame idea: rule matches, target invoked
Cosmos DB change feed triggerDynamoDB Streams or Kinesis event source mappingStream records are retained for 24 hours (DynamoDB Streams); plan for catch-up
Input and output bindingsSDK calls inside the handler (AmazonS3Client, AmazonSQSClient) or Lambda destinationsMore code, but explicit permissions in the function's role and no hidden host behaviour
host.json (batch sizes, retry)Event source mapping settings and the function's configurationRetry and DLQ behaviour sits on the mapping or the queue
Consumption planLambda on-demandScales to zero; pay per request and per GB-second
Premium plan (pre-warmed instances)Lambda provisioned concurrency (and SnapStart where supported)You pay for warm environments; ⚠ VERIFY SnapStart support for the dotnet10 runtime before relying on it
Flex ConsumptionLambda with reserved concurrency and memory tuningClosest in spirit; cost models differ, so compare with real traffic
Durable Functions orchestratorStep Functions state machine, or Lambda durable functionsSee the dedicated section below
Managed identity for the function appThe function's execution roleLeast privilege per function; the role holds the S3, SQS and Secrets Manager permissions your bindings once hid

Architecture

Security-boundary view. The mapping uses the function's execution role to read from the queue. Nothing needs inbound network access. Place the function in a VPC only if it must reach private resources such as an RDS instance; doing so adds ENI and NAT considerations.

Durable Functions: where does the state go?

Azure Durable Functions are an orchestrator function that calls activity functions, with progress stored in storage and replayed after each await. Common patterns map like this:

Durable patternStep FunctionsLambda durable functions
Function chainingSequence of Task statesSequential awaits in code
Fan-out / fan-inMap or Parallel stateParallel operations in code
Human interaction with timeoutTask token (waitForTaskToken) plus a Wait or heartbeat timeoutCallback or wait operations
Durable timerWait stateWait operation
Eternal orchestration (loop)Loop with Choice, or a scheduled startLoop in code, with care for history size

AWS offers two answers:

  1. AWS Step Functions. The workflow is a JSON (Amazon States Language) definition outside your code, visible in a console, with built-in retries, catch and service integrations. Best when the workflow should be inspected by non-developers or integrates many AWS services.
  2. Lambda durable functions. You write the workflow as ordinary code and the service checkpoints it. The AWS Lambda Durable Execution SDK for .NET reached general availability in July 2026 (announcement); AWS's supported-runtimes page lists the .NET managed runtimes for durable functions, and the SDK ships in your deployment package rather than the runtime. Best when the logic is mostly C# and the team wants to stay in code. Regional availability varies, so check the Regional Services list for your Region ⚠ VERIFY, and check the SDK's current API before writing code against it ⚠ VERIFY.

Rule of thumb for Harbourline: regulated approval flows with audit visibility go to Step Functions; code-heavy orchestration with little AWS service plumbing is a candidate for durable functions.

A taste of the Step Functions shape for "approve a large payment within 24 hours":

{
  "Comment": "Large payment approval with 24h timeout",
  "StartAt": "RequestApproval",
  "States": {
    "RequestApproval": {
      "Type": "Task",
      "Resource": "arn:aws:states:::sqs:sendMessage.waitForTaskToken",
      "Parameters": {
        "QueueUrl": "https://sqs.us-east-1.amazonaws.com/111122223333/hl-m13-approvals",
        "MessageBody": { "paymentId.$": "$.paymentId", "taskToken.$": "$$.Task.Token" }
      },
      "TimeoutSeconds": 86400,
      "Catch": [{ "ErrorEquals": ["States.Timeout"], "Next": "AutoReject" }],
      "Next": "Execute"
    },
    "Execute": { "Type": "Pass", "End": true },
    "AutoReject": { "Type": "Pass", "End": true }
  }
}

The account ID in the queue URL is a placeholder.

Step-by-step implementation

List what each Azure function really does

For every function, write: trigger, bindings, retry policy, poison handling, state, secrets, and the identity it uses. The bindings and retry settings are the migration items, because they were configuration rather than code.

Choose the AWS trigger

Use the table above. For queue consumers, decide batch size and whether ordering matters (ordering needs an SQS FIFO queue and message group IDs; see the integration lesson).

Port the handler

Move the business logic into a plain class with no Azure types. Write a thin Lambda entry point that parses the event and calls it. Replace each binding with an SDK call or a returned value.

Make it idempotent

Both platforms deliver messages at least once. Add an idempotency key check (a DynamoDB conditional write is the pattern from idempotency in .NET) before any money movement.

Wire retries and a dead-letter queue

Set the queue's redrive policy (maxReceiveCount) and turn on ReportBatchItemFailures so one bad message does not retry the whole batch.

Test locally, then deploy to the sandbox

Unit-test the logic and the handler with Amazon.Lambda.TestUtilities, then deploy with CDK and send a test message.

AWS Console instructions

Console → Lambda → Create function → Author from scratch, runtime .NET 10 (C#/F#/PowerShell). After creating it, open Configuration → Triggers → Add trigger → SQS to see the event source mapping settings (batch size, batching window, maximum concurrency, Report batch item failures). Compare these with the Azure host.json queue settings you are replacing.

AWS CLI

# Invoke a function with a test event (replace the function name; the event file is in Complete code).
aws lambda invoke --function-name hl-m13-authorisation-consumer \
  --cli-binary-format raw-in-base64-out --payload file://sqs-event.json \
  --profile learn-sandbox --region us-east-1 response.json
cat response.json

# See how the queue is wired to the function (batch size, failure reporting).
aws lambda list-event-source-mappings --function-name hl-m13-authorisation-consumer \
  --profile learn-sandbox --region us-east-1 \
  --query "EventSourceMappings[].[State,BatchSize,FunctionResponseTypes]"

Infrastructure as Code

AuthorisationConsumerStack.cs
using Amazon.CDK;
using Amazon.CDK.AWS.Lambda;
using Amazon.CDK.AWS.Lambda.EventSources;
using Amazon.CDK.AWS.SQS;
using Constructs;

public sealed class AuthorisationConsumerStack : Stack
{
    public AuthorisationConsumerStack(Construct scope, string id, IStackProps props) : base(scope, id, props)
    {
        var dlq = new Queue(this, "Dlq", new QueueProps { RetentionPeriod = Duration.Days(14), Encryption = QueueEncryption.SQS_MANAGED });

        var queue = new Queue(this, "Authorisations", new QueueProps
        {
            // Visibility timeout must exceed the function timeout (AWS recommends at least six times it).
            VisibilityTimeout = Duration.Seconds(180),
            Encryption = QueueEncryption.SQS_MANAGED,
            DeadLetterQueue = new DeadLetterQueue { Queue = dlq, MaxReceiveCount = 3 },
        });

        var fn = new Function(this, "Consumer", new FunctionProps
        {
            Runtime = Runtime.DOTNET_10,
            Handler = "Harbourline.Authorisations::Harbourline.Authorisations.Function::FunctionHandler",
            Code = Code.FromAsset("./src/Harbourline.Authorisations/bin/Release/net10.0/publish"),
            MemorySize = 512,
            Timeout = Duration.Seconds(30),
        });

        fn.AddEventSource(new SqsEventSource(queue, new SqsEventSourceProps
        {
            BatchSize = 10,
            ReportBatchItemFailures = true,
        }));

        Amazon.CDK.Tags.Of(this).Add("Project", "cea-lab");
        Amazon.CDK.Tags.Of(this).Add("Lab", "m13-lambda");
        Amazon.CDK.Tags.Of(this).Add("Environment", "learn");
    }
}

The IAM role aws_iam_role.consumer needs the AWS-managed AWSLambdaSQSQueueExecutionRole policy (or an equivalent least-privilege policy) and is omitted here for length.

Complete code

The Azure function being replaced, shown for comparison only:

Azure: AuthoriseCard.cs (before)
public class AuthoriseCard(ILogger<AuthoriseCard> log, IAuthoriser authoriser)
{
    [Function("AuthoriseCard")]
    public async Task Run(
        [ServiceBusTrigger("authorisations", Connection = "ServiceBus")] ServiceBusReceivedMessage message,
        ServiceBusMessageActions actions)
    {
        var request = message.Body.ToObjectFromJson<AuthorisationRequest>();
        await authoriser.AuthoriseAsync(request.AuthorisationId, request.Amount, request.Currency);
        await actions.CompleteMessageAsync(message); // explicit complete; abandon or dead-letter otherwise
    }
}

The Lambda replacement. Project Harbourline.Authorisations, packages Amazon.Lambda.Core, Amazon.Lambda.SQSEvents, Amazon.Lambda.Serialization.SystemTextJson:

Function.cs
using System.Text.Json;
using Amazon.Lambda.Core;
using Amazon.Lambda.SQSEvents;

[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace Harbourline.Authorisations;

public sealed record AuthorisationRequest(string AuthorisationId, decimal Amount, string Currency);

public interface IAuthoriser
{
    /// <summary>Must be idempotent: the same AuthorisationId can arrive more than once.</summary>
    Task AuthoriseAsync(string authorisationId, decimal amount, string currency, CancellationToken ct);
}

public sealed class Function
{
    private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
    private readonly IAuthoriser _authoriser;

    // Lambda calls the parameterless constructor. Real wiring (DI, clients) goes here; keep it cheap.
    public Function() : this(new LoggingAuthoriser()) { }

    public Function(IAuthoriser authoriser) => _authoriser = authoriser;

    public async Task<SQSBatchResponse> FunctionHandler(SQSEvent evt, ILambdaContext context)
    {
        var failures = new List<SQSBatchResponse.BatchItemFailure>();

        foreach (var record in evt.Records)
        {
            try
            {
                var request = JsonSerializer.Deserialize<AuthorisationRequest>(record.Body, Json)
                              ?? throw new JsonException("Empty body");
                await _authoriser.AuthoriseAsync(request.AuthorisationId, request.Amount, request.Currency, CancellationToken.None);
            }
            catch (Exception ex)
            {
                // Report only this message as failed; the others in the batch are deleted from the queue.
                context.Logger.LogError($"messageId={record.MessageId} failed: {ex.GetType().Name}");
                failures.Add(new SQSBatchResponse.BatchItemFailure { ItemIdentifier = record.MessageId });
            }
        }

        return new SQSBatchResponse(failures);
    }
}

public sealed class LoggingAuthoriser : IAuthoriser
{
    public Task AuthoriseAsync(string authorisationId, decimal amount, string currency, CancellationToken ct)
    {
        Console.WriteLine($"{{\"event\":\"authorised\",\"id\":\"{authorisationId}\",\"amount\":{amount},\"currency\":\"{currency}\"}}");
        return Task.CompletedTask;
    }
}
sqs-event.json
{
  "Records": [
    { "messageId": "m-1", "receiptHandle": "r-1", "body": "{\"authorisationId\":\"AUTH-0001\",\"amount\":25.50,\"currency\":\"GBP\"}", "eventSource": "aws:sqs" },
    { "messageId": "m-2", "receiptHandle": "r-2", "body": "not json", "eventSource": "aws:sqs" }
  ]
}

A unit test (xUnit v3) that proves one bad message does not fail the batch:

FunctionTests.cs
using Amazon.Lambda.SQSEvents;
using Amazon.Lambda.TestUtilities;
using Harbourline.Authorisations;
using Xunit;

public class FunctionTests
{
    private sealed class Recording : IAuthoriser
    {
        public List<string> Seen { get; } = [];
        public Task AuthoriseAsync(string id, decimal amount, string currency, CancellationToken ct)
        {
            Seen.Add(id);
            return Task.CompletedTask;
        }
    }

    [Fact]
    public async Task Bad_message_is_reported_and_good_message_is_processed()
    {
        var recorder = new Recording();
        var fn = new Function(recorder);
        var evt = new SQSEvent
        {
            Records =
            [
                new SQSEvent.SQSMessage { MessageId = "m-1", Body = """{"authorisationId":"AUTH-1","amount":5,"currency":"GBP"}""" },
                new SQSEvent.SQSMessage { MessageId = "m-2", Body = "not json" },
            ],
        };

        var result = await fn.FunctionHandler(evt, new TestLambdaContext());

        Assert.Equal(["AUTH-1"], recorder.Seen);
        Assert.Equal("m-2", Assert.Single(result.BatchItemFailures).ItemIdentifier);
    }
}

Code explained line by line

  1. [assembly: LambdaSerializer(...)] tells Lambda how to turn the incoming JSON into an SQSEvent. Without it, a handler with a typed event fails to deserialise.
  2. IAuthoriser isolates the business rule from Lambda types. This is what you move from the Azure class: the interface and its implementation have no ServiceBus* types.
  3. The handler loops over evt.Records. SQS can deliver up to the configured batch size in one invocation.
  4. Each record is processed inside its own try. A failure adds only that MessageId to BatchItemFailures.
  5. Returning SQSBatchResponse with failures makes Lambda delete the successful messages and leave the failed ones to reappear after the visibility timeout. If you return nothing (or throw), the whole batch is retried, which re-runs successful work.
  6. The parameterless constructor is what Lambda uses; the second constructor allows tests to inject a fake without a framework.
  7. In the test, TestLambdaContext stands in for the real context, and the assertions check both the processed ID and the reported failure.

Security considerations

⚠ Learning shortcut — not for production

LoggingAuthoriser writes the amount and authorisation ID to the console and accepts any caller. A production consumer authenticates the producer by queue policy (only the Payments service role may SendMessage), logs identifiers but never full card or personal data, writes an idempotency record before acting, and uses a customer managed KMS key if the queue holds regulated data.

  • Execution role per function, with only the queue, the table and the secret it needs. Azure bindings hid these permissions; now they are explicit.
  • Queue policy restricts who may send; encryption is on; DLQ retention is 14 days so investigators have time.
  • Poison messages are evidence. Do not auto-purge the DLQ; route alarms to the on-call rota.
  • Idempotency is a control, not a nicety. A retry after a timeout must never debit twice.
  • Logging hygiene. Log message IDs, not payloads, for anything that may hold personal data (UK GDPR data-minimisation applies to logs too).

Banking use case

The card-authorisation consumer is the template Harbourline reuses for thirty functions. The checklist the migration team writes per function is: trigger replaced, retry and DLQ set on the queue, idempotency key present, partial-batch failures enabled, execution role reviewed, alarm on DLQ depth, and a replay procedure for dead-lettered messages. The approval workflow goes to Step Functions because compliance wants to show an auditor the state machine and its execution history.

Common mistakes

  • Visibility timeout shorter than the function timeout. The message reappears while still being processed and runs twice. Set the queue visibility timeout well above the function timeout.
  • Throwing on one bad record. The whole batch retries. Use ReportBatchItemFailures.
  • Expecting Durable Functions replay semantics in a plain handler. Lambda handlers are stateless; keep state in DynamoDB, Step Functions or durable functions.
  • Putting a Lambda in a VPC "just in case". It adds networking complexity and may need NAT for AWS APIs; use VPC endpoints if you must.
  • Reading secrets on every invocation. Cache them in a static field or use the Parameters and Secrets Lambda extension; see the DevOps lesson.

Troubleshooting

SymptomLikely causeFix
Messages processed twiceVisibility timeout too low, or handler threw after partial successRaise visibility timeout; enable batch item failures; make processing idempotent
Unable to find a handler style errorsHandler string wrong (Assembly::Namespace.Class::Method)Correct the string; the assembly name is the project name
Whole batch retried on one errorReportBatchItemFailures not enabled on the mapping, or exception not caughtEnable it in the mapping and return SQSBatchResponse
Throttled invocations, queue backing upReserved or account concurrency reachedRaise limits or set maximum concurrency on the mapping
Cold starts of several secondsLarge .NET assemblies, JITIncrease memory, trim dependencies, consider Native AOT or provisioned concurrency

Cost and cleanup

Cost label: free within the always-free allowance for a handful of test messages (Lambda includes 1 million requests and 400,000 GB-seconds a month; SQS includes 1 million requests a month ⚠ VERIFY the current free tier). To stay safe, deploy, send a few messages, and destroy.

cdk destroy AuthorisationConsumerStack --profile learn-sandbox
# Terraform route:
terraform destroy
# Verify nothing is left
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab \
  --profile learn-sandbox --region us-east-1 --query "ResourceTagMappingList[].ResourceARN"

Exercises

  • 🟢 Guided: run the unit test in a Docker .NET 10 container, then change the test so that two of three messages fail and assert that exactly two IDs are reported.
  • 🟡 Challenge: add an idempotency check: a fake IIdempotencyStore with TryClaimAsync(id); skip processing when the claim fails. Test that a duplicate message is acknowledged but not re-processed.
  • 🔴 Live problem: an Azure timer function runs every night at 02:00 UK time, reads yesterday's blobs, and writes a summary. The team wants it on AWS "with no servers." Decide the triggers, the handling of daylight saving time, the failure alarm and where state lives, and say what happens if the run takes 20 minutes.

Assignment

Pick three real Azure Functions from your estate. For each, produce a one-row function migration card (trigger, bindings, retries, state, identity, AWS replacement, risks) and port one of them to a tested Lambda handler in your portfolio repository.

Solutions

Knowledge check

Interview questions

  • "What do you lose when you move from bindings to the SDK?" Convenience and implicit permissions. What you gain is explicit, testable code and a least-privilege role per function.
  • "A Lambda consumer processed a payment twice. Where do you look?" Visibility timeout versus function timeout, batch failure handling, and whether an idempotency key guards the write. Then the DLQ and CloudWatch logs for the message ID.
  • "Step Functions or durable functions?" Step Functions when the flow must be visible, audited and integrated with many AWS services; durable functions when the logic is code-heavy and the team wants one language.

Certification practice

Completion checklist

  • I can name the AWS replacement for each Azure Functions trigger
  • I ran the handler test and saw partial batch failure working
  • I can explain Step Functions versus Lambda durable functions in two sentences
  • I destroyed anything I deployed and ran the tag query

Key takeaways

  • Bindings become event source mappings plus SDK calls; permissions become the execution role.
  • Retries, batches and dead-letter behaviour live on the queue and the mapping, so migrate them on purpose.
  • At-least-once delivery means every money-moving function needs an idempotency check.
  • Durable Functions map to Step Functions or Lambda durable functions; choose by visibility and language preference.

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