---
name: event-sourcing
description: Use for event sourcing, event streams, event-sourced aggregates, business intent events, projections, replay, snapshots, optimistic stream concurrency, event schema evolution, and deciding whether event sourcing fits.
title: event-sourcing
canonical_url: https://skilld.dev/gh/eralmansouri/skills/event-sourcing
last_updated: 2026-09-28T13:40:03.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> If the user asked to install this Skill, run `npx skilld install eralmansouri/skills/event-sourcing`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/event-sourcing`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/eralmansouri/skills/event-sourcing) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/event-sourcing`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/event-sourcing --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/event-sourcing --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Event Sourcing

Use ordered, immutable business facts as the source of truth only when history,
intent, temporal reconstruction, auditability, or future reinterpretation has
enough value to repay permanent schema and operational costs.

## Qualify The Use Case

- Does the business care how and why state reached its current value?
- Are transitions meaningful domain facts rather than generic property changes?
- Is temporal reconstruction or first-class audit valuable?
- Do commands depend on prior state and enforce meaningful invariants?
- Does the process have a coherent lifecycle and stream boundary?
- Can the team own replay compatibility, projections, concurrency, and lag?
- Can event sourcing remain local to the capability that needs it?

Prefer current-state persistence for form-centric CRUD, generic created/updated/
deleted streams, defensive logs that will not be interpreted, or proposals
driven only by scale, Kafka, CQRS, DDD, EDA, or microservices.

## Concept Separation

- CQRS separates command and query code paths.
- Event sourcing persists ordered facts instead of only current state.
- DDD models language, rules, workflows, and boundaries.
- EDA coordinates reactions through messages.
- Microservices apply independent deployment topology to logical capability boundaries.

These patterns often compose but imply none of one another.

## Modeling Workflow

1. Select one business capability.
2. Map its workflow, decisions, invariants, lifecycle, and checkpoints.
3. Design task-oriented commands that capture intent.
4. Name events as past-tense business facts with enough data and metadata to replay and explain the transition.
5. Choose stream identity by consistency unit and lifecycle, not entity habit alone.
6. Load events, replay state, invoke behavior, record new events, and append with the expected version.
7. Design caller-specific projections and choose inline, live, or asynchronous consistency.
8. Separate private source events from stable integration contracts.
9. Test replay, decisions, projections, concurrency, and historical event versions.
10. Add snapshots only after measuring replay cost and revisiting stream design.

## Write Path And Aggregate Rules

1. Read the stream and retain its version.
2. Apply historical events without marking them uncommitted.
3. Invoke a command against reconstructed state.
4. Reject invalid behavior without producing events.
5. Apply and record each new event immediately.
6. Append only if the expected stream version still matches.
7. Publish integration events through an explicit reliable boundary.

- Use an event-sourced aggregate as a write-side decision model.
- Derive only the state required for future decisions.
- Persist uncommitted events, not a current-state object graph.
- Enforce immediate invariants from aggregate state, not a lagging projection.
- Retry version conflicts only when repeating the command is semantically safe.

## Projection Timing

| Mode | Use when | Tradeoff |
| --- | --- | --- |
| Inline | Event and read state must commit together | Higher write latency and coupling |
| Live/on-demand | Historical or occasional calculation | Replay cost at query time |
| Asynchronous | Independent scaling or expensive aggregation | Lag, idempotency, rebuild, and UX complexity |

Build narrow models for screens, reports, totals, and lookup needs. Maintain
ordinary query models incrementally, track checkpoints, make at-least-once
projectors idempotent, and expose asynchronous lag honestly. Prefer
single-stream projections where practical and asynchronous cross-stream
aggregation when it avoids contention.

## Snapshots And Stream Boundaries

First look for natural lifecycle boundaries such as accounting periods, stock
counts, closure, or driver-day assignments. Starting a new stream at a domain
checkpoint is modeling; a snapshot is merely a replay optimization.

If measured replay remains expensive, persist aggregate state at a stream
version and replay subsequent events. Keep original events authoritative and
budget for snapshot schema evolution.

## Evolution And Testing

- Prefer additive optional fields for shared and external contracts, then verify serializer and consumer compatibility.
- Upcast old events when current code requires a newer in-memory shape.
- Create a new event type when semantics change materially.
- Do not append both old and replacement events for one fact in the source stream.
- Ensure old and new application versions can read events written during rolling deployment.
- Rebuild projections when their logic changes.
- For fundamental changes, migrate side by side and catch up before switching writes.
- Given historical events, when a command executes, assert new events or rejection.
- Test each event application and verify full replay equals incremental projection results.
- Keep fixtures for historical event versions and test stale expected versions.

## Operations

- Monitor stream and projection position, lag, queue length, throughput, and processing time.
- Detect poison events and provide explicit repair or skip procedures.
- Make asynchronous projectors idempotent and ordered within a stream.
- Maintain replay and zero-downtime projection rebuild procedures.
- Surface projection freshness in user flows that depend on it.
- Record version, order, timestamp, correlation, and causation metadata.
- Test representative production events against new deployments.
- Perform a separate security and privacy review for immutable history, backup, recovery, retention, deletion, replay, and sensitive fields.

## Avoid

- CRUD sourcing and property-change events without business meaning.
- Applying event sourcing to every table or service.
- Infinite streams caused by missing lifecycle boundaries.
- Snapshots used to conceal bad stream design.
- Querying raw streams for routine UI needs.
- Treating private event-store records as public integration APIs.
- Retrying every optimistic-concurrency conflict automatically.
- Ignoring projection duplicates, poison events, lag, and rebuild time.
