ADR-0007 — Azure Cosmos DB (NoSQL API) as the event store technology
Forces / Drivers
- Requirement / Constraint:
../context/requirements.md#fr-2-event-store— FR-2 Event store: append-only, immutable, versioned, stream-based, ordered, archivable.../context/requirements.md#nfr-1-scalability— NFR-1 Scalability: horizontal, per-tenant partitioning; the reference envelope produces approximately 400 domain events/sec at sustained 5× peak, while the event-sourcing stress envelope reaches approximately 1,157 domain events/sec before subscriber or persistence amplification.../context/requirements.md#nfr-2-reliability— NFR-2 Reliability: SLO 99.9 %, RTO 1 h, RPO 0.../context/requirements.md#nfr-4-latency— NFR-4 Latency: incident freshness < 30 s (write-path + change-feed fan-out must fit).../context/constraints.md#bc-1-data-residency-switzerland— BC-1 Data residency: Switzerland North / West only.../context/constraints.md#bc-3-compliance-and-regulatory— BC-3 Per-customer data segregation + deletion on off-boarding.../context/capacity-model.md#derived-processing-load— At 1000-cust plan: ~208M domain events/month; ~2 KB per event; per-second write floor + read amplification for stream reconstruction on command path.../context/quality-goals.md— Cost as design constraint (§ 19); ~250 CHF/env idle ceiling for cross-cutting infra.- § 21 Azure-native managed services first — the load-bearing reason self-hosted event stores (EventStoreDB) are rejected on principle before feature comparison.
- Principle(s) embodied:
§ 8 Event Sourcing,§ 14 Independent scalability,§ 18 Data residency & compliance,§ 19 Cost as design constraint,§ 21 Azure-native managed services first. - WAF pillar optimized:
performance-efficiency(primary);reliability,cost-optimization,operational-excellence(secondary).
Context
ADR-0006 committed the platform to Event Sourcing as the persistence pattern for domain aggregates whose history is a first-class concern (Incident, Ticket, Investigation). That decision is deliberately technology-agnostic. The question this ADR answers is which Azure-native store realises the pattern, given the feature checklist an event store must satisfy:
- Append-only, atomic write of one or more events per stream — the command-handler transactional pattern from
../references/Event Sourcing- Design.mdreads the stream, reconstructs state, appends new event(s), and commits — all inside one transactional boundary keyed by the stream. - Optimistic concurrency on the stream — sequence-number-based, no distributed locks.
- Domain-aggregate read — read all events for
<AggregateType>-<AggregateId>in order, on the command path (single-digit ms budget shared with reconstruction + business-rule execution). - Change-feed / subscription primitive — every committed event must be available to downstream projectors in near-real-time, without a co-committed dual write into a broker (this is the dual-write problem ADR-0006 exists to dissolve at the aggregate boundary — see
../references/Design Pattern- Handling Dual Writes.md). - Per-tenant partitioning — stream ID prefixed by
customer-short/tenant/{aggregateId}so writes, reads, and deletion scope to a customer for BC-1/BC-3. - Retention + archival — hot 6 mo, cold 1 yr, deletion on off-boarding.
- Zone-redundant with PITR to satisfy RPO 0 — see
../references/Event Sourcing- Event Store Disaster Recovery.md. - Managed Identity access + private-endpoint — no connection strings, no public network (§ 12, NFR-3).
- Regional availability in Switzerland North — BC-1.
- Cost profile compatible with § 19 — consumption or autoscale, not fixed high-tier.
Three candidate technology families exist for this shape: a NoSQL document store with per-partition transactions (Cosmos DB NoSQL API); a relational store with per-row transactions (Azure SQL, PostgreSQL Flexible Server); a purpose-built event-log broker or event-sourcing DB (Kafka, EventStoreDB). The V3 references already document a feature-by-feature analysis in ../references/Event Sourcing- Event Store.md; this ADR captures the decision, not the analysis.
Cost sanity from the same reference (at ~100 GB, ~2 KB row, ~100 ops/sec across read/write): Cosmos DB ~150 USD/month; PostgreSQL Flexible ~230 USD/month — with Postgres compute-fixed and Cosmos consumption-based (so Cosmos scales down harder in non-prd environments — matters for the § 19 idle-cost ceiling).
Decision
V3 adopts Azure Cosmos DB (NoSQL API) as the event store technology for every event-sourced aggregate in scope of ADR-0006 (Incident, Ticket, Investigation, and any future aggregate passing ADR-0006’s adoption test). Concretely:
- API: Cosmos DB NoSQL API (formerly SQL API). Not Mongo API, not Cassandra API, not Gremlin API.
- Account topology: one Cosmos DB account per event-sourced aggregate boundary (Incidents, Tickets, Investigation), not one shared account. Rationale: independent scaling per aggregate; blast-radius isolation on outage; per-account DR posture; independent cost attribution. This aligns with ADR-0002 volatility containment — an aggregate’s store is inside its owning system.
- Region: Switzerland North primary (BC-1). No cross-region replication for the store (ION’s DR posture is in-region zone-redundant — see planned DR ADR).
- Zone redundancy: enabled on every environment’s Cosmos account. Individual node + zone outage → RTO 0, RPO 0 per Azure SLA.
- Continuous backup: enabled (7-day tier for non-prd; 30-day tier for prd). Point-in-Time Restore is the RPO-0 mechanism for logical-corruption / accidental-delete scenarios; zone redundancy handles infrastructure outage.
- Partition-key scheme:
stream_id=<AggregateType>-<AggregateId>— e.g.SecurityIncident-{incidentId}. This makes the aggregate stream the write-consistency unit. Every write batch is a transactional batch (Cosmos NoSQL transactional batch) scoped to a single logical partition, which gives atomicity + read-your-writes within the batch. - Consistency level: Session consistency (Cosmos default). Command handlers own the session token for the stream they write — read-your-writes on the write path is guaranteed. Change-feed consumers get session consistency across the account.
- Optimistic concurrency: enforced via a
sequence_idfield per event, monotonically increasing per stream. Unique key on(stream_type, stream_id, sequence_id). A concurrent writer trying to appendsequence_id = Nwhen N already exists gets a 409 Conflict; the handler retries after re-reading. - Idempotency: duplicate event submission is prevented by the same
(stream_type, stream_id, sequence_id)unique key. Commands are idempotent by carrying acommand_iddeduplicated at the command-queue layer (see../references/Design Pattern- Idempotent Write.md). - Change feed: Cosmos Change Feed is the subscription primitive. A change-feed processor projects events into (a) an integration adapter that publishes to the event backbone (shared Service Bus — ADR-0008), and (b) local projectors into operational and reporting stores. No co-committed broker write; the change feed is the transactional outbox.
- Retention + archival: Cosmos TTL per document, plus Change-Feed-to-Blob for cold storage. Hot 6 mo (queryable at Cosmos latency), cold 1 yr (in Blob, replay-capable via re-hydration). Per-customer deletion on off-boarding is a scoped query-and-delete across the stream ID prefix (BC-3).
- Throughput mode: autoscale on RU/s per container. Reserved capacity + autoscale gives cost predictability at the § 19 ceiling with headroom for peak (D7 = 5× sustained).
- Access: Managed Identity only (§ 12). Cosmos data plane RBAC via Entra ID role assignments; connection strings + primary keys disabled at the account level. Private endpoints only — public network access disabled.
- Snapshotting: deliberately deferred. V3 reference notes streams typically stay < 100 events per aggregate (a security incident’s lifecycle is short); reconstruction cost is bounded; snapshots would add complexity without clear payoff. Re-evaluated per aggregate if a stream regularly exceeds ~200 events.
Alternatives considered
-
Option A — Azure SQL Database (or PostgreSQL Flexible Server) with transactional appends. Rejected primarily on three grounds: (i) subscription primitive — CDC exists but it captures row changes with schema coupling, not domain events; wiring CDC-to-broker introduces the exact dual-write / outbox complexity ADR-0006 exists to remove at the aggregate boundary (Cosmos change feed sidesteps this cleanly). (ii) Schema rigidity — event payloads evolve per ADR-0005’s schema-evolution rules; a relational schema either forces payloads into a JSON column (giving up most SQL benefits) or requires migrations per event-type change (defeating additive-only evolution). (iii) Cost profile mismatch with § 19 — Postgres Flexible has a fixed ~190 USD/month compute floor; a Cosmos serverless / autoscale account can scale down to near-zero in idle non-prd environments. Retained as a comparison point in
../references/Event Sourcing- Event Store.md; may re-enter consideration for aggregates with strong relational query needs on the operational projection, which is a different store. -
Option B — EventStoreDB (or another purpose-built event-sourcing engine) self-hosted. Rejected — first-class rejection under § 21 Azure-native managed services first: EventStoreDB has no Azure PaaS offering, so adopting it means ION runs, patches, backs up, monitors, and DR-drills a stateful cluster forever. The V3 platform accepts one such self-hosted exception (Temporal in Cogs, where no Azure-managed equivalent covers the required workflow-execution semantics); adopting a second would double the operational surface for a pattern-level feature set (append, optimistic concurrency, change feed) that managed Cosmos already delivers via a shared events-library. The trade-off fails the § 21 test: the feature gap is not large enough to justify permanent operations ownership.
-
Option C — Kafka (Confluent or Azure Event Hubs Kafka-compatible) as the event log itself. Rejected as store: (i) retention ceilings — Event Hubs Premium tops out at 90-day retention on the tier ION uses; the 6-month hot / 1-year cold requirement (D10) does not fit; (ii) aggregate-read latency — reading all events for stream X in order, from a partitioned log, on the command path (single-digit ms budget) is not what a log broker is optimised for; log brokers are optimised for high-throughput sequential scan, not point aggregate reconstruction; (iii) optimistic concurrency on a stream requires bolt-on discipline (transactional producers + compacted key semantics) that is fragile compared to Cosmos’s per-partition transactional batch. Event Hubs is not part of the V3 internal event backbone either — see ADR-0008.
-
Option D — Cosmos DB Mongo API. Rejected. The transactional batch primitive that makes Cosmos-NoSQL suitable as an event store is a NoSQL-API feature; Mongo-API semantics differ, and V3 gains nothing from wire-compatibility with MongoDB. Would also fragment the SDK story unnecessarily.
-
Option E — Azure Table Storage / Blob append blobs. Rejected. Table Storage lacks transactional-batch semantics at the partition level suitable for the read-reconstruct-append pattern; append blobs give append-only durability but no query surface, no change feed with subscription semantics, and no per-record TTL. Blob is the right choice for the cold tier only.
-
Option F — Shared Cosmos DB account across all event stores. Rejected. Would collapse per-aggregate throughput isolation, blast-radius isolation, and cost attribution. The saving (one account vs three) is marginal compared to the coupling introduced.
Rationale
Cosmos DB (NoSQL) is the only Azure-managed option that lands cleanly on all four load-bearing features of an event store simultaneously:
- Transactional atomic append with optimistic concurrency, at aggregate granularity. Transactional batch scoped to a logical partition (= stream) gives the read-then-append pattern in one commit, with sequence-number uniqueness enforcing OCC. No relational locking, no lease coordination.
- Native change-feed primitive with subscription semantics. The change feed is the transactional outbox — every committed write is emitted exactly once (with at-least-once processor semantics on the consumer side, mitigated by idempotency). This dissolves the dual-write problem at the store level, not in application code.
- Elastic per-partition throughput with autoscale. Per-tenant partition-key scheme + autoscale RU/s gives natural horizontal scaling that matches the tenant-partitioned load profile (some tenants noisy, most quiet).
- Zone-redundant + PITR out of the box. Matches NFR-2 (RPO 0, RTO 1 h) with no application-level work beyond enabling the features.
On top of those, the operational case is decisive:
- Managed service. No cluster to run, patch, scale, or DR-drill at the infrastructure layer. Fits ION’s “one platform team runs many services” model.
- Cost scales down. Autoscale + serverless-eligible workloads mean non-prd environments idle cheap — a hard § 19 requirement (250 CHF/env idle floor is not per-store, but every store consuming a fixed floor makes the ceiling harder to hit).
- SDK maturity across ION’s stacks. First-class SDKs for TypeScript, Python, C# with async APIs and transactional-batch support. The change-feed processor library has a mature .NET flavour + an Azure-Functions Cosmos trigger for hosted projectors.
- Managed Identity + private endpoint story is complete. No connection-string workarounds; no public-network compromise.
The chief trade-offs — RU/s cost modelling, indexing-policy tuning to avoid write-RU inflation, and cross-partition query cost — are real, but they are operational tuning problems inside a well-understood service, not architectural risks. They are documented in Capacity, sizing, and scaling and Cost optimization.
Consequences
Positive
- Dual-write dissolved at the store level. Change feed replaces application-level outbox. One commit = one durable event = one downstream fan-out signal.
- RPO 0 achievable within a single region. Zone-redundant Cosmos + PITR meet NFR-2 without cross-region complexity (BC-1 compatible).
- Per-aggregate horizontal scale. Autoscale RU/s per container; noisy tenants do not throttle quiet ones (partition-scoped throughput).
- Managed-service operational profile. Backup, patching, replication, DR primitives are Azure’s responsibility.
- Idle cost is low. Autoscale + serverless-eligible containers make non-prd Cosmos cheap; supports the § 19 idle-cost ceiling.
- Per-customer deletion is a scoped operation. Stream-ID prefix carries customer scope; off-boarding = delete-by-partition-key-prefix, no cross-cutting migration.
- Change-feed processor is a first-class projection substrate. Every projection (reporting, operational store, external integration) is a change-feed consumer with checkpointing.
Negative
- RU/s cost modelling is a real ongoing skill. Write RUs depend on document size, indexing policy, and consistency level; queries can silently be cross-partition and expensive. Requires monitoring + query-cost budgets per container. See
../references/Architecture- Service Limits.md. - Indexing policy must be tuned. Default Cosmos indexing indexes every field; on 2 KB events at 208M/month this inflates write RU and storage. V3 mandates a custom indexing policy per container — index only what projections + audit queries need.
- Cross-partition queries are expensive. Audit-log queries “all events by user X across streams” are cross-partition by design; these belong on a projection, not on the event store directly.
- RU/s is a shared budget across containers in an account. Requires per-container throughput allocation discipline; misconfiguration = noisy-neighbour on the same account. Mitigated by per-aggregate account topology (one account per aggregate) and per-container autoscale ceilings.
- Change-feed lag under sustained peak. Change-feed processor scales with number of physical partitions; at D7 5× peak, projection freshness may degrade briefly. Freshness SLOs (incident < 30 s) must include change-feed lag in their error budget.
- Storage growth is monotonic (already flagged in ADR-0006). Cosmos storage at ~416 GB/month growth at 1000-cust plan requires disciplined TTL + Blob archival to keep hot-tier cost bounded.
- Vendor lock-in exposure. Cosmos NoSQL API is not portable to another provider. Mitigated by keeping the event schema (CloudEvents + AsyncAPI — ADR-0005) portable, and by isolating Cosmos SDK usage behind a shared event-store client library — the code that would need to change on migration is finite and centralised.
Neutral / follow-ups
- Custom indexing policy standard. Codified in
standards/— index only fields used by change-feed processors, projection queries, and audit-log queries. - RU/s budget + cost dashboard per container.
well-architected/cost-optimization/— per-container RU budgeting and alerting. - Event-store client library. Shared library encapsulating: transactional-batch append, sequence-number OCC + retry, idempotent-write helper, change-feed consumer with checkpoint. Prevents per-service reinvention.
- Snapshotting revisit trigger. If any stream regularly exceeds ~200 events, evaluate snapshotting for that aggregate.
- PITR runbook. DR runbook already drafted in
../references/Event Sourcing- Event Store Disaster Recovery.md— freeze commands → PITR → identify recovery-point event → replay to projections → cutover. To be codified underwell-architected/reliability/event-store-dr/. - Blob archival binding. Change-feed → Blob storage projector for cold tier — a shared component, one per aggregate.
WAF Pillar Impact
- Primary pillar:
performance-efficiency— per-partition transactional-batch append at aggregate granularity, autoscale RU/s per container, session-consistent read-your-writes on the write path, elastic per-tenant partition throughput. Matches the ingest-firehose + per-aggregate command shape of the ION workload. - Secondary pillars:
reliability— zone-redundant + PITR + change-feed-as-outbox delivers NFR-2 (RPO 0, RTO 1 h) with no application-level dual-write reconciliation.cost-optimization— autoscale + serverless-eligible workloads keep idle non-prd cost low, supporting the § 19 ceiling; usage-based pricing scales with tenant load rather than provisioned peak.operational-excellence— managed service; DR / backup / replication are Azure’s responsibility; SDK + change-feed processor + Functions trigger reduce boilerplate per projection.security— Entra ID data-plane RBAC + Managed Identity + private endpoints + Switzerland region satisfy § 12 and BC-1.
- Trade-offs:
- Sacrifices SQL query surface for schema flexibility + per-partition scale. Ad-hoc analytical queries belong on projections, not on the event store.
- Sacrifices multi-provider portability for managed-service leverage. Mitigated by CloudEvents/AsyncAPI schema portability + shared client library isolation.
- Sacrifices simplicity of a single shared account for per-aggregate blast-radius isolation.
- Requires ongoing RU/s + indexing tuning as workload evolves — this is a persistent operational responsibility, not a one-time setup.
Previous approach (V2)
V2 stored aggregate state in per-bounded-context operational databases (Azure SQL, Table Storage) with history — where kept — in bolted-on audit-log tables or Log Analytics workspace queries. There was no dedicated event store, because there was no Event Sourcing (V2 used the CRUD posture described in ADR-0006’s V2 section). Concretely: incident state lived in Sentinel (the SoR) plus a lightweight operational cache in ION; ticket state lived in ServiceNow; ION owned little authoritative state of its own.
The V3 change is compound: ADR-0006 introduces Event Sourcing as a pattern, and ADR-0007 chooses Cosmos DB (NoSQL) as the store to realise it. Neither store nor pattern existed at the aggregate boundary in V2. This ADR therefore does not supersede a V2 technology choice — it fills a slot V2 did not have.
Amendments
- 2026-10-15 — Reliability objectives pointer. The RTO 1 h and RPO 0 cited in this ADR are design objectives for the planned warm spare, not current guarantees. Zone redundancy and continuous backup are in place; current objectives are stated per scenario in the ADR-0017 amendment “Reliability objectives clarified”.
References
../references/Event Sourcing- Event Store.md— feature-by-feature comparison Cosmos vs SQL/Postgres; the analytical foundation for this ADR.../references/Event Sourcing- Event Store Disaster Recovery.md— DR posture using zone redundancy + PITR + Service-Bus command re-queueing.../references/ION v3- Incidents Event Store.md,../references/ION v3- Tickets Event Store.md,../references/ION v3- Investigation Event Store.md— per-aggregate event-store designs.../references/Incident Bounded Context- Design.md— Cosmos partition-key + transactional-batch design for the Incident aggregate; the reference implementation.../references/Design Pattern- Idempotent Write.md,../references/Design Pattern- Handling Dual Writes.md— patterns this decision enables at the store level.../references/Architecture- Service Limits.md— Cosmos-specific limits and quotas.- External: Cosmos DB — transactional batch — the primitive underpinning atomic stream appends.
- External: Cosmos DB — change feed — the subscription primitive replacing the transactional outbox.
- External: Cosmos DB reliability (zone redundancy + PITR) — the RPO 0 / RTO 0 posture for in-region resilience.
- External: Cosmos DB — consistency levels — session consistency semantics.
Related ADRs
- Depends on:
- Enables:
- ADR-0008 — Event backbone (shared Service Bus): change feed → broker binding.
- Pending: Event Store DR strategy (formalises the runbook in
../references/Event Sourcing- Event Store Disaster Recovery.md). - Pending: Reporting data store choice (a Cosmos change-feed projector is one candidate downstream).
- Related: