Skip to content
Tutorials Center
My learning

Topics

Lesson 123 of 146 ยท Platforms and Ecosystem

Swift on the Server

Learn how Swift runs backend services on Linux: HTTP basics, routing and middleware, async handlers, actors for shared state, Codable JSON, Vapor, Hummingbird and SwiftNIO.

Swift is not only for apps. It compiles to fast native code on Linux, starts in milliseconds, uses little memory, has no garbage collector pauses, and its concurrency model (async/await, actors, Sendable) makes the whole class of data-race bugs a compile-time error. Those are exactly the properties people want for backend services, command-line tools and serverless functions. Companies use Swift on the server for APIs, game backends, data pipelines and, because one language can serve both ends, for sharing model code between an iOS app and the service behind it.

This lesson explains how a Swift web service is put together. You will build the core of one (a request parser, a router with middleware, async handlers, shared state in an actor, JSON responses) in plain Swift that runs right here, and then read what the same ideas look like in the real frameworks Vapor, Hummingbird and SwiftNIO.

The runner has no network, no package manager and no web frameworks, so Vapor, Hummingbird and SwiftNIO code is read-only in this lesson, and clearly labelled. The runnable examples are small models that never open a socket: they take requests as values and return responses as values, which is also the most testable way to design a service.

What a web service does

An HTTP service repeats a simple cycle: read bytes from a socket, parse them into a request (method, path, headers, body), find the code that handles that route, run it, turn its result into a response (status, headers, body) and write the bytes back. Everything else (databases, authentication, logging) is code that runs around that cycle. Here is the first step, the text format itself, handled in Swift. The structure of the data is the point; the parsing is deliberately simple:

Swift Parsing a request, building a response

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice the types: Request and Response are plain structs conforming to Sendable. A server handles many requests at once on many threads, so everything crossing between them must be safe to share. Value types make that easy; a class carrying mutable state does not (see Sendable).

Real servers do not parse text by hand: SwiftNIO (below) reads sockets and parses HTTP, and gives your framework nicely typed requests.

Routing and middleware

A router maps GET /hello/:name to a function, extracts the name parameter and calls the function. Middleware is code that wraps every handler: logging, authentication, timing, CORS headers, error translation. Each middleware gets the request and a next function, can do work before and after calling next, or can answer by itself without calling it. This is exactly the function-types and closures material from earlier lessons, and handlers are async throws:

Swift A router with middleware and async handlers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Read the output closely, because it shows how middleware really behaves:

  • /hello/Ada passes through the logger, which prints both lines (-> before next, <- after).
  • /nope matches no route, so the router answers 404 before any middleware runs. In this model, middleware only wraps matched routes. Real frameworks usually run middleware for every request; the order of the layers is a design decision.
  • /boom throws. The logger prints -> GET /boom but never <-, because the error skipped the rest of its function. A real service handles this with a middleware that catches errors and turns them into a response (here the router does it and produces status 500).

Frameworks such as Vapor and Hummingbird provide this same structure, with much more: typed parameters, streaming bodies, route groups, content negotiation and so on.

Shared state without data races

A service almost always has state shared between requests: a cache, a counter, a connection pool, an in-memory store while you prototype. In languages without compile-time checks, shared state plus many threads means locks and race bugs. In Swift 6 the compiler refuses the dangerous version. Here is a counter shared by 100 concurrent tasks (a stand-in for 100 simultaneous requests):

