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

Event Sourcing Implementation in Rust

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 Rust as in every other language.
  • ✓The event set is an enum, and match over it is exhaustive by the compiler, so no default arm and no unknown-variant class of bug.
  • ✓apply takes &mut self and returns nothing, because a persisted event already happened and cannot be rejected; validation lives in decide(&self, cmd) -> Result<Vec<Event>, DomainError> and the two are reviewed as separate functions.
  • ✓The Rust trap: #[serde(untagged)] on an event enum is the trap that costs you the log. Untagged tries each variant in declaration order and takes the first that deserialises, so Withdrawn { cents } and Deposited { cents } decode to whichever is listed first, with no error at all, and every replay after that is confidently wrong.
  • ✓No GC, so replay cost is allocation from serde_json building an owned String per text field.

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 Rust: what you actually reach for

The event set is an enum, and match over it is exhaustive by the compiler, so no default arm and no unknown-variant class of bug. serde plus serde_json carry the wire format: #[serde(tag = "type")] makes an internally tagged union, #[serde(rename)] and #[serde(alias)] rename a variant on disk without touching history, and #[serde(default)] lets a field added today decode against every event written before it. Iterator::fold does the replay. Errors are Result with a thiserror enum, never panics. For a compact binary log reach for rmp-serde, not bincode, because bincode is not self-describing.

Rust implementation

apply takes &mut self and returns nothing, because a persisted event already happened and cannot be rejected; validation lives in decide(&self, cmd) -> Result<Vec<Event>, DomainError> and the two are reviewed as separate functions. Reviewers want #[non_exhaustive] on a public event enum, a fold that never unwraps a deserialisation result, and Send + Sync on anything a per-stream writer task holds. They reject moving state by value per event and they reject #[serde(untagged)].
rust
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "type")]      // internally tagged. NEVER untagged for a log.
#[non_exhaustive]
pub enum Event {
    #[serde(rename = "deposited", alias = "credited")]  // alias = free rename of history
    Deposited { cents: i64, #[serde(default)] currency: Option<String> },
    #[serde(rename = "withdrawn")]
    Withdrawn { cents: i64 },
}

#[derive(Default, Debug)]
pub struct Account { pub cents: i64, pub version: u64 }

impl Account {
    // infallible on purpose: you cannot reject an event that already happened
    fn apply(&mut self, e: &Event) {
        match e {   // exhaustive; adding a variant is a compile error, not a runtime one
            Event::Deposited { cents, .. } => self.cents += cents,
            Event::Withdrawn { cents } => self.cents -= cents,
        }
        self.version += 1;
    }
}

// bytes are one mmapped buffer of newline-delimited JSON
pub fn replay(bytes: &[u8], mut acc: Account) -> serde_json::Result<Account> {
    for line in bytes.split(|b| *b == b'\n').filter(|l| !l.is_empty()) {
        let e: Event = serde_json::from_slice(line)?;  // slice, not str: no UTF-8 re-scan
        acc.apply(&e);
    }
    Ok(acc)
}

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 Rust-specific trap

#[serde(untagged)] on an event enum is the trap that costs you the log. Untagged tries each variant in declaration order and takes the first that deserialises, so Withdrawn { cents } and Deposited { cents } decode to whichever is listed first, with no error at all, and every replay after that is confidently wrong. Use tag. The second is field addition: adding cents: i64 to an existing variant makes every historical event fail with missing field cents, because Option<T> is implicitly defaulted but a plain integer is not, so a field addition needs #[serde(default)] to be backward-compatible. And #[serde(deny_unknown_fields)] on an event guarantees a rollback cannot read forward-written data.

Performance in Rust, beyond the O(1) append

No GC, so replay cost is allocation from serde_json building an owned String per text field. Deserialise from a single mmapped buffer with from_slice and borrow those fields with #[serde(borrow)] as &str and the string allocations disappear entirely. Watch enum size: a Vec<Event> pays the largest variant plus a discriminant for every element, so one variant with a fat payload doubles the memory traffic of the whole fold; Box that variant's body. Iterating a contiguous Vec is prefetcher-friendly and LLVM hoists the bounds checks out of the loop. 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 Rust, 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 Rust, demonstrate proficiency with ownership system and pattern matching to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Rust code that is both correct and maintainable.

Frequently Asked Questions

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

The event set is an enum, and match over it is exhaustive by the compiler, so no default arm and no unknown-variant class of bug. serde plus serde_json carry the wire format: #[serde(tag = "type")] makes an internally tagged union, #[serde(rename)] and #[serde(alias)] rename a variant on disk without touching history, and #[serde(default)] lets a field added today decode against every event written before it. Iterator::fold does the replay. Errors are Result with a thiserror enum, never panics. For a compact binary log reach for rmp-serde, not bincode, because bincode is not self-describing.

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

#[serde(untagged)] on an event enum is the trap that costs you the log. Untagged tries each variant in declaration order and takes the first that deserialises, so Withdrawn { cents } and Deposited { cents } decode to whichever is listed first, with no error at all, and every replay after that is confidently wrong. Use tag. The second is field addition: adding cents: i64 to an existing variant makes every historical event fail with missing field cents, because Option<T> is implicitly defaulted but a plain integer is not, so a field addition needs #[serde(default)] to be backward-compatible. And #[serde(deny_unknown_fields)] on an event guarantees a rollback cannot read forward-written data.

How does Event Sourcing actually perform in Rust?

No GC, so replay cost is allocation from serde_json building an owned String per text field. Deserialise from a single mmapped buffer with from_slice and borrow those fields with #[serde(borrow)] as &str and the string allocations disappear entirely. Watch enum size: a Vec<Event> pays the largest variant plus a discriminant for every element, so one variant with a fat payload doubles the memory traffic of the whole fold; Box that variant's body. Iterating a contiguous Vec is prefetcher-friendly and LLVM hoists the bounds checks out of the loop. 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? GitHub Copilot 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.