Cap the Concurrency: TaskGroup and a Fixed Worker Limit for Batch Image Exports in Swift
When you export 80 photos, the tempting Swift Concurrency move is to throw every photo into a TaskGroup and let the system sort it out. It reads cleanly. It also tends to decode too many full-size images at once, and on an iPhone that is how a batch that was fine at ten photos starts getting jetsam'd at eighty.
I build BatchMark, an iPhone app for finishing photos in batches, so this is a problem I have to take seriously. What follows is a teaching version of a simple pattern: keep a TaskGroup, but only let a small number of photos be in flight at a time. It is not the app's source.
The problem isn't the group. It's the queue length.
withTaskGroup is a good tool. It gives you structured concurrency, cancellation that actually reaches the children, and a place to collect results. The habit that hurts is adding one task per photo up front.
A typical export does, for each photo:
- Decode the source
- Render a watermark, crop, or filter into a new bitmap
- Encode JPEG or HEIC
- Write the file
Steps 1 and 2 hold large bitmaps in memory. If you start 80 of those tasks at once, you have asked the device to hold a large number of decoded images plus their output buffers. The group will run many of them concurrently; the exact number is up to the executor, not up to your memory budget.
A memory warning, or a jetsam, in the middle of a batch is worse than a slow batch. People would rather wait than lose the work.
Pick a small, boring limit
For full-size photo export I would start with two or three concurrent workers, not eight, and not "however many cores." Encoding is often limited by memory bandwidth and by the size of the bitmaps, not by idle CPU. On older phones, two is plenty. You can raise it later if Instruments says you have headroom; it is harder to raise a limit after you've shipped a crash.
Keep the limit in one place, and keep it independent of the photo count:
let maxConcurrent = 3
Don't derive it from ProcessInfo.processInfo.activeProcessorCount for this kind of work. Core count is a poor proxy for "how many 12-megapixel bitmaps may I hold."
A TaskGroup that refills itself
The pattern is: start maxConcurrent tasks, then start a new one each time one finishes, until the list is done.
import Foundation
import ImageIO
import UniformTypeIdentifiers
struct PhotoJob: Sendable {
let source: URL
let destination: URL
}
enum BatchExportError: Error {
case cannotDecode(URL)
case cannotEncode(URL)
}
enum ExportLimiter {
static func run(
jobs: [PhotoJob],
maxConcurrent: Int,
process: @escaping @Sendable (PhotoJob) async throws -> Void
) async throws {
guard !jobs.isEmpty else { return }
let limit = min(maxConcurrent, jobs.count)
try await withThrowingTaskGroup(of: Void.self) { group in
var next = 0
func enqueue(_ index: Int) {
let job = jobs[index]
group.addTask { try await process(job) }
}
while next < limit {
enqueue(next)
next += 1
}
while let _ = try await group.next() {
if next < jobs.count {
enqueue(next)
next += 1
}
}
}
}
}
A few details worth not skipping:
- Use a throwing group if a failure should stop the batch. If you would rather record the error and continue with the next photo, use a non-throwing group and return a
Resultfrom each task. That "don't abort the whole batch" design is a separate topic; the concurrency cap is the same in both cases. - Don't close over a big image in the task. The process function should load, render, write, and drop the bitmaps before it returns. If you collect
CGImageresults in an array to write later, you have only moved the memory spike. - Cancellation. If the user cancels,
TaskGroupcancels its children when the group goes out of scope, or when you callgroup.cancelAll(). Your process function should checkTask.isCancelledbetween the expensive steps - after decode, after render, before write - and throwCancellationError. A limit of three doesn't help if a cancelled task still encodes a 4000-pixel JPEG.
What the worker actually does
The limiter doesn't care how you render. A minimal worker, for a "re-encode this file" example, looks like this:
func reencode(_ job: PhotoJob) async throws {
try Task.checkCancellation()
guard let source = CGImageSourceCreateWithURL(job.source as CFURL, nil),
let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else {
throw BatchExportError.cannotDecode(job.source)
}
try Task.checkCancellation()
let type = UTType.jpeg.identifier as CFString
guard let dest = CGImageDestinationCreateWithURL(
job.destination as CFURL, type, 1, nil
) else {
throw BatchExportError.cannotEncode(job.destination)
}
let options: [CFString: Any] = [
kCGImageDestinationLossyCompressionQuality: 0.9
]
CGImageDestinationAddImage(dest, image, options as CFDictionary)
try Task.checkCancellation()
guard CGImageDestinationFinalize(dest) else {
throw BatchExportError.cannotEncode(job.destination)
}
}
This is deliberately small. A real export would render into a new context, and might write to a temporary URL first and then move the file. The important part for memory is that image is a local, and nothing in the limiter retains it.
Call it like this:
try await ExportLimiter.run(jobs: jobs, maxConcurrent: 3) { job in
try await reencode(job)
}
Order, progress, and why I wouldn't start every task at once
TaskGroup yields results as they finish, not in the order you added them. If you need exports to appear in the same order as the album, don't serialize the work to get that. Give each job an index, let the workers finish out of order, and update your progress UI by count ("17 of 80"), not by which photo number just finished. If you also need a manifest in original order, store results in an array by index, and write the manifest when the group finishes.
Starting all 80 tasks up front and hoping only a few run is not the same as a cap. The group's children all exist; each one may start decoding as soon as the executor has a slot. You want the next decode to start only after a previous job has finished and released its buffers. That's why the group is refilled one at a time.
A semaphore is also fine
If you'd rather not manage the refill yourself, an async semaphore with a count of maxConcurrent, plus a task group that does add every job, can work - but only if wait() happens before the decode, not after. The refill version makes that harder to get wrong, which is why I prefer it for teaching.
Don't use a GCD semaphore (DispatchSemaphore) inside async tasks to do this. You can deadlock a cooperative thread. Stick to structured concurrency.
What I'd measure before raising the limit
If you do go looking for speed, look at peak memory and at the time to finish a representative batch - a few dozen large photos is enough - at 2, 3 and 4 workers. I won't quote numbers I haven't measured on a particular device. What I would check is whether going from 2 to 3 helps a little, and whether going to 8 helps less than it costs in memory. Instruments' Allocations and the Memory Gauge in Xcode are enough. If peak memory climbs in a straight line with the cap, the cap is doing its job and you should keep it low.
Closing
A batch photo pipeline is less like a server, where more concurrency is almost always better, and more like a small workshop with a limited bench. Two or three photos on the bench at a time is usually enough. TaskGroup is still the right tool - you just don't put the whole queue on the bench at once.
The code above is a teaching sketch. It isn't BatchMark's source, and I haven't compiled it in this write-up. The APIs are the usual ones: withThrowingTaskGroup, CGImageSource, CGImageDestination. Used carefully, they let you export a large set without asking the phone to hold the large set in memory.
Comments
No comments yet. Start the discussion.