In Swift, how would you upload 50 photos with `withThrowingTaskGroup` keeping at most four in flight, and what happens when one upload throws?
answer
- groups have no width limit
- seed four, add one per next()
- errors surface at next()
- throwing out cancels and still waits
- discarding groups for side effects
basics
~20 sA Swift task group has no width limit: add four uploads, then one more each time next() returns. A child's error surfaces at next(); letting it escape cancels the other children, which the group awaits before rethrowing.
solid answer
~50 s`withThrowingTaskGroup` imposes no concurrency limit: 50 `addTask` calls start up to 50 children. For a window of four, add the first four uploads, then loop on `try await group.next()` and add the next photo each time one finishes, so at most four are ever pending. Results arrive in completion order, not insertion order. A child that throws does not cancel its siblings by itself; its error is rethrown by the `next()` call that collects it. If the body lets that error escape, the group cancels every remaining child and still waits for all of them to finish before `withThrowingTaskGroup` rethrows. To keep going past a failed photo, catch inside the child and return a `Result` or `nil` instead. When you need no results at all, `withThrowingDiscardingTaskGroup` cancels itself on the first child error and rethrows it.
code
swift · 25 linesstruct UploadFailed: Error { let name: String }
func upload(_ name: String) async throws -> String {
try await Task.sleep(for: .milliseconds(20))
if name == "IMG_13.jpg" { throw UploadFailed(name: name) }
return name
}
func uploadAll(_ names: [String], maxInFlight: Int = 4) async throws -> [String] {
try await withThrowingTaskGroup(of: String.self) { group in
var pending = names.makeIterator()
for _ in 0..<maxInFlight {
guard let name = pending.next() else { break }
group.addTask { try await upload(name) }
}
var uploaded: [String] = []
while let done = try await group.next() { // a child's error is rethrown here
uploaded.append(done)
if let name = pending.next() {
group.addTask { try await upload(name) }
}
}
return uploaded
}
}go deeper
Know that a task group lets you start a variable number of child tasks and collect their results with next() or for await.
Explain completion-order results, that the group waits for every child, and how cancelAll() and addTaskUnlessCancelled behave.
Implement the sliding window, trace exactly when a child's error cancels the rest, and pick a discarding group or per-child Result for partial success.
Decide where concurrency limits belong in an upload pipeline, per group or shared across screens, given server limits and device memory.
## A group runs what you give it `withTaskGroup(of:returning:isolation:body:)` and `withThrowingTaskGroup(of:returning:isolation:body:)` open a scope in which you can add a **dynamic number of child tasks**. Each `group.addTask { ... }` creates a child that is scheduled at once. The group has no width parameter, so calling `addTask` 50 times creates 50 children, all of which may be in flight together: 50 simultaneous uploads, 50 open connections, 50 decoded images in memory. The executor's thread pool limits how many run **on a CPU** at once, but suspended children waiting on the network still count. The group's structural guarantees, from the standard library documentation: - A group **always waits for all of its child tasks** before the `with...TaskGroup` call returns, even cancelled ones, even if the body returns early with one result. - Children inherit the parent's priority and task-local values, and cancelling the parent cancels them. - `next()` returns results **in completion order**, and `nil` when no children are pending. - The group must not be used outside the task that created it; because adding a child is a mutating operation, the type system prevents the group from escaping into a child task in most cases. ## The sliding window Bounding concurrency is a pattern, not an API: 1. Make an iterator over the 50 photo names. 2. Add the first four uploads. 3. Loop on `try await group.next()`. Each time one upload finishes, record the result and, if a name remains, add the next upload. 4. When the iterator is exhausted and `next()` returns `nil`, every upload has finished. At no point are more than four children pending, and a slow photo does not hold up the others the way fixed batches of four would. Inside a group that may already be cancelled, `addTaskUnlessCancelled` returns `false` instead of adding a child that would start cancelled, which lets the loop stop adding work once the user has left the screen. ## What a thrown error does The documentation is explicit that throwing in one child does not immediately cancel the others. What happens depends on the body: | Situation | Outcome | |---|---| | A child throws and the body never calls `next()` | The error is discarded; the group returns normally | | `try await group.next()` collects the failed child | `next()` rethrows that child's error in the body | | The body lets that error escape | Remaining children are cancelled, awaited, then the error is rethrown | | The child catches its own error and returns `nil` or a `Result` | Nothing is cancelled; the body decides what a failure means | In the upload window above, a failure on photo 13 propagates out of the `while` loop, the three uploads still in flight are cancelled, the group waits for them to wind down cooperatively, and the caller sees that error. If the product wants "upload what you can, report the failures", catch inside each child and return a value describing the outcome. A non-throwing `withTaskGroup(of: Result<String, any Error>.self)` whose children wrap their own errors is the usual shape: the body sees every outcome, and nothing is cancelled unless the body decides so. Cancellation from outside works the same way: cancelling the task running the group, or calling `group.cancelAll()`, marks every child cancelled, and each child stops when its own code checks. ## Discarding groups When children are pure side effects, an ordinary group still stores each result until `next()` collects it. `withDiscardingTaskGroup` and `withThrowingDiscardingTaskGroup` (Swift 5.9, SE-0381) drop each child and its result as soon as it completes, which suits long-running servers that accept connections in a loop. They have no `next()`, so the error rule changes: a throwing discarding group **cancels itself as soon as any child throws**, and rethrows the first error once all children have finished. To let a particular error pass without tearing the group down, catch it inside that child. ## Review checklist - Is the number of children bounded by the input size or by an explicit window? - Does every `addTask` in a cancelled group make sense, or should it be `addTaskUnlessCancelled`? - Is a child's error collected with `next()`, or silently dropped by a body that never asks? - Does the code assume results come back in insertion order? - Is the window size a named value chosen with the server's limits and the device's memory in mind, rather than a number copied from an example? - Is the group's result type chosen to carry per-item failures when partial success is acceptable?
- Why not upload in fixed batches of four with `async let` or one group per batch?Because each batch waits for its slowest photo before the next batch starts, so one slow upload idles the other three slots. The sliding window refills a slot the moment any upload finishes, keeping four busy until the input runs out.
- If the body returns the first result from `next()` and exits, do the other children keep running?They keep running until they finish, and the group waits for all of them before returning; returning early does not cancel them. Call `group.cancelAll()` before returning if the remaining work is no longer wanted, so the children can stop cooperatively.
- A task group runs at most one child per CPU core.
- One child throwing immediately cancels every sibling in withThrowingTaskGroup.
- Returning from the group body early abandons the unfinished children.
- next() returns results in the order the children were added.
- A throwing discarding group ignores child errors because it discards results.