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.

01

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 @MainActor model 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
02

What Was Already Good (and Must Stay)

Before any reducer, the architecture was:

Baseline architecture
GalleryModel (@MainActor)
   ->
AsyncImagePipeline (public facade)
   ->
ImageCache actor + DownloadCoordinator actor + NetworkLoader actor
   ->
decode / transform

The important flow is still the duplicate-request path. Caller B does not start a second download; it joins the in-flight Task:

Swift
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:

ExperimentInvariant
Duplicate requests3 callers, 2 newWork, 1 sharedInFlight
Bounded prefetch4 fetches, maxConcurrentRequests = 2
Failure and retryfirst failed(...), second newWork
Cancellationcaller 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.

03

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) then newWork
  • 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.

04

Phase 1: Wrap First

Then I introduced TCA as a shell:

  • AppFeature / AppView as the root store
  • ImagePipelineFeature / ImagePipelineView as the experiment host
  • AsyncImagePipeline unchanged
  • ImagePipelineClient added as a dependency scaffold, not yet the only execution path
Swift
@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).

05

Phase 2: Four Reducers, One Parent

GalleryModel was doing four jobs. TCA's value here is boring and real: scoped domains.

Swift
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.

06

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.

Swift
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.

Swift
$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:

LayerProvesDoes not prove
Mock ImagePipelineClient + storereducer/effect contract, no networkactor algorithms
--phase0-autorunlive dedup/bound/retry/cancelisolation 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.

07

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.

ConcernOption A: hybrid (chosen)Option B: reducer-managed internals
Correctness under concurrencyAlready proven in actors; three live parity gates stayed greenNew design of shared tasks, eviction, bounds
Cancellation / failureOne waiter cancel ≠ shared-task cancel; failed entries evictedEasy to wire .cancel(id:) to the wrong grain
TestabilityClient mocks + live harnessInternals become pure transitions after a large rewrite
OnboardingActors for I/O; TCA for featuresOne model, if the team already thinks in TCA
ObservabilityPipelineMetrics / LogEvent from the facadeEvery 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.

08

Tradeoff Table

ConcernActor-firstTCA-first rewriteWhat this migration did
In-flight work sharingCoordinator dictionary of TasksWould re-encode as state + effectsLeft in the actor
Ownership visibilityIsolation domainsAction/state treeFeatures own UI state; client owns pipelines; actors own I/O
Effect compositionTask / task groups.run, .cancellable, ScopeTCA at the feature edge
Testing ergonomicsIntegration / custom async testsDependency override + (optionally) TestStoreMocks for contracts; autorun for parity
Refactor scalabilityAdd methods on the facadeAdd features and composeFour scoped features
Dependency overheadLowTCA + case paths + test target ceremonyReal cost; paid once in Phase 3 wiring
Cancellation grainWaiter Task vs shared workCancel IDs must match that grainUnchanged actor semantics
09

What TCA Cost

Honesty, because the precursor article did not sell actors as magic either.

  • Boilerplate: State / Action / Reducer / Scope / @Dependency for four small experiments is more files than GalleryModel.
  • A test file is not a test suite. Until the .xctest target and scheme TestAction exist, you have literature.
  • A client that still takes AsyncImagePipeline as 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.

10

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:

  1. Write the invariants down. Automate them.
  2. Wrap the service. Do not fork it.
  3. Split features only after the shell still passes parity.
  4. Put I/O behind a dependency. Then stop passing the service through that dependency.
  5. Wire a real test target before calling tests "done".
  6. Re-run the live harness.
  7. Ask whether internals must become UI state. If not, stop.
11

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. TestStore can 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.