Stream NDJSON With URLSession And A Record Size Limit

Your build service sends progress as JSON. On localhost, each callback seems to contain one complete object. In production, one delivery contains three objects and the next stops halfway through an emoji.

The network has not agreed to your object boundaries. It was barely consulted.

Newline-delimited JSON, or NDJSON, gives the response an explicit record boundary. We can decode each record as it arrives, put a byte limit on an unfinished record, and stop the request when the consumer has enough.

This is useful for job progress, incremental search, and streaming exports whose server supports NDJSON. It uses established URLSession APIs, with explicit concurrency annotations for current Swift projects. The examples were checked with Xcode 27 / Swift 6.4; the networking API dates to iOS 15 and macOS 12.

Start with the response format

A Stack Overflow question about production JSON chunks describes this exact trap. It already has an answer explaining buffering and delimiters. The useful next step is a small implementation with a record budget and a clear lifetime.

Zach Waugh’s streaming example also shows how readable an async iteration loop can be. His example handles server-sent events. Here we will use NDJSON, a different format: no data: prefix, blank-line event separator, or automatic reconnection protocol.

For our build endpoint, the body might be:

{"step":1,"message":"Compiling","finished":false}
{"step":2,"message":"Tests passed","finished":true}

Each displayed line must end with a newline byte, including the final line. According to the NDJSON specification, records use UTF-8 and parsers accept LF or CRLF delimiters. Our reader ignores empty lines by default, offers a strict option, and rejects an unfinished final record. A connection closing is not a substitute for the delimiter.

The server must actually flush progress, and any proxy must allow streaming. A client cannot extract updates that are still sitting in a server’s response buffer.

Why not just use bytes.lines?

Apple’s async URLSession session demonstrates the convenient bytes.lines approach. It is a good starting point when the response contract and record sizes are trusted.

Here we want to stop after a configured number of bytes even if no newline ever arrives. Checking a completed string’s size comes too late for that policy. Instead, a tiny framer collects bytes until a delimiter, rejecting the next byte when the record is already full.

Put the following three Swift blocks in one file. The first contains the errors and the framer:

import Foundation

nonisolated enum NDJSONError: Error, Equatable {
    case invalidLimit
    case recordTooLarge(Int)
    case bareCarriageReturn
    case emptyRecord
    case unterminatedRecord
    case invalidUTF8JSON
    case nonHTTPResponse
    case httpStatus(Int)
    case contentType(String?)
}

nonisolated struct NDJSONFramer {
    private var record = Data()
    private var pendingCR = false
    let maximumRecordBytes: Int
    let ignoreEmptyLines: Bool

    init(maximumRecordBytes: Int, ignoreEmptyLines: Bool = true) throws {
        guard maximumRecordBytes > 0 else { throw NDJSONError.invalidLimit }
        self.maximumRecordBytes = maximumRecordBytes
        self.ignoreEmptyLines = ignoreEmptyLines
    }

    mutating func push(_ byte: UInt8) throws -> Data? {
        if byte == 0x0A {
            pendingCR = false
            guard !record.isEmpty else {
                if ignoreEmptyLines { return nil }
                throw NDJSONError.emptyRecord
            }
            let complete = record
            record = Data()
            return complete
        }
        guard !pendingCR else { throw NDJSONError.bareCarriageReturn }
        if byte == 0x0D {
            pendingCR = true
            return nil
        }
        guard record.count < maximumRecordBytes else {
            throw NDJSONError.recordTooLarge(maximumRecordBytes)
        }
        record.append(byte)
        return nil
    }

    func finish() throws {
        guard record.isEmpty, !pendingCR else {
            throw NDJSONError.unterminatedRecord
        }
    }
}

The limit counts encoded bytes, excluding the LF or CRLF delimiter. A 64 KiB budget therefore does not mean 65,536 visible characters. UTF-8 has other plans for an emoji.

pendingCR lets CRLF straddle deliveries while rejecting a bare carriage return. We don’t turn partial byte sequences into strings, so splitting a multibyte character is harmless. At EOF, finish() rejects any retained bytes or incomplete CRLF.

The framer returns a complete record and releases its own reference to those bytes. An invalid record ends this reader; there is no attempt to skip damaged input and guess what the sender meant.

Give the stream one owner

The second block connects framing to URLSession.bytes(for:delegate:). It returns either normal EOF or an intentional stop requested by the consumer:

nonisolated enum NDJSONEnd {
    case endOfFile
    case stoppedByConsumer
}

@concurrent
nonisolated func consumeNDJSON<Value: Decodable & Sendable>(
    _ request: URLRequest,
    as type: Value.Type,
    maximumRecordBytes: Int = 64 * 1024,
    ignoreEmptyLines: Bool = true,
    receive: @Sendable (Value) async throws -> Bool
) async throws -> NDJSONEnd {
    var framer = try NDJSONFramer(
        maximumRecordBytes: maximumRecordBytes,
        ignoreEmptyLines: ignoreEmptyLines
    )
    let session = URLSession(configuration: .ephemeral)

    defer { session.invalidateAndCancel() }

    do {
        try Task.checkCancellation()
        var request = request
        request.setValue("application/x-ndjson", forHTTPHeaderField: "Accept")
        let (bytes, response) = try await session.bytes(for: request)

        return try await withTaskCancellationHandler {
            try Task.checkCancellation()
            guard let http = response as? HTTPURLResponse else {
                throw NDJSONError.nonHTTPResponse
            }
            guard http.statusCode == 200 else {
                throw NDJSONError.httpStatus(http.statusCode)
            }
            guard http.mimeType?.lowercased() == "application/x-ndjson" else {
                throw NDJSONError.contentType(http.mimeType)
            }

            let decoder = JSONDecoder()
            for try await byte in bytes {
                try Task.checkCancellation()
                guard let record = try framer.push(byte) else { continue }
                guard !record.contains(0), String(data: record, encoding: .utf8) != nil else {
                    throw NDJSONError.invalidUTF8JSON
                }
                let value = try decoder.decode(type, from: record)
                let keepReading = try await receive(value)
                try Task.checkCancellation()
                if !keepReading { return .stoppedByConsumer }
            }
            try Task.checkCancellation()
            try framer.finish()
            return .endOfFile
        } onCancel: {
            bytes.task.cancel()
        }
    } catch {
        if Task.isCancelled { throw CancellationError() }
        throw error
    }
}

