This is a companion to Designing a Production-Ready Async Image Pipeline with Swift 6 Concurrency. That article built AsyncImagePipeline: an actor-first subsystem for duplicate-request sharing, bounded prefetch, failure eviction, and cancellation under deduplication.
This article answers the next question a team actually asks: the pipeline is already correct, so why put The Composable Architecture around it, and how far should that rewrite go?
The short answer: migrate for composition, explicit effects, and deterministic tests. Do not migrate to replace the coordinator.
The companion project is TCAAsyncImagePipeline. The precursor remains AsyncImagePipeline.
We Are Not Replacing Correctness
AsyncImagePipeline was already production-oriented. Actors own mutable domains. In-flight work is shared. Cancellation of one waiter does not kill shared work. Failed entries are evicted so retries are fresh. Swift 6 strict concurrency is part of the design, not a warning to silence.
So this is not a rescue mission. The reason to migrate is a different constraint set:
- one observable app state instead of a
@MainActormodel driving four experiments - feature composition that can grow without a god object
- side effects that can be overridden in tests without hitting the network
- a written record of why each step was safe
What Was Already Good (and Must Stay)
Before any reducer, the architecture was:
GalleryModel (@MainActor)
->
AsyncImagePipeline (public facade)
->
ImageCache actor + DownloadCoordinator actor + NetworkLoader actor
->
decode / transformThe important flow is still the duplicate-request path. Caller B does not start a second download; it joins the in-flight Task:
if let cachedImage = await cache.read(url: url) {
return PipelineFetch(url: url, source: .cacheHit, image: cachedImage, duration: duration)
}
let (task, isNewWork) = await coordinator.retrieveOrCreate(url: url) { [weak self] in
do {
guard let self else { throw PipelineError.networkError("Pipeline deallocated") }
return try await self.loader.fetch(url: url)
} catch {
if let self {
await self.coordinator.evictFailed(url: url)
}
throw error
}
}
let image = try await task.value
await cache.insert(image)
await coordinator.markReady(url: url, image: image)Four experiments exist specifically to make those claims auditable:
| Experiment | Invariant |
|---|---|
| Duplicate requests | 3 callers, 2 newWork, 1 sharedInFlight |
| Bounded prefetch | 4 fetches, maxConcurrentRequests = 2 |
| Failure and retry | first failed(...), second newWork |
| Cancellation | caller B still gets sharedInFlight |
If TCA changed any of those, the migration would be a rewrite wearing a framework costume.
Non-goals
- Do not delete actors on day one.
- Do not change the URL set or the four scenarios.
- Do not treat "more reducer state" as progress.
- Do not accept a phase unless the same invariants still pass.
That last rule is the whole method.
Phase 0: Freeze Behavior Before Touching Structure
The first TCA file is not a reducer. It is a contract.
I added an in-app harness (--phase0-autorun) that runs all four experiments against the live pipeline, writes phase0-baseline-report.json, and marks each check passed or not. No UI tapping. Network is still real (picsum.photos IDs), so the run is evidence, not a mock.
Baseline capture (2026-10-27) on iOS Simulator:
- Duplicate:
newWorkStarts = 2,sharedInFlightHits = 1 - Bounded:
maxConcurrentRequests = 2, 4/4 succeeded - Retry:
failed(Transient failure for 600)thennewWork - Cancellation:
sources = ["sharedInFlight"]
All four: PASS. Every later phase re-ran the same harness. If you cannot replay the old behavior, you cannot claim the new architecture preserved it.
Phase 1: Wrap First
Then I introduced TCA as a shell:
AppFeature/AppViewas the root storeImagePipelineFeature/ImagePipelineViewas the experiment hostAsyncImagePipelineunchangedImagePipelineClientadded as a dependency scaffold, not yet the only execution path
@main
struct TCAAsyncImagePipelineApp: App {
private let store = Store(initialState: AppFeature.State()) {
AppFeature()
}
var body: some Scene {
WindowGroup {
AppView(store: store)
.task { await Phase0BaselineRunner.runIfEnabled() }
}
}
}The friction was organizational, not algorithmic: duplicate file names, reducer composition, case paths. After the shell compiled, I re-ran autorun. All four checks still PASS (phase1_artifacts/phase0-baseline-report-rerun.json).
Phase 2: Four Reducers, One Parent
GalleryModel was doing four jobs. TCA's value here is boring and real: scoped domains.
Scope(state: \.duplicate, action: \.duplicate) {
DuplicateRequestsFeature()
}
Scope(state: \.bounded, action: \.bounded) {
BoundedPrefetchFeature()
}
Scope(state: \.retry, action: \.retry) {
FailureAndRetryFeature()
}
Scope(state: \.cancellation, action: \.cancellation) {
CancellationFeature()
}Each experiment got its own State / Action / Reducer. Side effects started going through @Dependency(\.imagePipelineClient) instead of calling the actor from the reducer body.
This is also where a false progress marker appeared: I added DuplicateRequestsFeatureTests.swift before the Xcode project had a test target or scheme TestAction. xcodebuild test refused to run it. The file was clean. The suite did not exist.
Phase 3: Effects You Can Replace
The point of TCA in this codebase is not Store. It is the ability to say: this feature's I/O is a value I can swap.
In the end state, operations are keyed by experiment, so four isolated AsyncImagePipeline instances live inside the dependency, not in feature state.
enum ImagePipelineID: Hashable, Sendable {
case duplicate, bounded, retry, cancellation
}
struct ImagePipelineClient: Sendable {
var fetch: @Sendable (_ pipelineID: ImagePipelineID, _ url: URL) async -> PipelineFetch
var fetchBatch: @Sendable (_ pipelineID: ImagePipelineID, _ urls: [URL], _ maxConcurrent: Int) async -> [PipelineFetch]
var getMetrics: @Sendable (_ pipelineID: ImagePipelineID) async -> PipelineMetrics
var reset: @Sendable (_ pipelineID: ImagePipelineID) async -> Void
var setLogHandler: @Sendable (_ pipelineID: ImagePipelineID, _ handler: @escaping @Sendable (LogEvent) -> Void) async -> Void
var simulateFailure: @Sendable (_ pipelineID: ImagePipelineID, _ url: URL) async -> Void
}liveValue owns a registry actor and forwards to AsyncImagePipeline. Reducers never store the pipeline.
A passing client is not enough. Passing the actor through the client is still a wrapper. Ownership moved when State stopped containing let pipeline: AsyncImagePipeline.
Tests override only the client. Example: duplicate dedup without network.
$0.imagePipelineClient = ImagePipelineClient(
fetch: { _, url in
let source = await tracker.recordAndClassify(url: url)
return PipelineFetch(url: url, source: source, image: nil, duration: 0.01)
},
fetchBatch: { _, _, _ in [] },
getMetrics: { _ in await tracker.metrics() },
reset: { _ in await tracker.reset() },
setLogHandler: { _, _ in },
simulateFailure: { _, _ in }
)The assertions:
- Duplicate:
newWorkStarts = 2,sharedInFlightHits = 1 - Cancellation: second waiter still records a shared hit
- Retry: one failure, then fresh work
- Bounded:
maxConcurrentRequests = 2
After wiring TCAAsyncImagePipelineTests into the scheme: 4 tests, 0 failures on iPhone 17 (iOS 27). Then live autorun again (phase3_artifacts/phase0-baseline-report-rerun.json): all four experiments passed: true.
Two testing layers, two questions:
| Layer | Proves | Does not prove |
|---|---|---|
Mock ImagePipelineClient + store | reducer/effect contract, no network | actor algorithms |
--phase0-autorun | live dedup/bound/retry/cancel | isolation from the network |
TestStore is the stricter tool: exhaustive send / receive / finish. This project's first suite uses a hosted Store and waits on isRunning. That is enough to prove the experiment finishes with the expected metrics. It is not exhaustive action accounting. I would move the same cases onto TestStore if the action surface needed regression locks, not because the current tests are fake.
Phase 4: Stop Before the Interesting Mistake
The optional last step is the one architecture articles love: move DownloadCoordinator's in-flight map into reducer state. I evaluated it and rejected it.
| Concern | Option A: hybrid (chosen) | Option B: reducer-managed internals |
|---|---|---|
| Correctness under concurrency | Already proven in actors; three live parity gates stayed green | New design of shared tasks, eviction, bounds |
| Cancellation / failure | One waiter cancel ≠ shared-task cancel; failed entries evicted | Easy to wire .cancel(id:) to the wrong grain |
| Testability | Client mocks + live harness | Internals become pure transitions after a large rewrite |
| Onboarding | Actors for I/O; TCA for features | One model, if the team already thinks in TCA |
| Observability | PipelineMetrics / LogEvent from the facade | Every in-flight entry could be state, noisier |
Production-readiness answer, directly: yes, the TCA version is production-ready as a hybrid. The download coordinator should stay an actor until in-flight work itself is product state (a debug inspector, a per-URL progress UI owned by the app, a policy the reducer must decide). That is not this app.
Tradeoff Table
| Concern | Actor-first | TCA-first rewrite | What this migration did |
|---|---|---|---|
| In-flight work sharing | Coordinator dictionary of Tasks | Would re-encode as state + effects | Left in the actor |
| Ownership visibility | Isolation domains | Action/state tree | Features own UI state; client owns pipelines; actors own I/O |
| Effect composition | Task / task groups | .run, .cancellable, Scope | TCA at the feature edge |
| Testing ergonomics | Integration / custom async tests | Dependency override + (optionally) TestStore | Mocks for contracts; autorun for parity |
| Refactor scalability | Add methods on the facade | Add features and compose | Four scoped features |
| Dependency overhead | Low | TCA + case paths + test target ceremony | Real cost; paid once in Phase 3 wiring |
| Cancellation grain | Waiter Task vs shared work | Cancel IDs must match that grain | Unchanged actor semantics |
What TCA Cost
Honesty, because the precursor article did not sell actors as magic either.
- Boilerplate:
State/Action/Reducer/Scope/@Dependencyfor four small experiments is more files thanGalleryModel. - A test file is not a test suite. Until the
.xctesttarget and schemeTestActionexist, you have literature. - A client that still takes
AsyncImagePipelineas an argument is theater. Callers still own the service. - Live parity remains network-dependent. Autorun can fail because picsum is down, not because TCA is wrong.
- Hybrid looks unfinished to readers who wanted a 100% reducer rewrite. That is a communication problem, not an engineering one.
Prefer native SwiftUI when the feature is local and low-coordination; prefer TCA when cancellation, cross-feature invariants, and deterministic tests are first-order. This image pipeline is the third category: the coordination already lived in actors. TCA was justified at the app edge, not in the coordinator.
Decision Framework You Can Reuse
- Stay actor-first when the problem is shared in-flight work, cancellation isolation, or bounded I/O, and UI is a thin driver.
- Adopt TCA when many features must compose, effects must be explicit, and reducer tests are the main confidence mechanism.
- Stay hybrid when the actor service is already correct and you need TCA for composition and testability without re-deriving concurrency.
Checklist before a similar migration:
- Write the invariants down. Automate them.
- Wrap the service. Do not fork it.
- Split features only after the shell still passes parity.
- Put I/O behind a dependency. Then stop passing the service through that dependency.
- Wire a real test target before calling tests "done".
- Re-run the live harness.
- Ask whether internals must become UI state. If not, stop.
Final Takeaways
- A correct actor pipeline is not an argument against TCA. It is an argument against a total rewrite.
- Parity is a product. JSON reports beat "it still feels the same".
- Explicit effects are the TCA feature that paid rent here. Scoped tabs were nice.
TestStorecan wait. - Cancellation and retry semantics belong in the isolation domain that owns in-flight work.
- Production-ready does not mean "everything is a reducer". It means the team can change the app without silently breaking sharing, bounds, retry, or cancel.
Download the migrated app from the TCAAsyncImagePipeline GitHub repository. The actor-first precursor is AsyncImagePipeline; read the original pipeline article first if you have not.