Lambda - Serverless Computing
Lambda is AWS's serverless computing service. You write C# code, AWS runs it. No servers to manage, no infrastructure to maintain. Just C# code that runs when you need it.
What is Lambda?
Lambda lets you run C# code without provisioning or managing servers. You upload your .NET code, and AWS handles everything else:
Scaling
Automatic
Pay Per Use
Milliseconds
Languages
C#, .NET 6/8
Setting Up .NET for Lambda
-
Install the AWS .NET SDK:
dotnet add package AWSSDK.Lambda -
Install the Lambda .NET Core Global Tool:
dotnet tool install -g Amazon.Lambda.Tools -
Create a new Lambda project:
dotnet new lambda.EmptyFunction -n MyCSharpLambda -
Deploy your function:
dotnet lambda deploy-function MyCSharpLambda
Your Third Mission: Create a C# Lambda Function
-
Go to Lambda: Type
Lambdain the search bar and click it. - Click "Create function".
-
Name it:
HelloWorldCSharp. -
Runtime: Choose
.NET 6or.NET 8. -
Architecture: Choose
x86_64orarm64. - Click "Create function" (the orange button).
- Scroll down to the code editor. You will see default C# code.
- Click "Test" (the orange button right above the code).
-
Event name: Type
MyTest, ignore everything else, click "Save". - Click "Test" again.
- BOOM! You will see a green box at the top saying "Execution succeeded".
- AWS just woke up, ran your C# code for 100 milliseconds, gave you a response, and went back to sleep. You just did "Serverless" computing with C#!
C# Lambda Code Examples
1. Basic C# Lambda Function
// Using Amazon.Lambda.Core
using Amazon.Lambda.Core;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
public class Function
{
/// <summary>
/// A simple function that takes a string and returns a greeting
/// </summary>
public string FunctionHandler(string name, ILambdaContext context)
{
return $"Hello, {name ?? "World"}!";
}
}
2. Lambda with Input Parameters
using Amazon.Lambda.Core;
using System.Text.Json;
[LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
public class Function
{
public class Request
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Response
{
public string Message { get; set; }
public bool IsAdult { get; set; }
}
public Response FunctionHandler(Request request, ILambdaContext context)
{
return new Response
{
Message = $"Hello, {request.Name}!",
IsAdult = request.Age >= 18
};
}
}
3. Lambda with S3 Integration
using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using System.Text.Json;
[LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
public class Function
{
private readonly IAmazonS3 _s3Client;
public Function()
{
_s3Client = new AmazonS3Client();
}
public async Task<string> FunctionHandler(S3Event s3Event, ILambdaContext context)
{
foreach (var record in s3Event.Records)
{
var bucketName = record.S3.Bucket.Name;
var objectKey = record.S3.Object.Key;
// Get the object from S3
var response = await _s3Client.GetObjectAsync(bucketName, objectKey);
using (var reader = new StreamReader(response.ResponseStream))
{
var content = await reader.ReadToEndAsync();
context.Logger.LogInformation($"File content: {content}");
}
}
return "S3 event processed successfully!";
}
}
4. Lambda with API Gateway (HTTP API)
using Amazon.Lambda.Core;
using Amazon.Lambda.APIGateway.Events;
using System.Text.Json;
[LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
public class Function
{
public async Task<APIGatewayHttpApiV2ProxyResponse> FunctionHandler(
APIGatewayHttpApiV2ProxyRequest request,
ILambdaContext context)
{
// Get the HTTP method
var httpMethod = request.RequestContext.Http.Method;
// Get query parameters
var name = request.QueryStringParameters?.GetValueOrDefault("name") ?? "World";
// Create response body
var responseBody = new
{
Message = $"Hello, {name}!",
Method = httpMethod,
Timestamp = DateTime.UtcNow
};
return new APIGatewayHttpApiV2ProxyResponse
{
StatusCode = 200,
Headers = new Dictionary<string, string>
{
{ "Content-Type", "application/json" },
{ "Access-Control-Allow-Origin", "*" }
},
Body = JsonSerializer.Serialize(responseBody)
};
}
}
Key Lambda Concepts
| Concept | Description | C# Implementation |
|---|---|---|
| Function | Your C# code that runs when triggered | public class Function |
| Handler | The method that gets called | FunctionHandler() |
| Trigger | What causes your function to run | API Gateway, S3, SNS, etc. |
| LambdaSerializer | Serializes JSON input/output | [LambdaSerializer] attribute |
| ILambdaContext | Info about execution environment | ILambdaContext context |
| Timeout | Max time your function can run | 15 minutes max, 5 minutes default |
| Memory | RAM allocated to your function | 128 MB to 10 GB |
Exercise: Create a C# Weather API
Task: Create a C# Lambda function that returns weather data.
- Create a new .NET 6 Lambda function named "WeatherAPI".
- Write C# code that takes a city name as input.
- Return mock weather data (temperature, conditions, humidity).
- Test the function with different city names.
- Add API Gateway trigger to access it via HTTP.
- Test the API URL in your browser.
Show Solution
using Amazon.Lambda.Core;
using Amazon.Lambda.APIGateway.Events;
using System.Text.Json;
[LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
public class Function
{
private static readonly Random _random = new Random();
private static readonly string[] _conditions = { "Sunny", "Cloudy", "Rainy", "Snowy", "Windy" };
public APIGatewayHttpApiV2ProxyResponse FunctionHandler(
APIGatewayHttpApiV2ProxyRequest request,
ILambdaContext context)
{
// Get city from query string
var city = request.QueryStringParameters?.GetValueOrDefault("city") ?? "Unknown";
// Generate mock weather data
var weather = new
{
City = city,
Temperature = _random.Next(-10, 41),
Conditions = _conditions[_random.Next(_conditions.Length)],
Humidity = _random.Next(20, 91),
WindSpeed = _random.Next(0, 51),
Timestamp = DateTime.UtcNow
};
return new APIGatewayHttpApiV2ProxyResponse
{
StatusCode = 200,
Headers = new Dictionary<string, string>
{
{ "Content-Type", "application/json" },
{ "Access-Control-Allow-Origin", "*" }
},
Body = JsonSerializer.Serialize(weather)
};
}
}
Key Takeaway
Lambda is the easiest way to run C# code in the cloud. No servers to manage. Just write C# code, upload it, and AWS handles the rest. You get 1 million requests for FREE every month, forever! Use .NET 6 or 8 for the best performance.