Limit Concurrent Work With A Swift Task Group
You select 300 saved articles to refresh for offline reading. A task group sounds like the right tool: add a child task for each URL, collect the responses, and update the list.
The list is correct. The app has also enthusiastically invited 300 operations to dinner, despite owning three chairs.
A task group gives child tasks a lifetime and a place to return results. Your code still needs to decide how much work to admit at once. Let’s build that limit, preserve the original ordering, and make cancellation useful.
This is practical Swift 6 code for the current Xcode 27 toolchain. Task groups are an established API, not a new Swift 6.4 feature. The modern detail here is an explicit isolation contract that also compiles with MainActor default isolation enabled.
Start three, replace one
Apple demonstrates the underlying pattern in Beyond the basics of structured concurrency: start a limited number of children, consume a completion, then admit one replacement.
For a limit of three, the sequence is:
- Submit items 0, 1, and 2.
- Wait for whichever child completes next.
- Store its result and submit item 3.
- Repeat until there is no work left.
A slow first item does not prevent later completions from opening a slot. That is the advantage over splitting the input into fixed batches of three and waiting for an entire batch before continuing.
The limit counts admitted child operations whose results have not yet been consumed. It is an upper bound, not a promise that three operations will always be executing simultaneously.
Build a bounded map
Here is the complete helper. It accepts a finite array, a positive limit, and an async operation. A successful call returns one output for every input, in input order.
import Foundation
nonisolated enum BoundedMapError: Error {
case invalidLimit
}
@concurrent
func boundedMap<Input: Sendable, Output: Sendable>(
_ inputs: [Input],
maxConcurrent: Int,
operation: @escaping @Sendable (Input) async throws -> Output
) async throws -> [Output] {
guard maxConcurrent > 0 else { throw BoundedMapError.invalidLimit }
try Task.checkCancellation()
return try await withThrowingTaskGroup(of: (Int, Output).self) { group in
func submit(_ index: Int) throws {
let input = inputs[index]
let added = group.addTaskUnlessCancelled {
try Task.checkCancellation()
let value = try await operation(input)
try Task.checkCancellation()
return (index, value)
}
guard added else { throw CancellationError() }
}
let initialCount = min(maxConcurrent, inputs.count)
for index in 0..<initialCount {
try submit(index)
}
var nextIndex = initialCount
var results = [Output?](repeating: nil, count: inputs.count)
while let (index, value) = try await group.next() {
try Task.checkCancellation()
results[index] = .some(value)
if nextIndex < inputs.count {
try submit(nextIndex)
nextIndex += 1
}
}
try Task.checkCancellation()
return results.map { slot in
guard case .some(let value) = slot else {
preconditionFailure("A completed batch must fill every result slot")
}
return value
}
}
}
Only the parent task changes nextIndex and results. Each child captures one input and returns an index/value pair. There is no shared array for concurrent children to mutate.
The initial loop admits at most the limit. After that, one consumed completion permits one replacement. We never create a suspended child for every waiting input.
Swift delivers task-group results in completion order, so appending values would scramble the input order. Indexing the result slots fixes that. The explicit .some(value) also preserves a legitimate nil when Output itself is optional. An unfilled slot is different from a completed operation whose answer is nil.
The final precondition documents an internal invariant: a successful batch must have filled every slot. An operation error takes the throwing path instead of manufacturing a shorter success array. Empty input returns an empty array; zero and negative limits throw even for empty input.
Keep the isolation contract explicit
The @concurrent attribute makes this async function run away from the caller’s actor. It is available from Swift 6.2 and implies nonisolated isolation. It does not create another task by itself; the group creates the child tasks.
Input and Output are Sendable, and the operation is a Sendable closure. This helper is deliberately for work whose inputs and outputs can cross isolation boundaries. Do not capture a SwiftUI view’s mutable state inside that closure. Read the necessary values first, then publish the completed result back in the view’s actor context.
The nonisolated declarations on the small model and error types also make their intent explicit in a project using MainActor default isolation. Adding await does not, on its own, turn an actor-isolated decoder into parallel CPU work.
Use it for a small metadata refresh
Add this below the helper. Each URL should return a small JSON object containing an integer id and a string title:
nonisolated struct ArticleSummary: Decodable, Sendable {
let id: Int
let title: String
}
@concurrent
func loadSummaries(
from urls: [URL],
session: URLSession = .shared
) async throws -> [ArticleSummary] {
try await boundedMap(urls, maxConcurrent: 3) { url in
let (data, response) = try await session.data(from: url)
guard let response = response as? HTTPURLResponse,
(200..<300).contains(response.statusCode)
else {
throw URLError(.badServerResponse)
}
try Task.checkCancellation()
return try JSONDecoder().decode(ArticleSummary.self, from: data)
}
}
The returned array follows the supplied URL order, regardless of response timing. The three-operation limit covers each request and its JSON decoding. Three is an example policy, not a recommended setting for every device or service.
This uses one shared URLSession. Creating a session per item would make connection reuse and configuration harder to reason about. A connection setting such as httpMaximumConnectionsPerHost controls a different resource; it is not a replacement for bounding the complete application operation.
Use this version for reasonably small, trusted metadata responses. data(from:) buffers the response, and this helper retains every decoded output. For large payloads, use the file-download approach and return a file URL or another small result. Bounding the number of requests does not bound the size of an individual response.
Let errors escape, and understand what that means
When group.next() observes a child error, this implementation lets it escape the group body. The remaining children are then cancelled, and the scope waits for them to finish. That behavior follows Swift’s structured-concurrency cancellation rules.
A child failing does not instantly interrupt the parent at an arbitrary instruction. Another completion may be consumed, and another item admitted, before the failure is observed. Once the error escapes, this helper stops submitting replacements.
Cancellation is cooperative. addTaskUnlessCancelled declines admission to a group already marked cancelled; the checks inside each child cover cancellation around its operation. There is still a race between checking and starting work. Neither mechanism can interrupt a synchronous function that ignores cancellation.
The check after the operation prevents that child’s late result from being returned as a success when cancellation is already visible. The parent checks cancellation while collecting results and before constructing the final array too. None of these checks makes cancellation atomic with the eventual caller updating its UI.
Keep errors honest at that caller. A cancelled network request may throw a URL-loading error rather than CancellationError; inspect the enclosing task’s cancellation state before presenting a refresh failure. Also keep a request identity when overlapping refreshes can finish out of order, as in our stale-result example.
For independent downloads where partial success is the product requirement, return an explicit per-item outcome instead. This helper intentionally fails the whole call. It does not roll back side effects that have already happened, so treat writes separately from this read-only example.
Know which budget you bought
| This helper limits | It does not limit |
|---|---|
| Admitted operations within one invocation | Work started by other invocations or features |
| Replacement work while a cancelled group is observed | Requests per second or a server quota |
| Direct child operations that remain within their scope | Unstructured tasks an operation starts and abandons |
The result storage is proportional to the number of inputs. A limit of three is not a three-result memory budget. For a huge library or an ongoing feed, choose a producer/consumer design that also bounds queued inputs and retained outputs.
Likewise, three fast requests can still exceed a requests-per-second quota. Keep server rate-limit handling and retry policy separate from admission control.
Avoid wrapping every operation in Task { ... } and immediately returning. That would release a slot while its real work continued elsewhere. Await the complete operation inside the child.
Test the contract without racing a stopwatch
The useful tests control when operations finish. A test actor can hold each operation on a continuation, record the peak active count, and release selected inputs explicitly.
Start three inputs, release input 2, and verify that input 3 starts while inputs 0 and 1 remain suspended. Keep releasing later inputs first, then check that the returned values are still in input order. This catches both an unbounded implementation and an implementation that quietly serializes everything.
Also cover an empty input, a limit larger than the input, a limit of one, invalid limits, optional outputs, child failure, and cancellation before and during the batch. For cancellation, include an operation that deliberately waits for a manual release instead of cooperating immediately. The group must still wait for that child to finish.
Verified September 28, 2026: both Swift blocks compile together with Xcode 27.0 and Swift 6.4 for iOS 17, including MainActor default isolation with NonisolatedNonsendingByDefault enabled. The companion checks exercise ordering, admission, failures, and cancellation. The URLSession example is also exercised against a local HTTP fixture. These checks validate behavior; they do not establish an optimal concurrency limit or a device-performance benchmark.