Bounded concurrent I/O without overload

Published At: · 10 min read

engineering software-development #csharp #dotnet #async #concurrency

Series introduction: Async programming: identify the wait before choosing the tool

When several operations spend most of their time waiting, running them one at a time can make the caller wait longer than necessary. Concurrency lets those waits overlap. Bounded concurrency limits how many operations can run at once; the rest wait until one finishes.

A page that loads details for several items is a useful example. Each item needs an HTTP request, but one item's response isn't needed to request another, so the requests can overlap. Sending every request immediately, though, can leave the item service with more work than it can handle.

Requests that need an earlier result must still wait for it, and overlapping independent reads don't guarantee a consistent catalog snapshot. If prices or stock must agree across responses, the service has to provide that consistency.

Sequential, unbounded, and bounded requests

The C# solution is a .NET 10 console project. It requests the same eight item IDs in three ways. Run it from the code-sample repository root:

dotnet run --project 04-bounded-concurrent-io-without-overload/BoundedIoDemo

The sequential version in ItemRequests.cs waits for each item before requesting the next:

public static async Task<Item[]> SequentialAsync(HttpClient client, int[] ids)
{
    Validate(client, ids);
    var items = new List<Item>();
    foreach (var id in ids)
        items.Add(await FetchAsync(client, id));

    return items.ToArray();
}

Keep the sequential version if its response time is already acceptable. The unbounded version calls FetchAsync for every item before awaiting the results:

public static Task<Item[]> UnboundedAsync(HttpClient client, int[] ids)
{
    Validate(client, ids);
    return Task.WhenAll(ids.Select(id => FetchAsync(client, id)).ToArray());
}

Select is deferred. Calling ToArray enumerates the IDs and starts each fetch, so nothing in this method holds back a request because too many are already running. Task.WhenAll then waits for the group without starting or limiting the operations.[1] The earlier post on task lifetimes explains the task model behind that wait.

The bounded version wraps the fetch in a semaphore. The demo calls it with a limit of three.

public static async Task<Item[]> BoundedAsync(HttpClient client, int[] ids, int maxConcurrency)
{
    Validate(client, ids);
    ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxConcurrency);
    using var slots = new SemaphoreSlim(maxConcurrency, maxConcurrency);

    var tasks = ids.Select(async id =>
    {
        await slots.WaitAsync();
        try
        {
            return await FetchAsync(client, id);
        }
        finally
        {
            slots.Release();
        }
    }).ToArray();

    return await Task.WhenAll(tasks);
}

The program prints these summaries:

Sequential: completed 8; peak active 1
Unbounded: completed 8; peak active 8
Bounded: completed 8; peak active 3

These counts come from DemoHandler.cs, which holds responses until the check releases them. The requests still go through HttpClient and their responses are deserialized, but the handler replaces the transport; nothing is sent to demo.invalid. The counts verify concurrency, not production performance or a suitable limit for a real service; the controlled handler makes the overlap repeatable without relying on network timing.

A semaphore around the HTTP call

SemaphoreSlim tracks available slots. Its initial count is the number of available slots; its maximum count sets the upper bound. WaitAsync waits asynchronously for a slot, and Release returns one. The code using the semaphore has to pair those calls correctly.[2]

WaitAsync runs before FetchAsync. Once the slots are occupied, later items stop at that wait without starting their HTTP requests. Limiting the code that awaits the results would be too late if the requests had already started.

Validate checks the client, batch, and positive item IDs before any requests start. The concurrency limit must also be positive: zero means no initial slot, not sequential execution, so the method rejects it.

Slots free individually, so a waiting item can start while other requests are still pending. Fixed-size groups would instead wait for the slowest request in each group before starting the next.

Using .GetAwaiter().GetResult() would still block the caller. Native asynchronous HTTP calls don't need Task.Run either; offloading expensive CPU work to keep a UI responsive is a different use for it.[3]

The slot covers the whole request

FetchAsync reads the response and deserializes it into an Item record containing an ID and title:

