Outbox Pattern Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Outbox Pattern runs in O(1) time and O(n) space, in Swift as in every other language.
- ✓Nothing for databases. On the server side Vapor with Fluent is the usual stack, and PostgresNIO is the layer beneath it when you want raw SQL.
- ✓Use the transaction method on the database, which commits when the returned future or async call completes successfully and rolls back when it throws, and keep every write inside that closure sequential.
- ✓The Swift trap: Structured concurrency makes it very easy to break this without noticing. Spawning a Task inside the transaction closure detaches that work: it runs independently, on a different executor, and any database call it makes checks out a different connection, so its writes are outside the transaction and commit on their own.
- ✓NIO runs on a small number of event loops, so blocking inside the closure stalls every other request assigned to that loop.
What Outbox Pattern actually is
Outbox Pattern in Swift: what you actually reach for
Swift implementation
import Fluent
import Vapor
struct Order: Model, Content {
static let schema = "orders"
@ID(key: .id) var id: UUID?
@Field(key: "customer_id") var customerID: UUID
@Field(key: "total_cents") var totalCents: Int
}
struct OutboxRow: Model {
static let schema = "outbox"
@ID(key: .id) var id: UUID?
@Field(key: "aggregate_id") var aggregateID: UUID
@Field(key: "event_type") var eventType: String
@Field(key: "payload") var payload: String
}
func placeOrder(on db: any Database, customerID: UUID, totalCents: Int) async throws {
try await db.transaction { tx in
let order = Order()
order.customerID = customerID
order.totalCents = totalCents
try await order.save(on: tx)
// SAME transaction, same connection: the whole pattern.
let row = OutboxRow()
row.aggregateID = try order.requireID()
row.eventType = "OrderPlaced"
row.payload = #"{"totalCents":#(totalCents)}"#
try await row.save(on: tx)
// DO NOT DO THIS:
// Task { try await broker.publish(...) }
//
// A Task spawned here DETACHES: it runs on a different executor and
// any database call it makes checks out a DIFFERENT connection, so
// its writes are outside this transaction and commit on their own.
// The closure returns, the transaction commits, and you have a
// partial write with no error anywhere. Everything in here must be
// awaited sequentially on "tx". Publishing is the relay's job.
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Outbox Pattern?
Nothing for databases. On the server side Vapor with Fluent is the usual stack, and PostgresNIO is the layer beneath it when you want raw SQL.
What is the most common Swift mistake when implementing Outbox Pattern?
Structured concurrency makes it very easy to break this without noticing. Spawning a Task inside the transaction closure detaches that work: it runs independently, on a different executor, and any database call it makes checks out a different connection, so its writes are outside the transaction and commit on their own. The closure returns, the transaction commits, and you have a partial write with no error anywhere. The rule is that everything inside the closure must be awaited sequentially on the connection the closure was handed, and nothing may be launched into the background from within it. Publishing to the broker in particular belongs to the relay, not to the transaction.
How does Outbox Pattern actually perform in Swift?
NIO runs on a small number of event loops, so blocking inside the closure stalls every other request assigned to that loop. Keeping the transaction to two statements and doing the network publish elsewhere is a throughput decision, not just a correctness one. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialMost AI and dev tools have a student plan. See which ones and how to claim them on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.