Event Sourcing Implementation in Python
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 Python as in every other language.
- ✓functools.reduce is the fold and dataclasses is the event: from dataclasses import dataclass with frozen=True, slots=True gives immutability, structural equality and no per-instance __dict__.
- ✓Reviewers insist apply is pure: signature (state, event) -> state, no I/O, no datetime.now, no random inside it, because replay must be deterministic five years from now.
- ✓The Python trap: Pickle looks like free serialisation and is the classic way to lose a log. A pickle stores the fully qualified module path, so moving events.py into domain/events.py or renaming the class breaks every historical event with ModuleNotFoundError or AttributeError, and no type checker or test on new events will notice.
- ✓The fold is interpreter-bound at roughly microseconds per event, and constructing one object per event dominates, not json.loads which is C.
What Event Sourcing actually is
Event Sourcing in Python: what you actually reach for
Python implementation
import functools, json, sqlite3
from dataclasses import dataclass
class ConcurrencyError(Exception): pass
@dataclass(frozen=True, slots=True) # slots: no per-event __dict__ over millions of rows
class Deposited: cents: int; at: str
@dataclass(frozen=True, slots=True)
class Withdrawn: cents: int; at: str
TAGS = {"deposited": Deposited, "withdrawn": Withdrawn}
def apply(balance: int, e) -> int:
match e:
case Deposited(cents=c): return balance + c
case Withdrawn(cents=c): return balance - c
case _: raise ValueError(f"unknown event {type(e).__name__}")
def append(db, stream, expected_version, tag, payload):
# UNIQUE(stream_id, version) IS the optimistic concurrency check
try:
db.execute("INSERT INTO events(stream_id,version,tag,data) VALUES(?,?,?,?)",
(stream, expected_version + 1, tag, json.dumps(payload)))
except sqlite3.IntegrityError as exc:
raise ConcurrencyError(stream, expected_version) from exc
def replay(db, stream, state=0, since=0):
rows = db.execute("SELECT tag,data FROM events WHERE stream_id=? AND version>?"
" ORDER BY version", (stream, since))
return functools.reduce(apply, (TAGS[t](**json.loads(d)) for t, d in rows), state)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 Python-specific trap
Performance in Python, beyond the O(1) append
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Event Sourcing?
functools.reduce is the fold and dataclasses is the event: from dataclasses import dataclass with frozen=True, slots=True gives immutability, structural equality and no per-instance __dict__. json handles the wire; sqlite3 is a perfectly serious single-node log, with UNIQUE(stream_id, version) doing the optimistic concurrency check and raising sqlite3.IntegrityError. There is no stdlib json-to-dataclass path (dataclasses.asdict is one-way), so the ecosystem standard is pydantic v2: a Literal tag field plus a discriminated union gives you validated decoding and per-field upcast validators in one place.
What is the most common Python mistake when implementing Event Sourcing?
Pickle looks like free serialisation and is the classic way to lose a log. A pickle stores the fully qualified module path, so moving events.py into domain/events.py or renaming the class breaks every historical event with ModuleNotFoundError or AttributeError, and no type checker or test on new events will notice. The other one is time: datetime.datetime.utcnow() returns a naive datetime and is deprecated since 3.12 in favour of datetime.now(datetime.UTC); naive timestamps round-trip through JSON without their offset, so events written by a UTC box and a local box interleave in the wrong order forever once you sort by timestamp instead of by version.
How does Event Sourcing actually perform in Python?
The fold is interpreter-bound at roughly microseconds per event, and constructing one object per event dominates, not json.loads which is C. slots=True removes the per-instance dict and cuts both memory and attribute-access cost measurably over millions of events. The real trick is the cyclic collector: every surviving event object gets promoted, so a bulk replay triggers repeated gen-2 collections. gc.disable() around the replay and gc.freeze() after loading a snapshot are the standard levers. The GIL means threads will not parallelise the fold; shard by stream across processes. Time complexity is O(1) append 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 trialStudying for this? GitHub Copilot free tiers and academic plans are laid out 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.