Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Event Sourcing Implementation in Swift

19 min readadvanced
Website QA and SEO audits

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

  • ✓Event Sourcing runs in O(1) append time and O(n) space, in Swift as in every other language.
  • ✓An enum with associated values is the event set, and switch over it is exhaustive without a default.
  • ✓reduce(into:) rather than reduce, because state is a value type and the returning form copies it once per event.
  • ✓The Swift trap: Swift synthesises Codable for enums with associated values by keying off the case name and the parameter labels, so renaming .deposited to .credited, or renaming its cents label, silently changes the on-disk shape and every older event stops decoding.
  • ✓COW is the whole performance story. reduce(into:) keeps the state's buffer uniquely referenced so appends stay in place; any stray retained reference flips every subsequent mutation into a full copy.

What Event Sourcing actually is

Event sourcing keeps the append-only log of what happened as the system of record and derives current state by folding that log with a pure function, state = events.reduce(apply, seed). Nothing overwrites; a correction is another event. The interesting constraint is that the log outlives both the process and the code that wrote it, so every event you ever append becomes a permanent input to a function you have not written yet. That forces three things the naive version skips: snapshots so replay does not grow unbounded, upcasting so a 2019 payload still folds under 2026 code, and a compare-and-set on the stream version so two writers cannot both append version 8. The eight languages diverge because those three things are serialisation and closed-set problems, not algorithm problems. Rust, Swift and Java can make the event set a real sum type and let the compiler prove the fold is exhaustive; C# can model the same shape with records but has no closed union, so a switch expression over it cannot be proven exhaustive and a discard arm guarding a runtime throw stays mandatory; Go and Python and JavaScript must dispatch on a tag string; TypeScript can express the union but erases it before the bytes arrive.

Event Sourcing in Swift: what you actually reach for

An enum with associated values is the event set, and switch over it is exhaustive without a default. Foundation gives JSONEncoder and JSONDecoder plus Codable; set dateEncodingStrategy and dateDecodingStrategy to .iso8601 explicitly, because the default .deferredToDate writes a Double of seconds since 2001-01-01. reduce(into:) from the standard library is the fold, UUID makes event ids, and an actor is the natural per-stream serialisation point so the version check and the append cannot interleave. Events carry Sendable so they can cross that actor boundary.

Swift implementation

reduce(into:) rather than reduce, because state is a value type and the returning form copies it once per event. Events are structs or enums with let properties and Sendable conformance. Reviewers insist on hand-written CodingKeys or a full init(from:) on every event so that a Swift-side rename cannot silently rename the wire format. They reject class-based events, reject a projection registry of closures that captures self strongly, and reject force-unwrapping a decode result.
swift
import Foundation

enum Event: Decodable, Sendable {
    case deposited(cents: Int)
    case withdrawn(cents: Int)

    // Hand-written because this stores a FLAT {type, cents} envelope, not the nested
    // single-key object the synthesised coder emits. A pure RENAME would not need this:
    // a top-level CodingKeys case, plus a nested DepositedCodingKeys, retargets names.
    enum CodingKeys: String, CodingKey { case type, cents }

    init(from decoder: Decoder) throws {
        let c = try decoder.container(keyedBy: CodingKeys.self)
        let cents = try c.decode(Int.self, forKey: .cents)
        switch try c.decode(String.self, forKey: .type) {
        case "deposited": self = .deposited(cents: cents)
        case "withdrawn": self = .withdrawn(cents: cents)
        case let other:
            throw DecodingError.dataCorruptedError(
                forKey: .type, in: c, debugDescription: "unknown event \(other)")
        }
    }
    // encode(to:) is the mirror image and must be written by hand too
}

struct Account: Sendable { var cents = 0; var version = 0 }

func replay(_ events: [Event], from snapshot: Account = Account()) -> Account {
    // reduce(into:) keeps the buffer uniquely referenced, so COW never deep-copies per event
    events.reduce(into: snapshot) { acc, event in
        switch event {
        case .deposited(let c): acc.cents += c
        case .withdrawn(let c): acc.cents -= c
        }
        acc.version += 1
    }
}

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 Free

The Swift-specific trap

Swift synthesises Codable for enums with associated values by keying off the case name and the parameter labels, so renaming .deposited to .credited, or renaming its cents label, silently changes the on-disk shape and every older event stops decoding. CodingKeys alone can absorb a rename: a top-level CodingKeys case pins each case's wire name, and a nested DepositedCodingKeys pins that case's labels. Only a shape change needs init(from:) and encode(to:) by hand. The other one is copy-on-write: hold any second reference to the state's storage while folding, a snapshot array or a captured closure, and the refcount rises above one so every mutation inside apply deep-copies the whole collection, turning an O(n) replay into O(n squared) with no code change visible at the call site.

Performance in Swift, beyond the O(1) append

COW is the whole performance story. reduce(into:) keeps the state's buffer uniquely referenced so appends stay in place; any stray retained reference flips every subsequent mutation into a full copy. ARC retain and release traffic is real in a tight loop, which is why value-type enum payloads beat class-based events. Passing events as any Event through an existential adds dynamic dispatch and boxes any payload larger than three words, whereas a concrete enum is statically dispatched and stays inline. Foundation's JSONDecoder is comparatively slow, so snapshot aggressively. The asymptotic cost is the same in every language, O(1) append time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Event Sourcing between languages.

Real-World Applications

Event Sourcing is used extensively in production software: relational databases, NoSQL systems, ORMs, and data pipelines use this pattern for managing data access and consistency. In Swift, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Event Sourcing helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Event Sourcing appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Event Sourcing over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Event Sourcing to build pattern recognition. In Swift, demonstrate proficiency with optionals and value types to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Swift code that is both correct and maintainable.

Frequently Asked Questions

Which Swift type or library should I use for Event Sourcing?

An enum with associated values is the event set, and switch over it is exhaustive without a default. Foundation gives JSONEncoder and JSONDecoder plus Codable; set dateEncodingStrategy and dateDecodingStrategy to .iso8601 explicitly, because the default .deferredToDate writes a Double of seconds since 2001-01-01. reduce(into:) from the standard library is the fold, UUID makes event ids, and an actor is the natural per-stream serialisation point so the version check and the append cannot interleave. Events carry Sendable so they can cross that actor boundary.

What is the most common Swift mistake when implementing Event Sourcing?

Swift synthesises Codable for enums with associated values by keying off the case name and the parameter labels, so renaming .deposited to .credited, or renaming its cents label, silently changes the on-disk shape and every older event stops decoding. CodingKeys alone can absorb a rename: a top-level CodingKeys case pins each case's wire name, and a nested DepositedCodingKeys pins that case's labels. Only a shape change needs init(from:) and encode(to:) by hand. The other one is copy-on-write: hold any second reference to the state's storage while folding, a snapshot array or a captured closure, and the refcount rises above one so every mutation inside apply deep-copies the whole collection, turning an O(n) replay into O(n squared) with no code change visible at the call site.

How does Event Sourcing actually perform in Swift?

COW is the whole performance story. reduce(into:) keeps the state's buffer uniquely referenced so appends stay in place; any stray retained reference flips every subsequent mutation into a full copy. ARC retain and release traffic is real in a tight loop, which is why value-type enum payloads beat class-based events. Passing events as any Event through an existential adds dynamic dispatch and boxes any payload larger than three words, whereas a concrete enum is statically dispatched and stays inline. Foundation's JSONDecoder is comparatively slow, so snapshot aggressively. Time complexity is O(1) append and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? Replit free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.