Skip to content

Lesson 2 of 9 · 27m

Async/Await, Event Loops, and Concurrency Without Self-Inflicted Damage

Use Swift structured concurrency correctly in Vapor, avoid blocking server threads, and design cancellation and shared state deliberately.

Every server-side Swift team has a scar from a blocking dependency hidden inside an async route. It looks fine with one tester. Under traffic, a few slow calls park the threads doing useful work and unrelated endpoints become intermittent. Asynchrony does not make blocking cheap.

The scarce-thread mental model

Vapor is built on SwiftNIO and Swift concurrency. Do not perform long synchronous blocking work in request handling:

// Bad shape: blocks a server thread
let html = try String(contentsOf: someURL)

// Better shape: suspension lets the runtime serve other work
let response = try await req.client.get(URI(string: upstream))
let projects = try await Project.query(on: req.db).all()

If a legacy dependency is unavoidably blocking, isolate it behind a bounded executor or separate service. Do not sprinkle it through handlers.

Structured concurrency is the default

Use async let only for independent operations:

async let project = Project.find(projectID, on: req.db)
async let membership = Membership.find(userID: user.id, projectID: projectID, on: req.db)

guard let loadedProject = try await project,
      try await membership != nil else {
    throw Abort(.notFound)
}

Do not parallelize dependent authorization checks merely because the syntax is available. Concurrency increases connection-pool pressure as well as speed.

Cancellation and lifetimes

Clients disconnect and proxies time out. Cancellation is cooperative:

try Task.checkCancellation()
let results = try await search.execute(on: req.db)

Be careful with unstructured work:

Task {
    try await sendEmail(using: req)  // unclear owner, lifetime, and cancellation
}

If work must finish before the response, await it. If it must continue afterward, persist a job and let a worker own it.

Isolate mutable shared state

An actor protects the memory it owns:

actor FeatureFlagCache {
    private var values: [String: Bool] = [:]
    func value(for key: String) -> Bool? { values[key] }
    func store(_ value: Bool, for key: String) { values[key] = value }
}

Actors do not make external side effects transactional. They only serialize access to their isolated state.

Field notes

  • CPU-heavy image processing stays expensive when asynchronous; move it to workers.
  • A random Task { } usually means nobody decided who owns the work.
  • Parallel database reads can exhaust the pool faster than sequential reads.
  • One-user load tests prove syntax, not saturation behavior.

Was this lesson helpful?

Sign in to rate