Prompt
How do I build an event-driven architecture with replay and backfills?
Latest observation
Building an event-driven architecture that supports replay and backfills means designing your system so events are:
- Durably stored
- Orderable and versioned
- Consumable independently by multiple readers
- Reprocessable from history without breaking state
Here’s a practical blueprint.
1) Start with the right core model
Use events as the source of truth for important domain changes.
Examples:
UserCreatedOrderPlacedPaymentCapturedAddressChanged
Each event should be:
- Immutable
- Timestamped
- Attributed to a versioned schema
- Assigned a unique ID
- Associated with an aggregate/entity ID
- Stored durably before being published or consumed
2) Separate the three concerns
A. Event production
Your app emits events when business state changes.
B. Event storage
Events go to a durable log or event store:
- Kafka / Pulsar / Redpanda
- EventStoreDB
- Database-backed outbox + stream
- Cloud pub/sub with retention
C. Event consumption
Consumers build:
- projections/materialized views
- downstream integrations
- analytics pipelines
- caches
- notifications
This separation is what makes replay possible.
3) Choose a storage model that supports replay
Best option: append-only log
Use a log with retention long enough for your replay/backfill needs.
Examples:
- Kafka with partitions and retention
- Pulsar
- EventStoreDB
Key properties:
- Messages are append-only
- Consumers track offsets independently
- You can re-read from any offset if data is retained
If using a relational DB
Use the outbox pattern:
- Write business state + outbox event in one transaction
- A relay publishes outbox records to the broker
- Keep outbox history for replay/backfill if needed
4) Design events for future replay
Replay fails when events are too “presentation-oriented” or lack context.
Include:
event_idevent_typeevent_versionaggregate_idoccurred_atproducercorrelation_idcausation_id- domain payload
- optional metadata like tenant, source, schema hash
Example:
{
"event_id": "evt_123",
"event_type": "OrderPlaced",
"event_version": 2,
"aggregate_id": "order_456",
"occurred_at": "2026-10-24T12:00:00Z",
"correlation_id": "req_789",
"causation_id": "evt_122",
"payload": {
"customer_id": "cust_1",
"items": [{"sku": "ABC", "qty": 2}],
"currency": "USD",
"total": 4999
}
}
5) Use idempotent consumers
Replay and backfills will re-deliver events. Consumers must handle duplicates safely.
Common techniques:
- Store processed
event_ids - Use upserts instead of inserts
- Make side effects idempotent
- Use version checks on aggregates
- Deduplicate by
(event_id)or(aggregate_id, version)
If a consumer can’t safely process the same event twice, replay becomes dangerous.
6) Build projections as rebuildable
Most replay use cases are for projections:
- read models
- search indexes
- dashboards
- analytics tables
Design them so they can be deleted and rebuilt from events.
Pattern:
- Drop or version the projection table
- Re-read historical events
- Recompute state
- Swap over atomically if needed
Avoid treating projections as canonical source of truth.
7) Support replay explicitly
You need a mechanism to reprocess history.
Replay modes
- Full replay: from the beginning of retained history
- Partial replay: from a specific time/offset/event ID
- Targeted replay: only for a tenant, entity, or event type
Implementation options
- Kafka consumer reset to earlier offset
- Separate “replay consumer group”
- Rebuild job that scans event store
- Export events to batch processing tool for historical rebuilds
Important
Replay should usually go to:
- a new projection version, or
- a shadow environment
Don’t blindly replay into live production state unless consumers are explicitly designed for it.
8) Design for backfills as first-class jobs
A backfill is usually different from replay:
- replay = reprocess old events already in the system
- backfill = generate or ingest missing historical events/data
Examples:
- You added a new field to projections
- You onboarded historical records from a legacy system
- You discovered a gap for a time window
Backfill strategies
A. Recompute from original source
Best when you have the authoritative source.
- Fetch historic rows/orders/payments
- Convert them into events or projection updates
- Run as a batch job
B. Synthesize events
If historical domain events never existed, create carefully versioned “import” events:
HistoricalOrderImportedLegacyUserMigrated
Treat them differently from real-time events.
C. Dual-write historical seed + live stream
Seed initial state, then continue with live events from a checkpoint.
9) Use versioning everywhere
Replays break when schemas change.
Event schema versioning
- Add new fields as optional
- Never remove or rename fields without compatibility plan
- Support multiple event versions in consumers if needed
Consumer/projection versioning
When logic changes, create a new version:
orders_read_model_v1orders_read_model_v2
Run both if necessary until cutover is complete.
Migration rule
Prefer:
- additive changes
- new consumers
- new projections over in-place destructive changes
10) Handle ordering carefully
Replay/backfills often fail because of ordering assumptions.
Common rule
Order only matters within a partition / aggregate, not globally.
Ways to manage:
- Partition by
aggregate_idortenant_id - Include
sequence_numberper aggregate - Ignore out-of-order events if the version is older than current state
- Buffer if strict order is required
If you need global ordering, expect scalability tradeoffs.
11) Make side effects separate from state rebuilds
Notifications, emails, webhooks, and payments should not be blindly re-triggered during replay.
Split consumers into:
- state projection consumers: safe to rebuild
- side-effect consumers: carefully deduplicated or replay-disabled
For side effects:
- keep a “sent” ledger
- distinguish live processing from replay mode
- use event metadata to suppress historical re-execution
12) Add checkpoints and auditability
Track:
- last processed offset/event ID
- replay job ID
- source range
- processed count
- failures/retries
- schema version used
- checksum or watermark
This helps answer:
- “Did we rebuild everything?”
- “What changed after the backfill?”
- “Can we resume safely after a crash?”
13) Operational patterns that work well
Pattern: live stream + shadow rebuild
- Keep production running
- Rebuild a new projection in parallel
- Validate counts/checksums
- Switch traffic to the new projection
Pattern: checkpointed batch backfill
- Process historical data in chunks
- Commit checkpoint after each chunk
- Resume from checkpoint if interrupted
Pattern: blue/green consumer deployment
- Deploy new consumer version
- Run it alongside old version
- Compare outputs
- Cut over when correct
14) A simple reference architecture
App/Service
-> writes domain state
-> writes event to outbox/event store
-> publisher streams to broker (Kafka/Pulsar)
-> Consumer A: read model projection
-> Consumer B: search index
-> Consumer C: notifications
-> Consumer D: analytics
For replay/backfill:
Event store / broker retention
-> replay job reads historical range
-> writes to new projection version
-> validates
-> cutover
15) Practical rules of thumb
- Use events as immutable facts, not commands
- Store enough metadata for traceability
- Make all consumers idempotent
- Keep projections rebuildable
- Version schemas and projections
- Separate side effects from state rebuilds
- Treat backfills as batch jobs with checkpoints
- Test replay in staging with production-like data
- Document the exact replay procedure before you need it
16) Common mistakes to avoid
- Relying on ephemeral queue retention only
- Using events that are too coarse or too UI-specific
- Letting projections become the source of truth
- Re-triggering emails/webhooks during replay
- Not versioning schemas
- Assuming total ordering across the whole system
- Replaying directly into live side-effect handlers
- Ignoring duplicate delivery
17) If you’re starting from scratch, a good minimal stack is
- Kafka for durable event log
- Transactional outbox in your primary DB
- Consumer services that build projections
- Idempotency table for dedupe
- New projection version for every major rebuild
- Backfill jobs that read from source-of-truth data and write through the same event pipeline or projection contract
If you want, I can also give you:
- a concrete implementation in Kafka + Postgres,
- a schema design for replay-safe events, or
- a step-by-step backfill/replay runbook.