Prompt
How do I build a metrics store that can handle late events?
Latest observation
To build a metrics store that handles late events well, you need to design around one core fact: event time is not the same as arrival time.
A good late-event design usually has these pieces:
1) Separate event time from ingestion time
Every metric event should carry at least:
- event_timestamp: when the event actually happened
- ingest_timestamp: when your system received it
- dimensions/tags: service, region, user segment, etc.
- metric name / value
This lets you:
- place the event in the correct historical bucket
- detect how late it is
- decide whether to accept, correct, or discard it
2) Use an immutable raw event log as the source of truth
Don’t try to make the aggregated store your only source of truth.
A common pattern:
- Append raw events to durable storage first
- Kafka, Kinesis, Pulsar, S3, BigQuery, etc.
- Build aggregates from the raw stream
- Allow reprocessing when late events arrive
This gives you replayability and makes corrections possible.
3) Choose a lateness policy
You need a rule for how late is “too late.”
Typical options:
A. Hard cutoff
- Accept events only within a window, e.g. 24 hours
- Drop older events
Pros: simple
Cons: loses data
B. Soft cutoff with corrections
- Accept late events for a retention window, e.g. 7 days
- Update historical aggregates when they arrive
Pros: accurate
Cons: more complex
C. Unlimited lateness
- Always accept and recompute history
Pros: most correct
Cons: expensive and operationally harder
Most systems use bounded lateness.
4) Store aggregates in a merge-friendly form
If late events can arrive, your aggregates should be easy to update incrementally.
For example, for each:
- metric
- time bucket
- dimension set
store:
- count
- sum
- min
- max
- maybe sketch-based percentiles
If an event arrives late, you:
- find the bucket it belongs to
- add its contribution
- write back the updated aggregate
Important:
If you compute derived values like averages, don’t store only the average. Store the components:
sumcount
Then avg = sum / count.
5) Use time buckets with a watermark
A watermark is the system’s belief that data earlier than a certain time is mostly complete.
Example:
- current time: 12:00
- watermark: 11:50
That means:
- buckets before 11:50 are considered “final” or nearly final
- buckets after that may still change
You can:
- keep recent buckets mutable
- freeze older ones
- support corrections via special backfill jobs
6) Design for upserts or versioned writes
Late events often mean you need to modify previously written aggregates.
Two common patterns:
Upsert model
- read aggregate bucket
- modify it
- write it back
Works well if your storage supports atomic upserts.
Versioned / append-only delta model
- each late event becomes a delta record
- queries or a compactor apply deltas
- periodic compaction materializes final state
This is often safer at scale because it avoids write conflicts.
7) Make reprocessing cheap
Late events are easiest to handle if you can rebuild affected windows.
Typical approach:
- raw events are immutable
- aggregates are derived
- if late events arrive for a time range, re-run only that range
For example:
- a late event for 2026-10-24 10:03 affects the 10:00–10:05 bucket
- maybe also hourly and daily rollups
- recompute just those partitions
8) Support idempotency and deduplication
Late events often arrive alongside retries and duplicates.
Add:
- event_id or unique business key
- dedup store or bloom filter or idempotent consumer logic
Without this, your late-event correction logic can double count.
9) Handle multiple aggregation layers carefully
If you have minute, hour, and day rollups, late events can propagate upward.
Options:
- recompute from raw data for all impacted layers
- or cascade deltas upward from minute to hour to day
Recompute is simpler and more reliable; cascading is faster but more complex.
10) Expose freshness and completeness to users
Users need to know if a metric is still changing.
Good UI/API metadata:
is_finalwatermarklast_updated_atlate_event_windowdata_completeness_pct
This avoids confusion when dashboards shift.
A practical architecture
A solid pattern looks like this:
Ingest path
- Event arrives
- Validate schema
- Write raw event to log/storage
- Compute event-time bucket
- Update near-real-time aggregate
- Mark bucket as tentative if within lateness window
Correction path
- Late event arrives
- Determine affected bucket(s)
- If within allowed lateness:
- update bucket aggregate
- possibly trigger downstream rollup correction
- If beyond cutoff:
- route to dead-letter / audit / backfill review
Query path
- Read aggregated buckets
- Prefer finalized data for older time ranges
- Use latest tentative data for recent ranges
Storage choices
Depending on scale, these are common:
- Kafka + Flink / Spark Structured Streaming + OLAP store
- ClickHouse with Replacing/Collapsing engines or upserts via materialized views
- Druid / Pinot for analytics-style metrics
- BigQuery / Snowflake for batch or hybrid systems
- Postgres for smaller scale, with partitioned tables and upserts
- FoundationDB / Cassandra / RocksDB-based state stores for streaming aggregation state
Common pitfalls
- Storing only final averages instead of sums/counts
- Not keeping raw events
- Not deduplicating retries
- Freezing buckets too early
- Recomputing too much data on every late event
- Ignoring query-time freshness metadata
- Mixing processing time and event time
Rule of thumb
If you expect late events, design your metrics store as:
- event-time aware
- append-only at the raw layer
- incrementally correctable at the aggregate layer
- bounded by a lateness window
- transparent about freshness
If you want, I can also give you:
- a schema design for such a store,
- a streaming architecture using Kafka/Flink/ClickHouse,
- or a Postgres-only implementation for smaller scale.