The endpoint contract is deliberately specific: HTTP 200 and application/x-ndjson, with MIME parameters such as charset=utf-8 permitted. An HTML error page or a different successful response shape should fail before decoding. If your service has another documented media type, adapt that check explicitly.

Before decoding, we check that the complete record is valid UTF-8 and contains no raw NUL. A raw NUL is illegal in JSON text; this also prevents Foundation’s encoding detection from accepting UTF-16 bytes that happen to pass a UTF-8 string check. A JSON escape such as \u0000 contains no raw NUL byte and remains valid. JSON syntax checking and decoding into the model then belong to JSONDecoder. Add any business-rule validation your records require.

The reader uses a dedicated ephemeral session because it owns this one request. invalidateAndCancel() cancels that session’s outstanding tasks. The defer covers EOF, a consumer returning false, bad input, and a throwing consumer. After bytes(for:) returns, the cancellation handler cancels the specific transfer task, including when iteration is waiting for more bytes. During the initial bytes(for:) call, cancellation uses URLSession’s async support.

Do not replace that owned session with URLSession.shared and keep the same cleanup strategy: invalidating the shared session has no effect. This example also does not inherit your app’s custom delegate, authentication flow, or session configuration. Supply any required request headers, and adapt session ownership deliberately if those features are needed.

withTaskCancellationHandler still runs its operation when the task is already cancelled. We check before opening the request and again inside the handler’s operation, covering cancellation between acquiring the response and installing the handler. We only invalidate the session when the function exits: invalidating it concurrently with creating a task risks trying to use a session that is already invalid. The catch normalizes errors to CancellationError when this task is cancelled; other errors propagate unchanged.

Cancellation remains cooperative for the consumer. If receive suspends in work that never responds to cancellation, closing the network request cannot force that work to return.

Await the work for each record

There is one receive call in flight at a time. We await it before asking the iterator for another byte. This avoids adding a separate producer task and an unbounded queue of decoded values.

That does not cap the process at 64 KiB. Foundation and the transport may buffer ahead; decoding allocates a model; and your consumer can retain every value it receives. The guarantee here is narrower: the framer never appends more than the configured number of payload bytes to one record. It is not a measured total-memory guarantee or a promise about the server’s sending rate.

@concurrent explicitly moves the reader’s execution off the caller’s actor. Framing and decoding therefore do not inherit MainActor isolation in an app using the newer default-isolation settings. The syntax requires a Swift 6.2-or-newer compiler; it does not require an iOS 27 networking API.

Use small Sendable value models. If a consumer updates UI state, make the required hop to its MainActor owner and await that update. Don’t spawn an unrelated task for every record and quietly rebuild the queue we just avoided.

Know whether the job actually finished

The final block is a complete consumer for the two JSON records above:

nonisolated struct BuildUpdate: Decodable, Sendable {
    let step: Int
    let message: String
    let finished: Bool
}

nonisolated enum BuildStreamError: Error {
    case missingCompletion
}

nonisolated func printBuildProgress(from url: URL) async throws {
    let end = try await consumeNDJSON(URLRequest(url: url), as: BuildUpdate.self) { update in
        print("Step \(update.step): \(update.message)")
        return !update.finished
    }
    guard case .stoppedByConsumer = end else {
        throw BuildStreamError.missingCompletion
    }
}

Call try await printBuildProgress(from: url) from the task that owns watching this job. Cancelling that task cancels its read. In a SwiftUI feature, that ownership can belong to the view’s .task(id:); error presentation and retaining the latest progress belong to your screen’s model.

Here, finished: true is the application-level terminal record. Returning false stops the read and yields .stoppedByConsumer. If the connection ends cleanly before that marker, we throw missingCompletion, even if every received JSON line was valid. A clean EOF means the response ended; it does not prove the build succeeded.

For a finite export whose contract defines EOF as success, handle .endOfFile differently. For a live feed, reconnecting needs an explicit cursor or event ID and a replay policy. This reader does not invent either, retry side effects, or guarantee exactly-once delivery.

Test a stream that refuses to finish politely

The exact Swift blocks were compiled together for iOS 15 simulator and macOS 12 deployment targets, in Swift 6 mode with warnings treated as errors. Both ordinary isolation and MainActor default isolation were checked.

Runtime checks use a loopback HTTP server on macOS 27. They exercise fragmented Unicode, several records in one write, both delimiters, empty-line policy, exact and excessive byte limits, malformed input, and an unterminated last line. The server also withholds the rest of a response until the consumer acknowledges the first record, demonstrating delivery before EOF.

Separate checks reject the wrong status and media type, stop on a terminal record, propagate a consumer’s error, and cancel both before response headers and while the server keeps the body open. Those exit paths are checked for connection closure. These are local macOS observations, not iOS-device, proxy, or throughput measurements. Run the same failure cases against your real service and supported OS versions.

For an ordinary JSON array that only becomes meaningful when the response finishes, our large JSON feed article covers that different job. Use streaming when the server exposes meaningful incremental records, then make the boundary, budget, and end condition explicit.