Swift Shared class state across tasks (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler stops with error: passing closure as a 'sending' parameter risks causing data races between code in the current task and concurrent execution of the closure and a note that the closure captures counter. The program in a language without this check would compile and then lose updates under load, in a way you could not reproduce on your laptop. The cure is an actor, which serializes access to its own state (see actors and shared state):

Swift An actor as a store, JSON in and out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Five tasks created five users; every id from 1 to 5 was used exactly once, but which name got which id depends on scheduling, so the example prints only the ids and counts. That nondeterminism is normal in concurrent code: never write a test that depends on it. Notice too that Codable does the JSON work in both directions, and that the same User type could be shared with an iOS app through a Swift package.

An in-memory actor is perfect for learning and caches, but it loses data on restart and cannot be shared by several server processes. Real services put durable state in a database (PostgreSQL, MySQL, SQLite, Redis) and treat the actor as a cache or coordinator.

The Swift server ecosystem

Everything below is read-only: it needs Swift Package Manager (see SwiftPM) and network access to fetch packages. Versions change, so check each project's documentation for the current API.

SwiftNIO

SwiftNIO is the low-level engine under almost every Swift server framework. It is an event-driven, non-blocking network library: a small number of threads, each running an event loop, handle thousands of connections. It provides the channels, byte buffers and protocol handlers (HTTP/1.1, HTTP/2, WebSocket, TLS) and works with Swift concurrency. You will rarely write NIO code yourself, but its names appear in logs, stack traces and framework options.

Vapor

Vapor is the most popular full-featured framework: routing, middleware, Content (Codable request and response bodies), the Fluent ORM, authentication, sessions, WebSockets, a Leaf template engine and testing helpers. A small API looks like this:

Swift
// Read-only example: needs the Vapor package.
import Vapor

struct Greeting: Content {
    var message: String
}

func routes(_ app: Application) throws {
    app.get("hello", ":name") { req async throws -> Greeting in
        let name = req.parameters.get("name") ?? "world"
        return Greeting(message: "Hello, \(name)!")
    }

    app.post("users") { req async throws -> HTTPStatus in
        let user = try req.content.decode(NewUser.self)
        // save the user ...
        return .created
    }
}

The Content protocol makes a struct decodable from the request and encodable as the response, so the handler works with Swift types, not strings.

Hummingbird

Hummingbird is a lighter, modular framework built directly on Swift concurrency. It has a similar router and middleware model with fewer built-in parts, so you add only what you use. It is a good choice for microservices, serverless-style functions and for people who like small dependency trees.

Swift
// Read-only example: needs the Hummingbird package.
import Hummingbird

let router = Router()
router.get("hello") { _, _ in
    "Hello, world!"
}

let app = Application(
    router: router,
    configuration: .init(address: .hostname("127.0.0.1", port: 8080))
)
try await app.runService()

Other building blocks

  • Databases: PostgresNIO and Fluent for PostgreSQL, MySQLNIO, SQLite.swift/GRDB for SQLite, RediStack for Redis.
  • HTTP client: AsyncHTTPClient for calling other services. (URLSession exists on Linux in FoundationNetworking, but it is not the usual choice for servers.)
  • Observability: swift-log (logging), swift-metrics and swift-distributed-tracing define standard APIs that every framework integrates with.
  • Protocols: grpc-swift for gRPC, swift-openapi-generator to generate typed server and client code from an OpenAPI document.
  • Serverless: swift-aws-lambda-runtime builds AWS Lambda functions in Swift.

Deploying a Swift service (read-only)

You build a Linux executable and ship it. The usual route is a container; the Swift project publishes official images for building and running:

TEXT
# Dockerfile (read-only example)
FROM swift:6.3 AS build
WORKDIR /app
COPY . .
RUN swift build -c release --static-swift-stdlib

FROM ubuntu:24.04
COPY --from=build /app/.build/release/App /usr/local/bin/App
EXPOSE 8080
CMD ["App"]

--static-swift-stdlib links the Swift runtime into the binary, so the final image does not need the Swift toolchain. For fully static binaries there is also the Static Linux SDK (see Swift on Linux and Windows).

Production checklist: run behind a reverse proxy or load balancer that handles TLS, configure logging and graceful shutdown, set connection and body size limits, never trust request input (validate with Codable and your own rules), and load test before launch.

Why not just use another language?

Honest answer: Swift on the server is a smaller ecosystem than Node, Java, Go or Python. You will find fewer libraries and fewer answers online. Choose it when you already have Swift developers, when sharing types with an Apple app is valuable, when you want predictable latency and low memory, or when compile-time concurrency safety matters to you. Choose something else when the one library you need exists only elsewhere.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why are Request and Response modeled as structs conforming to Sendable?

    Values that cross concurrency boundaries must be safe to share. Immutable-by-copy value types are.
  2. 2. What does a middleware function receive and do?

    Middleware wraps the handler. Calling next continues the chain; returning without calling it short-circuits.
  3. 3. What does Swift 6 do with group.addTask { counter.hits += 1 } where Counter is a non-Sendable class?

    Strict concurrency checking in Swift 6 turns a possible data race into a compile error. An actor or a Mutex fixes it.
  4. 4. What is SwiftNIO?

    NIO provides event loops, channels and protocol handlers; Vapor and Hummingbird build on it.
  5. 5. Why is an in-memory actor store not enough for production data?

    Durable, shared data belongs in a database. The actor is fine for caches and for coordinating access.

Summary

  • Swift compiles to fast, low-memory native Linux binaries and checks data races at compile time, which suits backend services.
  • A service parses requests, routes them to async throws handlers, wraps them in middleware and encodes responses; model them as Sendable value types.
  • Shared mutable state needs an actor (or a lock like Mutex); the compiler rejects unsafe sharing.
  • Codable handles JSON both ways and can be shared with client apps.
  • SwiftNIO is the networking foundation; Vapor is the full-featured framework and Hummingbird the lighter, modular one.
  • Ship a Linux release build (often in a container), keep durable state in a database, and validate all input.
  • Everything involving real frameworks, sockets and deployment is read-only here; the runnable models explain the structure.

Next: Swift on Linux and Windows