Introduction
AWS Lambda is commonly used to run backend operations without managing servers. A .NET application can invoke a Lambda function, wait for execution to finish, and then receive the complete response. This traditional approach works well for most API operations, but it can become inefficient when a function generates a large response or produces information gradually.
Consider an application that uses an AI model to generate a response, exports thousands of records, or processes a large report. With a normal Lambda invocation, the caller generally waits until the function finishes generating the complete response. The function also needs to prepare the response before returning it.
AWS Lambda response streaming provides another approach. Instead of waiting for the complete response, a function can send data to the caller in smaller chunks as soon as the data becomes available.
AWS introduced response streaming support for .NET Lambda functions in August 2026. Developers can now use standard .NET streams to write response data and the AWS SDK for .NET to consume that data incrementally.
In this article, we will explore how Lambda response streaming works, how to implement a streaming .NET function, how to invoke it from another .NET application, and how to handle errors and cancellation.
What Is AWS Lambda Response Streaming?
Response streaming allows a Lambda function to return data incrementally instead of waiting until the complete response has been generated.
In a traditional invocation, the function creates the response, serializes it, and returns it to Lambda. The caller receives the response after the function completes.
With response streaming, the function writes data to a response stream. Lambda forwards the available data to the caller while the function continues processing.
For example, imagine a Lambda function that generates a report containing 50,000 records.
With a buffered response, the function may need to generate the complete report before returning anything. With response streaming, it can begin sending records while the remaining records are still being processed.
This approach is useful for:
- AI applications that generate text incrementally.
- Large CSV and JSON exports.
- Applications that process large datasets.
- Report generation services.
- Workloads that need lower time-to-first-byte latency.
- Applications that cannot efficiently hold the complete response in memory.
AWS Lambda response streaming supports response payloads up to 200 MB through the direct streaming invocation API. This is significantly higher than the 6 MB limit for a normal buffered synchronous response.
However, streaming does not automatically make every Lambda function faster. It provides the most benefit when the function can produce useful output before its complete execution finishes.
Buffered Responses vs. Streaming Responses
Before implementing response streaming, understand how it differs from the traditional invocation model.
Area | Buffered response | Streaming response |
|---|
Response delivery | After the complete response is ready | Incrementally as data is produced |
Memory usage | May require the complete response in memory | Can process and send smaller chunks |
Time to first byte | Depends on complete response generation | Can be lower |
Response size | 6 MB for synchronous buffered invocation | Up to 200 MB for direct response streaming |
Implementation | Return a response object or value | Write to a response stream |
Suitable workloads | Small API responses | Large or gradually generated responses |
The main difference is when the caller receives the data.
A buffered response is easier to implement and works well for ordinary API operations. Streaming is more useful when the response is large or when users benefit from receiving information before the entire operation finishes.
Installing the Required NuGet Packages
To implement response streaming in a .NET Lambda function, use the AWS Lambda Core package and a compatible version of the Lambda Runtime Support package.
Install the required packages:
dotnet add package Amazon.Lambda.Core
dotnet add package Amazon.Lambda.RuntimeSupport
dotnet add package Amazon.Lambda.Serialization.SystemTextJson
To invoke the function from another .NET application, install the AWS Lambda SDK package:
dotnet add package AWSSDK.Lambda
The packages have different responsibilities.
Package | Responsibility |
|---|
Amazon.Lambda.Core | Provides Lambda interfaces and response streaming APIs |
Amazon.Lambda.RuntimeSupport | Provides runtime support for .NET Lambda functions |
Amazon.Lambda.Serialization.SystemTextJson | Provides JSON serialization |
AWSSDK.Lambda | Allows applications to invoke Lambda functions through the AWS SDK |
Use compatible package versions and keep the Lambda runtime support library updated. Response streaming requires a current version of Amazon.Lambda.RuntimeSupport.
Creating a .NET Lambda Function That Streams Responses
Let's create a simple Lambda function that generates multiple messages and sends them to the caller incrementally.
The important API is LambdaResponseStreamFactory.CreateStream(). It creates a writable .NET Stream that Lambda uses to deliver response data.
The following example writes 100 messages to the response stream.
using Amazon.Lambda.Core;
using Amazon.Lambda.Core.ResponseStreaming;
[assembly: LambdaSerializer(
typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace StreamingLambda;
public class Function
{
public async Task FunctionHandler(
string input,
ILambdaContext context)
{
await using var responseStream =
LambdaResponseStreamFactory.CreateStream();
using var writer = new StreamWriter(responseStream);
for (int i = 1; i <= 100; i++)
{
await writer.WriteLineAsync(
$"Hello {input} - {i}");
if (i % 10 == 0)
{
await writer.FlushAsync();
}
}
}
}
The handler receives the input value and Lambda execution context.
It then creates a response stream using LambdaResponseStreamFactory. A StreamWriter is used to write text into the stream.
The function generates 100 messages, but it flushes the writer after every ten messages. Flushing is important because it pushes buffered writer content into the underlying response stream instead of waiting for the writer to finish.
Once the response stream has been created, the handler's normal return value is ignored. All response data must be written to the stream.
This is different from a traditional Lambda handler that returns a string, object, or serialized response.
Streaming HTTP Responses With a Lambda Function URL
When a Lambda function is accessed through a Function URL or API Gateway, the response may need HTTP information such as a status code and Content-Type header.
For this scenario, use LambdaResponseStreamFactory.CreateHttpStream().
The following example streams plain text through an HTTP response.
using Amazon.Lambda.Core;
using Amazon.Lambda.Core.ResponseStreaming;
using System.Net;
public class Function
{
public async Task FunctionHandler(
string input,
ILambdaContext context)
{
var prelude = new HttpResponseStreamPrelude
{
StatusCode = HttpStatusCode.OK,
Headers =
{
["Content-Type"] = "text/plain",
["Cache-Control"] = "no-cache"
}
};
await using var responseStream =
LambdaResponseStreamFactory.CreateHttpStream(prelude);
using var writer = new StreamWriter(responseStream);
for (int i = 1; i <= 5; i++)
{
await writer.WriteLineAsync(
$"Processing item {i} for {input}");
await writer.FlushAsync();
await Task.Delay(500);
}
}
}
The HttpResponseStreamPrelude defines the HTTP status code and response headers.
The CreateHttpStream method creates a response stream that includes this HTTP information before the response body.
The function writes one message at a time and flushes after each message. The delay is included to demonstrate incremental output; a production application would normally perform actual processing between writes.
This approach is useful for HTTP endpoints where the client should start receiving content before the complete operation finishes.
Invoking a Streaming Lambda Function From a .NET Application
Creating a streaming Lambda function is only one part of the implementation. The calling application must also use the streaming invocation API.
The AWS SDK for .NET provides InvokeWithResponseStreamAsync through the AmazonLambdaClient class.
First, install the AWS Lambda SDK:
dotnet add package AWSSDK.Lambda
Next, create an application that invokes the streaming function.
using Amazon.Lambda;
using Amazon.Lambda.Model;
using System.Text;
var client = new AmazonLambdaClient();
var request = new InvokeWithResponseStreamRequest
{
FunctionName = "StreamingLambda",
Payload = new MemoryStream(
Encoding.UTF8.GetBytes("\"World\""))
};
var response =
await client.InvokeWithResponseStreamAsync(request);
Console.WriteLine(
$"Status Code: {response.StatusCode}");
Console.WriteLine(
$"Executed Version: {response.ExecutedVersion}");
The request specifies the Lambda function name and the input payload.
The input is serialized as JSON because the Lambda handler expects a string. The request is sent through InvokeWithResponseStreamAsync instead of the normal InvokeAsync method.
The response contains an EventStream that exposes the data produced by the Lambda function.
The next step is reading the events.
Reading Streamed Response Chunks
The response stream contains different event types. The most important ones are:
Event | Purpose |
|---|
InvokeResponseStreamUpdate | Contains a chunk of response data |
InvokeWithResponseStreamCompleteEvent | Indicates that the response stream has completed |
The following example reads the chunks and writes them directly to the console.
using Amazon.Lambda.Model;
await foreach (var streamEvent in response.EventStream)
{
switch (streamEvent)
{
case InvokeResponseStreamUpdate payloadChunk:
{
if (payloadChunk.Payload != null)
{
await payloadChunk.Payload.CopyToAsync(
Console.OpenStandardOutput());
}
break;
}
case InvokeWithResponseStreamCompleteEvent completed:
{
if (!string.IsNullOrEmpty(completed.ErrorCode))
{
Console.WriteLine(
$"Lambda error: {completed.ErrorCode}");
Console.WriteLine(
completed.ErrorDetails);
}
break;
}
}
}
Each InvokeResponseStreamUpdate event contains a portion of the response payload.
The application copies that portion to the console output stream without first collecting the entire response in memory.
The completion event indicates that Lambda has finished sending the response. It can also contain error information.
This event-based approach allows the calling application to process data as it arrives rather than waiting for the complete response.
For a production application, send the chunks to the appropriate destination, such as an HTTP response, a file, or a processing pipeline.
Writing a Large Export Without Loading Everything Into Memory
One practical use case for response streaming is generating large CSV files.
Suppose a Lambda function reads records from a database and returns them as CSV. Creating one large string before returning the response can consume unnecessary memory.
Instead, the function can write each record directly to the response stream.
using Amazon.Lambda.Core;
using Amazon.Lambda.Core.ResponseStreaming;
public class ExportFunction
{
public async Task FunctionHandler(
string input,
ILambdaContext context)
{
var prelude = new HttpResponseStreamPrelude
{
StatusCode = System.Net.HttpStatusCode.OK,
Headers =
{
["Content-Type"] = "text/csv",
["Content-Disposition"] =
"attachment; filename=report.csv"
}
};
await using var responseStream =
LambdaResponseStreamFactory.CreateHttpStream(prelude);
using var writer = new StreamWriter(responseStream);
await writer.WriteLineAsync(
"Id,Name,Amount");
await writer.FlushAsync();
for (int i = 1; i <= 10000; i++)
{
await writer.WriteLineAsync(
$"{i},Product-{i},{i * 10}");
if (i % 100 == 0)
{
await writer.FlushAsync();
}
}
}
}
The example generates CSV records in batches. It does not create a collection containing all 10,000 rows before writing the response.
In a real application, the loop could read records from a database using pagination or an asynchronous data reader.
This approach reduces the amount of application memory required for response generation. However, the database query itself must also be designed for streaming or bounded batches. Loading every database record into a list before writing it would remove much of the memory benefit.
Configuring Lambda Function URLs for Response Streaming
A Lambda function that writes to a response stream must be invoked through a streaming-enabled integration.
For Lambda Function URLs, the invoke mode determines whether the function uses buffered or streaming invocation.
The default mode is BUFFERED. To enable response streaming, configure the function URL to use RESPONSE_STREAM.
You can update the configuration through the AWS CLI:
aws lambda update-function-url-config \
--function-name StreamingLambda \
--invoke-mode RESPONSE_STREAM
The same configuration can be defined through infrastructure as code.
For example, the CloudFormation configuration is:
StreamingFunctionUrl:
Type: AWS::Lambda::Url
Properties:
TargetFunctionArn: !GetAtt StreamingLambda.Arn
AuthType: AWS_IAM
InvokeMode: RESPONSE_STREAM
When using API Gateway, the integration must also be configured for response streaming. A normal buffered Lambda proxy integration does not automatically become a streaming integration simply because the Lambda handler writes to a stream.
Always verify the complete request path, including the Lambda function, Function URL or API Gateway configuration, and the client.
Handling Errors and Cancellation
Streaming introduces additional error-handling considerations because some response data may already have reached the caller before an error occurs.
For example, a function may successfully send the first 20 records and then encounter a database connection failure.
The caller cannot assume that receiving some data means the complete operation succeeded.
Check the InvokeWithResponseStreamCompleteEvent for ErrorCode and ErrorDetails. Also handle exceptions raised while reading the EventStream.
Use cancellation tokens when the caller no longer needs the response.
using var cancellationSource =
new CancellationTokenSource(
TimeSpan.FromMinutes(5));
try
{
var response =
await client.InvokeWithResponseStreamAsync(
request,
cancellationSource.Token);
await foreach (
var streamEvent in response.EventStream
.WithCancellation(cancellationSource.Token))
{
if (streamEvent is InvokeResponseStreamUpdate chunk)
{
if (chunk.Payload != null)
{
await chunk.Payload.CopyToAsync(
Console.OpenStandardOutput(),
cancellationSource.Token);
}
}
else if (
streamEvent is InvokeWithResponseStreamCompleteEvent complete)
{
if (!string.IsNullOrEmpty(complete.ErrorCode))
{
throw new InvalidOperationException(
complete.ErrorDetails ??
complete.ErrorCode);
}
}
}
}
catch (OperationCanceledException)
{
Console.WriteLine(
"Lambda response streaming was cancelled.");
}
The cancellation token limits how long the application waits for the operation and its streamed events.
In production, distinguish between an invocation failure, a stream-reading failure, and a cancellation initiated by the caller. Log the Lambda request ID and execution details where available so that failures can be investigated.
Important Limits and Performance Considerations
AWS Lambda response streaming has several limits that developers should understand before using it in production.
- The direct response streaming API supports response payloads up to 200 MB.
- The first 6 MB of the response is delivered without the subsequent bandwidth restriction.
- After the first 6 MB, response bandwidth is limited to 2 MB per second.
- API Gateway has its own response size and integration limits. Its response streaming configuration supports up to 10 MB.
- Response streaming can increase network transfer costs.
- The client, SDK, firewall, and network infrastructure must allow long-lived connections.
Response streaming is available for .NET 8 and later Lambda functions. AWS also requires a current Lambda Runtime Support package.
Another important consideration is buffering outside Lambda. A proxy, gateway, or client may buffer incoming data even when Lambda is streaming correctly. Test the complete application path to verify that chunks reach the actual client incrementally.
Best Practices for Production Applications
Flush data at suitable intervals
Flushing after every small write can create unnecessary overhead. Choose a reasonable batch size based on the type of response and the required delivery speed.
Use asynchronous stream operations
Use asynchronous writing and reading methods so that network operations do not unnecessarily block application threads.
Avoid buffering the complete response
If the goal is to reduce memory consumption, generate output incrementally. Do not create a large string or collection before writing it to the response stream.
Validate the streaming integration
Check the Function URL invoke mode or API Gateway integration configuration. A streaming handler alone is not sufficient.
Handle partial results
Design the client to recognize incomplete responses. If a failure occurs after some chunks have been delivered, the application should not treat the partial data as a successful complete result.
Configure timeouts carefully
Long-running streaming operations require suitable timeouts across the Lambda function, SDK client, HTTP infrastructure, and downstream systems.
Monitor response generation
Measure time to first byte, total execution time, bytes transferred, and errors. These measurements help determine whether streaming is improving the application.
Common Mistakes to Avoid
One common mistake is using InvokeAsync instead of InvokeWithResponseStreamAsync. The normal invocation API follows the buffered response model and does not provide the same incremental event stream.
Another mistake is forgetting to flush the StreamWriter. Data may remain in the writer's buffer, preventing the caller from receiving it when expected.
Developers may also enable response streaming in the Lambda function but forget to change the Function URL invoke mode or API Gateway integration. The result is that the application continues behaving like a buffered endpoint.
Finally, receiving the first response chunk should not be treated as proof that the function completed successfully. Always process the completion event and handle errors that occur during stream consumption.
Advantages and Disadvantages
Advantages
- Reduces time to first byte for suitable workloads.
- Supports larger responses than normal buffered synchronous invocation.
- Can reduce memory requirements during response generation.
- Allows clients to process data as it arrives.
- Works with standard .NET Stream and StreamWriter APIs.
- Supports use cases such as AI output, exports, and large reports.
Disadvantages
- Requires changes to the Lambda handler and invocation path.
- Needs a streaming-enabled Function URL or API Gateway integration.
- Requires careful handling of partial responses and errors.
- Long-lived connections require appropriate timeout configuration.
- Bandwidth is limited after the initial 6 MB.
- Streaming does not guarantee better performance for small responses.
Summary
AWS Lambda response streaming gives .NET developers a practical way to send response data incrementally instead of waiting for the complete output.
The LambdaResponseStreamFactory API provides a writable .NET stream for producing responses, while the AWS SDK for .NET exposes InvokeWithResponseStreamAsync for consuming streamed output through response events.
This approach is particularly useful for AI-generated content, large exports, and workloads that produce information gradually. It can improve the time to first byte and reduce the need to hold an entire response in memory.
However, successful implementation requires more than changing the Lambda handler. The invocation method, Function URL or API Gateway configuration, stream flushing, error handling, and timeout settings must all be considered.
For ordinary small API responses, buffered invocation remains a simple and effective choice. When an application benefits from receiving data progressively, response streaming provides a useful alternative.
Join the conversation! Your thoughts help the community grow.