private static async Task<Item> FetchAsync(HttpClient client, int id) =>
    await client.GetFromJsonAsync<Item>($"items/{id}")
    ?? throw new InvalidDataException($"Item {id} returned a null response.");

The slot covers all of FetchAsync, including the HTTP wait and response parsing, and finally returns it after success, an HTTP error, or unusable response data. Releasing it as soon as the HTTP task is created would let another request start before that fetch finishes.

The try starts after the wait succeeds, because an operation should only release a slot it acquired. If a cancellation token is later passed to WaitAsync, a cancelled wait must not cause an extra Release; this sample leaves cancellation ownership and deadlines out of the implementation.

The final await Task.WhenAll stays inside the using scope. Returning its task directly would dispose the semaphore while operations could still be waiting on it or returning slots, and disposal is only safe after all other operations finish.[2]

One failed request fails this batch

The batch returns all the items or throws. If any supplied task faults, WhenAll waits for the supplied tasks to finish and then faults.[1] This implementation doesn't cancel the other fetches, so waiting items can still take released slots and run; an exception from the batch doesn't mean every request failed.

Program.cs tests an HTTP 503 failure, reported as HttpRequestException, and a rejected JSON null response. Both checks use a limit of one and require later requests to finish; a leaked slot makes the check time out. It also checks that empty input returns an empty array without making HTTP requests.

Partial success would need a return type with an outcome for each item. Swallowing the exception and returning an empty list or a default item would hide the failure, so this sample keeps the all-items-or-exception return type.

When every fetch succeeds, Task.WhenAll returns results in the order of the supplied tasks.[1] The task array follows the input IDs, so the returned items do too, even though SemaphoreSlim doesn't promise FIFO admission and requests may start in a different order.[2]

A limit per batch, not per service

Each call to BoundedAsync creates a new semaphore, so two batches can each stay within their own limit while sending more requests together than the service can handle.

To limit all callers of one dependency within an application instance, those callers need to share the semaphore. A long-lived service or dependency client can own it and dispose it after its callers finish. Unrelated dependencies don't necessarily need to wait on that same semaphore.

A shared semaphore still covers only that application instance; if the limit belongs to a tenant or the service as a whole, enforce it where all of those callers meet.

The example reuses the supplied HttpClient across the batch instead of creating a client per item; Microsoft's guidance describes long-lived clients with configured connection lifetimes or factory-managed clients and handlers.[4] Each self-check has an isolated handler and client so that one run doesn't affect another, but an application should use an appropriate reused or managed lifetime.

Choosing the limit

Three makes the sample's behavior easy to check; it isn't a suggested production setting. Try a representative batch against the real dependency and watch its response times, errors, timeouts, and throttling responses, along with the waiting work and memory in the calling application. More overlap helps only while the service can handle the added work.

Time spent waiting for a slot is worth measuring separately from time spent on HTTP. Item loading can feel slow even when the service answers quickly, because requests are spending time waiting in the application. An HTTP timeout doesn't cover the time already spent waiting for the semaphore, so a deadline for the whole operation has to include both waits.

Active requests and requests started per second are different limits. Fast responses can free slots many times during an interval, so even a small concurrency limit can exceed an API's allowed request rate.

Enforcing that rate needs a policy that accounts for all callers, including retry attempts; an arbitrary delay in this loop doesn't do that, and this sample doesn't retry failed requests at all.

Waiting tasks still use memory

There is a task for every ID, including the items waiting for a slot, and the input array stays in memory while the successful results end up in another array. Limiting active HTTP calls doesn't limit how many waiting tasks this method creates.

For a very large input, a fixed number of workers can take the next item as they finish, so the method doesn't need a task for every waiting item; consuming results as they arrive would also require a different return type.

Sources

  1. Microsoft Learn: Task.WhenAll (.NET 10)
  2. Microsoft Learn: SemaphoreSlim (.NET 10)
  3. Microsoft Learn: Asynchronous programming scenarios
  4. Microsoft Learn: Guidelines for using HttpClient
Share on LinkedIn