Not every API request can return a response immediately. Some operations require multiple database queries, calls to external services, file processing, or complex calculations before the final result becomes available.
Consider an application that generates a monthly sales report. The API may need to retrieve thousands of transactions, calculate totals, group records by region, and prepare a downloadable report. Depending on the amount of data and the performance of external dependencies, this operation may take several seconds or even minutes.
A common implementation waits until every operation is complete and then returns the entire response. Although this approach works for small operations, it can create problems when processing takes longer. The client remains waiting, HTTP connections stay occupied, and requests may eventually fail because of configured timeouts.
One way to improve this experience is to return partial results while the operation is still running.
Instead of waiting for the complete response, the API can send available data in smaller pieces. The client receives information as it becomes ready and can begin processing it without waiting for the entire operation to finish.
ASP.NET Core supports several approaches for this pattern, including response streaming, asynchronous enumeration, and background processing with status endpoints.
In this article, we will explore how to choose the right approach, implement streaming responses, handle failures, and design long-running API operations for production applications.
Why Long-Running API Requests Become a Problem
Traditional HTTP API endpoints usually follow a simple request-response model.
The client sends a request, the server performs the required work, and the server returns a response after processing is complete.
For example:
[HttpGet("report")]
public async Task<IActionResult> GetReport()
{
var report = await _reportService.GenerateReportAsync();
return Ok(report);
}
This implementation is straightforward, but it requires the complete report to be generated before the response can be returned.
For operations that take a long time, several problems can occur.
Clients Wait Without Receiving Useful Information
The client does not know whether the server is still processing the request or whether the operation has become stuck.
A web application may display a loading indicator for an extended period without showing any progress.
Memory Usage Can Increase
If the application collects thousands of records into a list before returning them, the complete result remains in memory.
This can become expensive when multiple large requests execute simultaneously.
HTTP Timeouts Can Interrupt Processing
Reverse proxies, gateways, load balancers, and clients may have their own timeout settings.
If the operation takes longer than the configured limit, the connection may be closed before the response is completed.
Clients Cannot Process Available Data Early
Suppose an API retrieves information from several independent sources. If one source responds quickly and another responds slowly, a traditional response may force the client to wait for both.
Streaming allows the application to deliver available information without waiting for every remaining operation.
Understanding Partial Responses and Streaming
Returning partial results means sending a response incrementally rather than preparing the entire response before writing anything to the HTTP response body.
There are different ways to implement this behavior.
Approach | How It Works | Suitable Scenario |
|---|
Response streaming | Sends response data as it becomes available | Large exports and result sets |
IAsyncEnumerable | Produces records asynchronously one at a time | Database-backed collections |
Server-Sent Events | Sends continuous server-to-client events | Progress updates and live notifications |
Background processing | Executes work separately and exposes its status | Reports and long-running business operations |
These approaches solve different problems.
For example, streaming is useful when the client needs actual result data incrementally. Background processing is more appropriate when an operation must continue even if the client disconnects.
Choosing the right approach is important because partial responses do not automatically solve every long-running request problem.
Implementing Response Streaming in ASP.NET Core
Let's consider an API that generates customer records for a large export.
Instead of building a complete collection and returning it through Ok(), the API can write each record directly to the response stream.
ASP.NET Core provides HttpResponse.Body for writing response content.
The following example demonstrates a simple streaming endpoint:
using System.Text.Json;
[ApiController]
[Route("api/customers")]
public class CustomersController : ControllerBase
{
[HttpGet("export")]
public async Task ExportCustomers(
CancellationToken cancellationToken)
{
Response.ContentType = "application/x-ndjson";
var customers = GetCustomersAsync(cancellationToken);
await foreach (var customer in customers)
{
var json = JsonSerializer.Serialize(customer);
await Response.WriteAsync(
json + "\n",
cancellationToken);
await Response.Body.FlushAsync(
cancellationToken);
}
}
private async IAsyncEnumerable<Customer> GetCustomersAsync(
[System.Runtime.CompilerServices.EnumeratorCancellation]
CancellationToken cancellationToken)
{
for (int i = 1; i <= 10; i++)
{
cancellationToken.ThrowIfCancellationRequested();
await Task.Delay(500, cancellationToken);
yield return new Customer
{
Id = i,
Name = $"Customer {i}"
};
}
}
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
This example uses newline-delimited JSON, commonly called NDJSON.
Each customer is serialized as an independent JSON object followed by a newline character.
The response looks like this:
{"Id":1,"Name":"Customer 1"}
{"Id":2,"Name":"Customer 2"}
{"Id":3,"Name":"Customer 3"}
The server does not need to construct one large JSON array before sending the response.
Why Use NDJSON?
A regular JSON array requires a complete structure with opening and closing brackets:
[
{
"id": 1,
"name": "Customer 1"
},
{
"id": 2,
"name": "Customer 2"
}
]
When sending a response incrementally, the server needs to manage the array structure correctly.
NDJSON simplifies this process because every line contains an independent JSON object.
Clients can read and process each line separately.
However, NDJSON is a different response format from a normal JSON array. The client must explicitly support it.
Streaming Database Results With IAsyncEnumerable
A more practical scenario is retrieving a large number of records from a database.
Instead of loading every record into memory, a service can expose an asynchronous stream.
Consider the following service implementation:
public class OrderService
{
private readonly AppDbContext _context;
public OrderService(AppDbContext context)
{
_context = context;
}
public async IAsyncEnumerable<Order> GetOrdersAsync(
[System.Runtime.CompilerServices.EnumeratorCancellation]
CancellationToken cancellationToken)
{
var query = _context.Orders
.AsNoTracking()
.OrderBy(x => x.Id)
.AsAsyncEnumerable();
await foreach (var order in query
.WithCancellation(cancellationToken))
{
yield return order;
}
}
}
The controller can consume this stream:
[HttpGet("stream")]
public async Task StreamOrders(
CancellationToken cancellationToken)
{
Response.ContentType = "application/x-ndjson";
await foreach (var order in _orderService
.GetOrdersAsync(cancellationToken))
{
var json = JsonSerializer.Serialize(order);
await Response.WriteAsync(
json + "\n",
cancellationToken);
await Response.Body.FlushAsync(
cancellationToken);
}
}
This implementation avoids explicitly creating a complete in-memory list of orders.
However, there are important considerations.
The database provider may use buffering internally, and a long-running database query may hold a connection and database resources for an extended period. Streaming reduces application-level collection buffering, but it does not guarantee that every layer operates without buffering.
For production applications, use appropriate database indexes, pagination where possible, and query time limits.
Also, avoid returning database entities directly from public APIs. Map them to dedicated response models to prevent accidental exposure of internal fields.
Sending Progress Updates With Server-Sent Events
Sometimes clients do not need partial business data. They simply need to know how much work has been completed.
For example, a report-generation screen may display:
Report generation started.
Customer records processed.
Sales calculations completed.
Report file generated.
Server-Sent Events (SSE) provide a way to send continuous server-to-client updates over an HTTP connection.
The server sends events using the text/event-stream content type.
A simple ASP.NET Core implementation looks like this:
[HttpGet("progress")]
public async Task StreamProgress(
CancellationToken cancellationToken)
{
Response.ContentType = "text/event-stream";
for (int progress = 10; progress <= 100; progress += 10)
{
cancellationToken.ThrowIfCancellationRequested();
var message = $"data: {{\"progress\":{progress}}}\n\n";
await Response.WriteAsync(
message,
cancellationToken);
await Response.Body.FlushAsync(
cancellationToken);
await Task.Delay(1000, cancellationToken);
}
}
The server sends an event every second.
A browser client can receive these updates using EventSource:
const source = new EventSource("/api/reports/progress");
source.onmessage = function (event) {
const result = JSON.parse(event.data);
console.log("Progress:", result.progress);
if (result.progress >= 100) {
source.close();
}
};
source.onerror = function () {
console.log("Progress connection interrupted.");
};
This approach is useful when the server needs to communicate progress without sending a complete business response.
SSE is designed for server-to-client communication. If the client also needs to send frequent messages through the same connection, another communication mechanism may be more appropriate.
When Background Processing Is a Better Choice
Streaming is not always the right solution.
Consider a report that takes five minutes to generate. The client may close its browser, lose network connectivity, or navigate to another screen.
If the operation should continue regardless of the client's connection, tying it directly to the HTTP request is not a good design.
In this situation, background processing is a better option.
The API can create a job and return an identifier immediately.
For example:
[HttpPost("generate")]
public IActionResult GenerateReport()
{
var jobId = Guid.NewGuid();
_reportQueue.Enqueue(jobId);
return Accepted(new
{
JobId = jobId,
Status = "Queued",
StatusUrl = $"/api/reports/{jobId}/status"
});
}
The client receives an HTTP 202 Accepted response because the request has been accepted for processing but is not complete.
A separate endpoint can expose the job status:
[HttpGet("{jobId}/status")]
public IActionResult GetReportStatus(Guid jobId)
{
var job = _reportService.GetJob(jobId);
if (job == null)
{
return NotFound();
}
return Ok(new
{
JobId = job.Id,
Status = job.Status,
Progress = job.Progress,
DownloadUrl = job.DownloadUrl
});
}
The client can periodically request the status or receive updates through SSE.
For production applications, the queue and job status should use durable storage if processing must survive application restarts. An in-memory queue is not sufficient for jobs that must not be lost.
Handling Client Disconnections and Cancellation
One important part of streaming is handling clients that disconnect before the operation finishes.
ASP.NET Core provides HttpContext.RequestAborted, which can be used as a cancellation token.
When a client closes the connection, the server can observe cancellation and stop unnecessary work.
For example:
[HttpGet("stream")]
public async Task StreamData()
{
var cancellationToken = HttpContext.RequestAborted;
Response.ContentType = "application/x-ndjson";
await foreach (var item in _service.GetDataAsync(
cancellationToken))
{
var json = JsonSerializer.Serialize(item);
await Response.WriteAsync(
json + "\n",
cancellationToken);
await Response.Body.FlushAsync(
cancellationToken);
}
}
Cancellation should also be passed to database queries, external HTTP calls, and other operations that support it.
However, not every operation should stop when the client disconnects.
For example, if a customer has submitted a payment request or started a business-critical report, the operation may need to continue independently.
In such cases, use background processing rather than relying on the lifetime of the HTTP connection.
Important Production Considerations
Streaming introduces additional responsibilities that should be considered before deploying an API.
Response Headers Must Be Set Early
Set the response content type and other required headers before writing the response body.
Once response data has started, changing the response status code or headers may no longer be possible.
Flushing Does Not Guarantee Immediate Delivery
Calling FlushAsync sends buffered response data toward the next layer, but it does not guarantee that the browser or client immediately receives it.
Reverse proxies, compression middleware, network infrastructure, and client libraries may buffer data.
Test the complete request path rather than assuming that every write becomes immediately visible.
Handle Errors After Streaming Starts
A normal API can return a structured error response before writing its response body.
Streaming changes this behavior.
After response data has started, the server generally cannot replace the existing response with a different HTTP status code.
If an error occurs during streaming, the connection may end with an incomplete response. The client should be able to recognize that the stream did not complete successfully.
For long-running operations, it can be useful to include explicit completion or error events in the streaming protocol.
Apply Appropriate Resource Limits
A streaming endpoint may keep an HTTP connection and database resources occupied for an extended period.
Set reasonable limits for:
Maximum processing duration.
Maximum number of records.
Database command execution time.
Concurrent streaming requests.
External service request timeouts.
Streaming should reduce unnecessary memory usage, not become an unlimited resource-consumption mechanism.
Protect Sensitive Data
Each streamed record should pass through the same authorization and data-filtering rules as a normal API response.
Do not assume that sending data incrementally makes it safer.
Common Mistakes to Avoid
Mistake | Why It Causes Problems | Better Approach |
|---|
Loading all records before streaming | Uses unnecessary application memory | Read records incrementally |
Using streaming for every endpoint | Adds complexity without always improving performance | Use it for genuinely large or incremental responses |
Ignoring cancellation | Wastes resources after clients disconnect | Propagate cancellation tokens |
Returning database entities directly | Can expose internal properties | Use response DTOs |
Assuming FlushAsync guarantees immediate delivery | Intermediate layers may buffer data | Test through the actual deployment infrastructure |
Running critical jobs inside request lifetime | Work may stop when the client disconnects | Use durable background processing |
Ignoring incomplete streams | Clients may treat partial data as complete | Define completion and error handling |
Summary
Returning partial results from long-running ASP.NET Core requests can improve the client experience and reduce unnecessary memory usage. Instead of waiting for a complete result, clients can receive information as it becomes available.
ASP.NET Core supports several approaches for this requirement. Response streaming and IAsyncEnumerable are useful for delivering large result sets incrementally. Server-Sent Events work well for progress notifications, while background processing is more appropriate for operations that must continue independently of the HTTP connection.
The most important decision is understanding whether the client needs partial data, progress updates, or a durable long-running job. Choosing the correct approach helps keep API behavior predictable, improves resource management, and makes long-running operations easier to maintain in production applications.
Join the conversation! Your thoughts help the community grow.