A Swift chat client feeds messages and presence updates into AsyncStreams; which buffering policy suits each, and what does yield report when the buffer fills?
answer
- yield never waits for the reader
- the default keeps everything
- newest evicts old, oldest rejects new
- YieldResult says what fell out
basics
~20 syield(_:) never waits, so the policy decides what a lagging reader loses: .unbounded keeps all, .bufferingNewest(n) evicts the oldest, .bufferingOldest(n) rejects the newcomer. Messages need every element; presence needs .bufferingNewest(1). yield returns .enqueued, .dropped or .terminated.
solid answer
~40 s`AsyncStream.Continuation.yield(_:)` is synchronous: it never suspends the producer, so the `BufferingPolicy` is the only thing deciding what happens when the reader falls behind. The default `.unbounded` keeps every element, which is right for chat messages, where dropping one is data loss, but memory grows for as long as the reader stalls. `.bufferingNewest(n)` keeps the latest `n` and evicts the oldest, which fits presence or connection state: `.bufferingNewest(1)` hands a slow reader only the current state. `.bufferingOldest(n)` keeps the first `n` and rejects new arrivals, which suits work where the earliest items matter. `yield` reports the outcome as a `YieldResult`: `.enqueued(remaining:)`, `.dropped(element)` naming the element that fell out, or `.terminated` once the stream has ended.
code
swift · 18 linesenum Presence: Sendable { case online, typing, away }
@main struct BufferDemo {
static func main() async {
// Presence: only the latest state matters, so keep one value.
let (presence, presenceIn) = AsyncStream.makeStream(
of: Presence.self, bufferingPolicy: .bufferingNewest(1))
for state in [Presence.online, .typing, .away] {
print(presenceIn.yield(state)) // nobody is iterating yet
}
presenceIn.finish()
for await state in presence {
print("consumer saw", state)
}
}
}go deeper
Recall the three policies by name and that the default, .unbounded, keeps every element.
Explain which element each bounded policy drops and how yield reports it through .enqueued, .dropped and .terminated.
Pick a policy per stream from the data's meaning, explain why yield gives no backpressure, and reach for the unfolding initializer when the producer can wait.
Frame the choice as a loss-versus-memory budget per data type, and insist on counting drops so the trade-off is measured rather than assumed.
## No backpressure on the push side An `AsyncStream` fed through its **continuation** is push-based. The producer, here a socket delegate, calls `yield(_:)` whenever an event arrives, and the source says that call "returns to the caller immediately without blocking for any awaiting consumption from the iteration". If the reader is slower than the socket, elements pile up between them. The **`BufferingPolicy`**, set at creation with `bufferingPolicy:`, decides what that pile may hold. The default is `.unbounded`; the documentation describes it as a buffer limit of `Int.max`. ## The three policies | Policy | When the buffer is full | Element reported as `.dropped` | Fits | |---|---|---|---| | `.unbounded` | never full | none | chat messages, anything that must not be lost | | `.bufferingNewest(n)` | evicts the oldest buffered element | the evicted oldest one | presence, connection state, location | | `.bufferingOldest(n)` | rejects the new element | the new one | "first n wins", such as the first results of a search | For `n` of zero or less, nothing is buffered at all: "an iterator receives an element only if it is already awaiting a value when the continuation yields". That is a policy for "only if someone is listening right now". ## Reading `YieldResult` `yield(_:)` is `@discardableResult`, so most code ignores the result, but it carries the information you need to log or meter loss: - **`.enqueued(remaining:)`**: the element was handed to a waiting reader or buffered. `remaining` is a hint, and the source calls it "a lower bound on the number of remaining slots", because a concurrent read can change it at once. For `.unbounded` it is `Int.max`. - **`.dropped(Element)`**: the buffer was full. With `.bufferingNewest` and a positive limit, the associated element is the old one that was evicted (with a limit of zero it is the new one); with `.bufferingOldest` it is the element you just tried to yield. - **`.terminated`**: the stream had already finished or been cancelled, so the element went nowhere. ## Choosing for a chat client 1. **Messages**: keep `.unbounded`. A message silently evicted is a bug the user sees. The risk moves to memory, so watch for a reader that can stall (a loop waiting on slow work per message) and fix the reader rather than bounding the buffer. 2. **Presence and typing state**: use `.bufferingNewest(1)`. Only the latest state matters, and a reader that wakes late should see `away`, not replay `online`, `typing`, `away`. 3. **Telemetry you may sample**: a bounded policy plus a counter of `.dropped` results gives a measured loss rate instead of unbounded memory. ## When you need real backpressure A continuation cannot slow the producer down; it can only buffer or drop. When the producer can wait, as a log tailer reading a file can, use the pull-based initializer **`AsyncStream(unfolding:onCancel:)`**: its closure runs only when the reader asks for the next element, so reading happens at the consumer's pace and nothing piles up. The demand-signalling designs of reactive-streams libraries are the general form of this idea; Swift's continuation-based stream has no such demand signal. ## Where the policy lives The policy belongs to one stream and is fixed when the stream is created, through `init(_:bufferingPolicy:_:)` or `makeStream(of:bufferingPolicy:)`. A chat client therefore keeps separate streams for separate kinds of data rather than one stream of an enum mixing messages and presence: one stream cannot be lossless for messages and lossy for presence at the same time. The buffer exists only between the continuation and the reader; once a loop takes an element, the policy no longer applies to it. A reader that is already waiting in `next()` receives a yielded element directly, so the policy matters only while the reader is busy or not yet iterating. ## Traps - Mixing messages and presence in one stream, so a bound chosen for presence also drops messages. - Choosing `.bufferingOldest(1)` for state: the reader keeps the stale first state and every newer update is dropped. - Believing `.unbounded` slows a fast producer; nothing does, it only grows. - Reading `remaining` as an exact count; it is a lower-bound hint. - Yielding after `finish()` and treating the ignored `.terminated` as delivered.
- Why is .unbounded risky for the message stream, and what do you do about it?Nothing ever slows the socket, so a stalled reader lets the buffer grow without limit. For messages that must not be lost, keep `.unbounded` but make the reader cheap: hand slow work elsewhere, and watch memory. Bound the buffer only for data you are willing to drop, and count the `.dropped` results so the loss is visible.
- How would a log tailer get real backpressure instead of a buffer?Use `AsyncStream(unfolding:onCancel:)`. Its closure produces one element each time the reader calls `next()`, so the tailer reads the next line only when the consumer is ready and nothing accumulates. The continuation-based API cannot do that, because `yield(_:)` always returns immediately.
A voicemail box with room for n messages. bufferingOldest is the box that answers 'mailbox full' and loses the new caller; bufferingNewest erases the oldest message to record the new one; unbounded never fills until the phone runs out of storage.
- yield(_:) suspends the producer when the buffer is full.
- bufferingNewest(n) drops the element that was just yielded.
- The default AsyncStream buffer holds a small fixed number of elements.
- remaining in .enqueued is an exact count of free slots.
- bufferingOldest(1) is the right choice for a stream of latest presence state.