Editorial diagram splits a sequence of records into full batches and a smaller final batch before processing

Editorial illustration.

An API may accept 100 records per request even when your program has thousands to send. Building one giant list for the request is awkward, while writing an index loop makes off-by-one errors easy. In .NET 6 and later, LINQ’s Enumerable.Chunk splits an IEnumerable<T> into arrays of at most a chosen size. The useful detail is that the last batch can be smaller, and batching alone does not make a workflow transactional or retry-safe.

Summary

  • Chunk(size) returns batches containing up to size elements; the final batch may be shorter.
  • The API is part of .NET LINQ and is available in .NET 6+; it is not a new C# language feature.
  • Process one chunk at a time when you want to limit the collection held by your loop.
  • Choose batch size and retry behavior from the downstream API’s limits, latency and failure semantics.

A small, complete example

This top-level Program.cs example targets a .NET 6 or later console project. It assumes the HTTP endpoint accepts an array of records and that client has been configured with the correct base address and authentication. Production applications should usually obtain HttpClient from IHttpClientFactory or another managed lifetime rather than create a client for every batch.

using System.Net.Http.Json;

var records = LoadRecords(); // IEnumerable<Record> from your application
const int batchSize = 100;

foreach (Record[] batch in records.Chunk(batchSize))
{
    using HttpResponseMessage response = await client.PostAsJsonAsync(
        "/api/records/import",
        batch,
        cancellationToken);

    response.EnsureSuccessStatusCode();
}

Record, LoadRecords(), client and cancellationToken represent values your application supplies; they are placeholders, not built-in APIs. The Chunk call itself is the built-in method. Microsoft documents it as returning IEnumerable<TSource[]>; each array is at most the requested size, and a size below one throws ArgumentOutOfRangeException (API reference).

If there are 235 records and the batch size is 100, the loop receives arrays of 100, 100 and 35. Do not assume the last request has exactly 100 items. The server should accept a shorter final batch or your client should handle that explicitly.

Why Chunk helps, and what it does not do

When you enumerate an input sequence once and process each yielded array before moving on, the loop can avoid building a second list containing every record. That is valuable when records comes from a streaming or lazy source. Each batch is still an array that occupies memory, and upstream code may already have loaded all records. Chunk limits the group size; it does not make the entire application memory-bounded by itself.

The returned sequence is deferred: the source is consumed as the chunks are enumerated. Do not enumerate the chunk sequence twice if the source is expensive, stateful or can only be read once. If you need a retry, retain or recreate the specific failed batch rather than restarting a partially completed input blindly.

Chunk is also not parallel processing. The foreach example sends each request one after another. This is often the right starting point because it controls load on the destination. If the remote service allows concurrency, add a deliberate limit and measure it; launching every chunk at once can turn batching into a burst of requests.

Pick a batch size from constraints

Start with the destination’s documented maximum request size, rate limit and payload limits. A batch of 100 small integer IDs is different from a batch of 100 large documents. If the server imposes a maximum body size, count alone may not be sufficient. If the request fails as “too large”, lower the size and measure again.

Larger chunks mean fewer network round trips, but also larger payloads and more work to repeat after a failure. Smaller chunks are easier to retry and can reduce latency for the first result, but add overhead and may hit a rate limit sooner. Record the number of successful batches and the failure point so operators can resume safely.

For database writes, decide whether one batch should be a transaction. A transaction per chunk allows earlier chunks to remain committed if a later one fails. Wrapping the entire import in one transaction gives different atomicity and resource costs. Chunk chooses grouping only; your database code defines those semantics.

Add cancellation and clear failure behavior

In an import or background job, pass a cancellation token to the operation being performed, as in PostAsJsonAsync. The Chunk enumeration itself has no cancellation-token parameter. If retrieving records is asynchronous, use an async-stream approach with a batching helper appropriate to that source rather than calling synchronous Chunk on something that is not an IEnumerable<T>.

On a failed request, EnsureSuccessStatusCode throws. That is a clear fail-fast policy, but the already completed earlier requests are not undone. Before adding retries, determine whether the operation is idempotent. If resending the same batch can create duplicate records, use an idempotency key or a server-side upsert strategy supported by the API. Retry transient errors with bounded attempts and a delay; do not retry authentication failures or invalid input as if they were network hiccups.

For sources that need manual index-based paging or a different lifecycle, Chunk is not mandatory. A list can be sliced by ranges, or a database can page records by a stable key. Avoid offset paging over a table that changes during processing unless you have checked its consistency behavior.

Handle validation and empty input

Validate the size before starting the job so a configuration mistake fails close to its source:

if (batchSize <= 0)
{
    throw new ArgumentOutOfRangeException(nameof(batchSize));
}

An empty source produces no batches, so the loop sends no request. If the remote API requires an explicit “empty import” call, handle that as a separate case. Each batch is an array, which is convenient for JSON serialization but means the consumer can mutate it. Treat it as owned by the current iteration or copy it if you must retain it beyond processing.

Common mistakes

  • Assuming every chunk has exactly the configured size.
  • Setting a large number without checking API payload or rate limits.
  • Converting the entire source to a list before chunking, then expecting lower memory use.
  • Starting all requests in parallel without a concurrency cap.
  • Retrying a batch whose server-side effect is not idempotent.
  • Using Chunk on .NET 5 or earlier without adding an appropriate implementation or upgrading; the standard LINQ API is available from .NET 6.

The method comes from System.Linq in the .NET libraries. The foreach, array type and await syntax are C# language features, while Enumerable.Chunk is a .NET API. This distinction matters when checking target frameworks and compiler requirements. See our earlier guides on C# async streams and cancellation and bounded channels in .NET for related streaming and queue patterns.

My Take

I reach for Chunk when a consumer has a real batch boundary, such as an API limit or a database operation that should be measured in groups. I do not use it just to make a loop look modern. The important design choice remains what happens after batch 7 fails: whether earlier work is kept, whether retry is safe and how progress is recorded.

Conclusion

Use Enumerable.Chunk on .NET 6+ to split a sequence into manageable arrays, then process each group according to the downstream system’s rules. Expect a shorter final batch, keep enumeration single-pass when appropriate, and design bounded retries and checkpointing around partial completion. The method groups data; your application still owns delivery guarantees.

Sources