Design an Immutable Multi-Tenant Audit Log System
System DesignModel answerLast updated
Design a compliance audit logging platform that ingests events at scale, proves tamper-evidence cryptographically, detects sequence gaps, and serves fast investigation queries.
Context
A legal-tech platform serves thousands of corporate and government customers across a suite of independently deployed microservices — contract execution, document search, litigation holds, permission management, and more. Regulators and enterprise compliance officers require a complete, tamper-proof record of every user, API, and system action.
You are asked to design a centralized audit log platform. It must reliably accept events from all upstream services, store them immutably with cryptographic integrity guarantees, detect any missing records automatically, and answer investigator queries quickly.
Functional Requirements
- Canonical ingestion: Accept structured audit events from heterogeneous services. Validate against a schema, enforce tenant isolation, and handle client-side retries without creating duplicate records.
- Tamper evidence and immutability: Guarantee that no internal operator or compromised service credential can silently alter or delete records. A third-party auditor must be able to independently verify ledger integrity.
- Gap detection and replay: Automatically identify missing sequences or silent delivery failures from producer services and coordinate replay without duplicating existing records.
- Investigation queries: Support sub-second-to-low-second filtered searches by tenant, actor, action, resource ID, and time range for forensic and compliance use cases.
- Privacy-compliant redaction: Satisfy "right to erasure" requests (GDPR/CCPA style) within an append-only architecture, without breaking cryptographic verification of surrounding records.
Non-Functional Requirements
- Durability and availability: 99.999% durability, zero data loss. The ingestion path must stay available (99.99%) even during background compaction or index rebuilds.
- Scale: 50,000 tenants; 1 billion events per day (~12,000/s average, ~40,000/s peak). Seven-year retention.
- Query performance: Queries over the last 30 days must return within 3 seconds; multi-year cold queries within 30 seconds.
- Blast radius: A single high-volume tenant or compromised producer must not degrade service for others.
What Is Expected
Walk through your full design covering:
- End-to-end architecture — ingestion pipeline, transport, buffering, validation, and storage tiering (hot vs. warm vs. cold).
- Tamper-evidence data model — the cryptographic mechanism (hash chains, Merkle trees, external anchoring), event schema, and how erasure requests interact with integrity proofs.
- Reliability and operational controls — SLIs/SLOs, gap detection logic, backpressure, deduplication strategy, and key management for cryptographic shredding.
Go deep on at least two of those three areas. Mention trade-offs wherever you make a choice.
Hints
Hint 1
Start by sizing the system: 1B events/day at ~1 KB each is roughly 1 TB/day raw. Work out what that means for hot storage (30 days ≈ 30 TB), total retention (~2.5 PB before compression), and the throughput headroom you need to build in above 40k/s peak.
Hint 2
Tamper evidence has two distinct problems: proving a record hasn't changed (hash chains / Merkle trees), and proving an insider hasn't rewritten both the data and the hashes (external anchoring to an independent account or transparency log). You need both, and they have different trust assumptions.
Hint 3
Gap detection depends on producers emitting monotonic sequence numbers per stream and sending heartbeats even when idle. Without heartbeats, a completely silent producer looks identical to a healthy one — the platform can't distinguish 'no events' from 'events lost'.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and Back-of-Envelope Sizing
Before diving into components, anchor the design in numbers.
- Throughput: 1B events/day ≈ 12k/s average, 40k/s peak. Design ingestion for 3× peak headroom (~120k/s) to absorb traffic spikes and replay bursts.
- Storage: ~1 KB/event × 1B = 1 TB/day raw. Over 7 years that is ~2.5 PB raw. Parquet + zstd compresses audit data 5–10×, so target ~300–500 TB on disk before replication.
- Hot tier: 30 days × 1 TB ≈ 30 TB. Must serve sub-3s queries.
- Cold tier: Years 1–7 beyond the hot window. Must serve 30s queries, which rules out deep-archive classes with multi-hour restores.
- Trust model: Internal operators and producer credentials are untrusted. Integrity proofs must be verifiable by an external party with no access to your infrastructure.
- Delivery semantics: At-least-once ingest, exactly-once storage (deduplicated on
event_id).
2. API Surface
POST /v1/events:batch
Auth: mTLS + per-service signed token scoped to (producer, tenant set)
Body: { producer_id, stream_id, events: [{event_id, seq, ...}] }
Response 202: { accepted: [...], rejected: [{event_id, reason}] }
GET /v1/tenants/{t}/events
?actor=&action=&resource=&from=&to=&cursor=
GET /v1/tenants/{t}/proofs/{event_id}
→ Merkle inclusion proof + signed tree head
GET /v1/tenants/{t}/checkpoints?from=&to=
→ list of signed tree heads (consistency proofs)
POST /v1/tenants/{t}/subjects/{id}:erase
→ initiates crypto-shred; requires dual approval
Producers use a sidecar or SDK that maintains a local durable spool, assigns monotonically increasing seq per (producer_id, stream_id), and retries with the same event_id on failure.
3. Event Schema
event_id UUIDv7 (client-assigned idempotency key)
tenant_id string
producer_id string
stream_id string
seq int64 (monotonic per stream, gap-detection key)
occurred_at timestamp (client clock)
received_at timestamp (gateway clock)
actor { type, id, ip_address }
action string
resource { type, id }
outcome enum { success, failure, partial }
payload_plain object (non-sensitive; indexed and hashed)
payload_enc bytes (sensitive fields; AES-GCM with per-subject DEK)
subject_key_ids []string
prev_hash bytes (optional per-stream hash chain pointer)
producer_sig bytes (signature over canonical event bytes)
schema_version string
Schemas live in a registry (Protobuf or Avro). Validation is strict on required fields, lenient on unknown extensions so services can evolve independently.
4. End-to-End Architecture
Producer SDK and local spool. Events are written to a local disk WAL before any network call. The SDK batches, signs, and assigns seq. Retries carry the same event_id, so the platform always sees idempotent pushes.
Ingestion gateway (stateless, autoscaled). Performs mTLS authentication, token validation, schema validation, and per-tenant/per-producer token-bucket rate limiting. Returns 202 only after the durable log acknowledges the write. This is where blast-radius isolation begins — a runaway tenant hits its own rate limit and never backpressures the gateway for others.
Durable write-ahead log (Kafka / Kinesis). acks=all, replication factor 3 across AZs, min.insync.replicas=2. Partition by hash(tenant_id, stream_id) to preserve per-stream order. Large tenants get dedicated partitions or a dedicated topic tier. Retain 7–14 days — this is the replay buffer and what keeps ingestion available while downstream storage compacts or rebuilds indexes.
Sealer / committer (Flink with exactly-once checkpoints). Consumes from the durable log and:
- deduplicates on
event_idusing keyed state with a TTL equal to the replay window, backed by a uniqueness constraint at the storage layer; - tracks per-stream sequence watermarks for gap detection;
- batches events into 1-minute or N-event windows per tenant;
- builds a Merkle tree over each batch and signs a tree head (STH) with an HSM-held key;
- writes immutable Parquet segment files to object storage and emits the STH.
Immutable object store (system of record). S3 with Object Lock in compliance mode for 7 years. Partitioned as tenant/date/hour. Tiering: Standard → Standard-IA at 30 days → Glacier Instant Retrieval at 90 days. Glacier Instant keeps cold queries under 30s; Deep Archive would not.
Hot index (OpenSearch or ClickHouse). Holds the most recent 30 days. Shard by tenant; large tenants get dedicated indices. This is a derived, rebuildable view — not the source of truth. If it drifts, replay from object storage corrects it.
Witness / anchor service. Every 5–10 minutes, aggregates all tenant STHs into a global Merkle tree, signs the global root with an HSM key, and publishes it to: (a) an independent AWS account's Object Lock bucket, and (b) an external transparency log or RFC 3161 timestamp authority. This defeats the insider-rewrites-everything attack: any change to a committed record would produce a root that contradicts an already-published external timestamp.
5. Deep Dive: Tamper Evidence
There are two distinct integrity problems:
Within-record integrity: The producer signs each event, proving origin. The sealer builds a per-tenant Merkle tree per batch. Each STH includes prev_sth_hash, creating a hash chain of tree heads. An auditor requests an inclusion proof (O(log n) hashes) and a consistency proof between two checkpoints — standard techniques from Certificate Transparency.
Why per-tenant trees? They parallelize horizontally and isolate proofs. Tenant A's auditor verifies Tenant A's sub-tree without accessing Tenant B's data.
External anchoring defeats the insider threat. Rewriting any event changes its leaf hash, which changes the root, which contradicts the already-published external anchor. The anchor is the trust anchor, not the platform itself.
Object Lock in compliance mode blocks deletion even by privileged operators. Deletion attempts are themselves written to an audit trail in a separate account.
Hash ciphertext, not plaintext. This matters for erasure: shredding a DEK later does not break the Merkle proof, because the hash was taken over ciphertext plus the plaintext envelope metadata.
6. Deep Dive: Deduplication, Gap Detection, and Replay
Deduplication. The sealer maintains event_id in keyed state with a TTL covering the replay window. Retries with the same ID are absorbed silently. If two events share an ID but have different content hashes, that is a security signal — alert and quarantine, never silently overwrite.
Gap detection. Each (producer_id, stream_id) emits contiguous seq values. The sealer tracks a high watermark and a set of missing ranges. Producers also send periodic heartbeats carrying last_seq_emitted, even when idle. Without heartbeats, a silent producer is indistinguishable from a healthy one.
A missing range older than a configurable grace period (e.g., 15 minutes) and below the heartbeat's last_seq is a suspected gap. If no heartbeat arrives for N minutes, the stream is declared dark and an alert fires.
Replay. The orchestrator requests the specific missing seq ranges from the producer's spool. Because dedup is idempotent, replayed events that already landed are harmlessly discarded. Late-arriving events land in a later Merkle batch, indexed by occurred_at, flagged late=true. The original batch is never reopened.
Unrecoverable gaps (producer spool expired, data lost) are written as signed "gap attestation" records. Regulators prefer an acknowledged, signed gap over a silently missing range.
7. Privacy and Crypto-Shredding
Sensitive fields are encrypted with a per-subject DEK (or per-tenant/per-matter DEK), which is itself wrapped by a tenant KEK stored in KMS or an HSM. Erasure destroys the DEK, rendering ciphertext unreadable. The operation requires dual approval, is logged as an audit event in a separate append-only trail, and does not touch the Merkle tree or object store — the ciphertext remains in place, preserving chain-of-custody metadata and integrity proofs.
8. SLIs, SLOs, and Common Mistakes
Key SLIs: ingestion end-to-end latency (p99), event durability within N seconds of acceptance, gap detection latency, query latency at p95/p99, and Merkle anchor lag.
Common design mistakes to avoid:
- Using the query index as the source of truth. It can be rebuilt; the object store cannot be recreated from it.
- Hashing plaintext then shredding, which breaks proofs. Always hash ciphertext.
- Skipping heartbeats, which makes silent failures invisible.
- Single global Merkle trees, which create a serialization bottleneck at scale. Per-tenant trees with a global roll-up are the right structure.
- Putting all tenants on the same Kafka partitions without rate-limiting, which lets one tenant starve others.