Architecting and Defending a High-Security Event Streaming Backbone
Medium · System Design · Software Engineer · Take-home Project
Prompt
This exercise simulates a two-phase architecture evaluation: first, preparing a written design proposal on your own schedule, and second, walking an engineering panel through that proposal in an interactive review session where panelists probe edge cases, pitch alternative components, and introduce mid-meeting requirement changes.
Design an internal near-real-time event streaming backbone where backend microservices publish domain events and downstream services subscribe to them continuously. Within this organization, security posture and continuous availability outrank every convenience feature—treat both as foundational invariants woven into every layer rather than bolt-on sections at the end. Frame every architectural trade-off around the operational teams and downstream workloads relying on the backbone.
Before locking in components, explicitly establish working assumptions for the ambiguities an architecture brief leaves open: - Client boundary: Are publishers and subscribers strictly internal backend workloads, or do external customer agents connect directly? - Traffic shape: What baseline and peak message rates, payload sizes, and burst multipliers must the backbone absorb? - Freshness target: What end-to-end publish-to-consume latency budget defines "near real time" for active subscribers? - Delivery & ordering rules: Should the backbone guarantee at-most-once, at-least-once, or effectively-once semantics, and on what key (if any) is strict ordering preserved? - History & replay: How many days must events remain readable, and do subscribers rewind cursors to reprocess historical windows? - Multi-tenancy: Do multiple internal engineering organizations share the infrastructure while requiring strict security and resource isolation?
Structure your solution across both phases of the evaluation: 1. Written architecture proposal: State your concrete assumptions and recovery targets, estimate network/storage/broker capacity, define the publish and subscribe APIs plus the event and metadata schemas, trace the end-to-end architecture, detail defense-in-depth security (cryptographic workload identity, fine-grained access control, in-transit and at-rest encryption, tenant blast-radius isolation, and immutable audit logging) and multi-zone/regional resilience, and explain which alternative designs you ruled out. 2. Interactive panel pushback: Demonstrate how you collaborate constructively—acknowledging a reviewer's core risk before evaluating their fix, adopting better options without ego, holding firm with numbers when invariants are threatened, and logging architectural changes—across three live scenarios: - Build-versus-buy pushback: A panelist proposes swapping a stateful core component you designed for a managed cloud offering. - Full regional blackout: A panelist asks for the exact behavior experienced by publishers, subscribers, and in-flight data if an entire cloud region goes offline. - Mid-review scope change: Stakeholders announce that a subset of high-impact command events must never produce duplicate downstream side effects.
Scope & Expectations
- Explicit foundations & sizing: Clear workload assumptions, RPO/RTO availability commitments, back-of-the-envelope throughput and storage math, and justified delivery, ordering, and retention choices.
- Durable partitioned data path: Well-defined publish and subscribe contracts, tamper-resistant event envelopes, and a replicated, partitioned storage core engineered for zone and regional faults.
- Defense-in-depth security: Concrete workload authentication, default-deny authorization, envelope and end-to-end encryption options, noisy-neighbor quotas, and tamper-evident audit trails that never fail open.
- Collaborative review responses: Disciplined handling of all three panel challenges—restating concerns first, quantifying latency/storage/operational costs of requirement shifts, and recording an explicit decision log.
Step-by-step walkthrough
Clarify requirements and write assumptions for the review
This evaluation has two halves: an asynchronous architecture proposal submitted ahead of time, and an interactive panel review where engineers challenge your choices and introduce mid-session scope changes. Because reviewers read the written proposal before entering the room, we state our working assumptions and most debatable trade-offs right on page 1: an explicit assumption invites a calm two-minute alignment, whereas an unstated assumption looks like an oversight.
Explicit scope and workload assumptions
- Producers and consumers: Internal backend microservices only—roughly 300 producer services and 1,000 consumer groups across 40 engineering teams (tenants). External customer devices do not connect directly here; any external telemetry enters through a separate edge ingestion tier that publishes into this platform as a normal internal tenant.
- Traffic volume and event size: 300,000 events/s regional average and 1,000,000 events/s peak per region, with per-tenant bursts up to 3x normal traffic. Average event payload is 1 KB, capped at 1 MB inline (larger blobs upload to object storage and send a pointer URL—the claim-check pattern).
- Real-time latency target: End-to-end publish-to-consume latency p50 < 50 ms and p99 < 500 ms within a region for healthy consumers keeping up with the stream.
- Delivery and ordering: At-least-once delivery (no acknowledged event is lost, though rare retries can deliver duplicates) with strict ordering per partition key (e.g., all events for
host_idoraccount_idarrive in order). No global cross-topic ordering. - Retention and replay: 7 days default retention (configurable up to 90 days per topic); consumers can rewind to an earlier offset or timestamp at any time to reprocess history.
- Multi-tenant isolation: All 40 teams share the platform, so security permissions, throughput quotas, and failure blast radius must be strictly isolated per tenant.
First-class availability and security targets
Before listing numbers, let us define two recovery terms we will use throughout: - RPO (Recovery Point Objective): The maximum age of acknowledged data that could be lost during a disaster (
RPO = 0means zero acknowledged events lost). - RTO (Recovery Time Objective): How quickly the system resumes serving traffic after a disaster begins.Property Target Plain-English meaning Publish availability 99.99% per month At most ~4.3 minutes/month ( 43,200 min * 0.01%) of failed writesConsume availability 99.95% per month At most ~21.6 minutes/month of delayed reads Single availability-zone loss RPO = 0, RTO < 1 min Automatic failover across zones with zero lost acknowledged events Whole-region disaster Standard: RPO < 5 s, RTO < 5 min; Critical: RPO = 0 Standard topics mirror asynchronously; critical topics replicate synchronously Identity & authorization Cryptographic identity + default-deny ACLs Zero anonymous connections, zero shared API keys, explicit per-topic grants Encryption TLS 1.3 in transit, envelope encryption at rest, optional E2EE Encrypted on every wire and disk; restrictedpayloads unreadable even to brokersImmutable auditing Tamper-evident logs in an isolated security account Even platform admins cannot delete or edit access/admin audit trails Five deliberate choices flagged up front for reviewers 1. Running partitioned Kafka-compatible broker cells (self-hosted initially; revisited in Challenge 1). 2. Putting a stateless policy gateway on the publish path, while letting consumers read directly from brokers. 3. Asynchronous cross-region replication by default, reserving synchronous multi-region quorum for a small critical tier. 4. At-least-once delivery with producer-generated
event_ids by default, rather than global transactions on every topic. 5. Disabling unclean leader election (refusing writes on a partition rather than promoting a stale replica that is missing acknowledged events).Back-of-the-envelope numbers
Let us walk through the capacity math step by step, keeping raw vs. compressed bytes explicit so every number checks out:
1. Network and disk throughput (per region) Raw ingress: 300k/s avg * 1 KB = 300 MB/s avg 1M/s peak * 1 KB = 1,000 MB/s = 1 GB/s raw peak Batch compression: ~3x with zstd/lz4 on structured events (validate on real payloads) -> 1,000 MB/s / 3 = ~333 MB/s compressed ingress at peak 3x zone replication: 1 leader + 2 follower replicas across 3 availability zones (AZs) -> Total cluster disk writes = 3 * 333 MB/s = ~1,000 MB/s (1 GB/s) compressed -> Cross-AZ replication traffic = 2 * 333 MB/s = ~667 MB/s (~5.3 Gbps) Consumer fan-out: Average 3 consumer groups read each topic (batches stay compressed on wire) -> Total broker egress = 3 * 333 MB/s = ~1,000 MB/s compressed (unpacks to ~3 GB/s raw inside consumer pods; served mostly from OS RAM cache) 2. Storage footprint Daily volume: 300,000 events/s * 1 KB * 86,400 s/day = ~25.9 TB/day raw Compressed (3x): ~8.64 TB/day Hot tier (NVMe SSD): Newest 24 hours on brokers * 3 replicas = 8.64 TB * 3 = ~26 TB per region Cold tier (S3/GCS): 7-day default retention = 8.64 TB/day * 7 = ~60.5 TB in object storage (Object storage handles multi-AZ durability internally, so 1 logical copy) 3. Partitions, broker cells, and publish gateways Partition count: Target <= 5 MB/s raw per partition -> 1,000 MB/s / 5 = 200 partitions min; with 40 tenants and hundreds of topics -> ~3,000 partitions per region Broker sizing: 12 brokers (4 per AZ) handle 1,000 MB/s / 12 = ~83 MB/s disk writes each. If 1 AZ fails, 8 surviving brokers still write ~83 MB/s each (only 2 active replicas remain per partition!), while consumer reads rise 1.5x to ~125 MB/s. To isolate blast radius, we split into 3 cells of 6 brokers (2 per AZ) = 18 brokers per region. Publish gateways: 1M events/s batched ~50/request = 20,000 RPCs/s. At ~50k events/s per stateless instance -> 20 needed; run 30 (10 per AZ) so 2 surviving AZs carry 100% of peak with zero throttling.APIs, event envelope, and control-plane data model
Publish API (gRPC over mutual TLS to the Publish Gateway) Mutual TLS (mTLS) means both client and server prove their cryptographic certificate identity during the TLS handshake.
rpc Publish(PublishRequest) returns (PublishResponse) PublishRequest { topic: "sec.telemetry.v1", events: [{ event_id: "01JA7M2R...", // UUIDv7 generated by producer SDK BEFORE first send key: "endpoint:srv-pay-07", // routes all events for this endpoint to the same partition schema_id: 41, headers: {"traceparent": "..."}, payload: <bytes> // plaintext serialized record, or SDK-encrypted ciphertext }] } PublishResponse { ack_offsets: [{event_id: "01JA7M2R...", partition: 4, offset: 9182734}] } // Standard errors: UNAUTHENTICATED, PERMISSION_DENIED, INVALID_ARGUMENT (schema mismatch), // RESOURCE_EXHAUSTED (tenant quota hit + retry_after_ms), UNAVAILABLEConsume API (Platform SDK wrapping the native Kafka protocol over mTLS directly to brokers)
subscribe(group_id="incident-correlator", topics=["sec.telemetry.v1"]) poll(max_records=500, timeout_ms=100) -> list[Event] commit(offsets) // called ONLY after processing finishes (at-least-once) seek(partition, offset_or_timestamp) // rewind into hot SSD or cold object storageTamper-evident event envelope Never trust a client-supplied
"sender"string! The Publish Gateway overwrites identity metadata from the verified mTLS certificate:+-----------------------------------------------------------------------------------+ | event_id (UUIDv7, set once by producer SDK; preserved across all retries/regions) | | tenant_id | topic | key | schema_id | classification (internal|confidential|restr)| | produced_at (producer clock, informational) | accepted_at (gateway clock, trusted)| | producer_principal: "spiffe://prod/ns/telemetry/sa/collector" (STAMPED BY GW!) | | payload: bytes (for `restricted` topics, AES-GCM ciphertext + key_id header) | +-----------------------------------------------------------------------------------+Control-plane metadata (PostgreSQL + GitOps config repository) All topic definitions and access grants live as code in a Git repository requiring peer review (with MFA-authenticated emergency API access), synced into a small control-plane database: -
tenants(tenant_id, owning_team, cell_id, max_publish_mb_s, max_consume_mb_s, max_storage_tb)-topics(topic_name, tenant_id, partitions, retention_days, availability_tier, priority_class, classification, schema_subject)-acl_grants(grant_id, spiffe_principal, topic_pattern, operation, approved_by, ticket_id, expires_at)-encryption_keys(topic_name, key_id, wrapped_dek_bytes, kms_kek_version, state, created_at)High-level architecture and publish-to-consume flow
Region A (3 Availability Zones: AZ-1, AZ-2, AZ-3) +------------------+ +------------------+ | Producer Pods | | Consumer Pods | | (Platform SDK: | | (Platform SDK: | | UUIDv7, batch, | | poll, decrypt, | | memory/disk buf)| | dedup, commit) | +------------------+ +------------------+ | mTLS (short-lived SPIFFE workload cert) ^ v | mTLS + Broker ACLs +------------------+ | (same-AZ follower | Zonal Network LB | | reads preferred) +------------------+ | | | v | +------------------------------------------------------------------+ | | Stateless Publish Gateways (10 per AZ = 30 instances) | | | 1. Verify mTLS cert 2. Check cached ACL grant 3. Tenant quota | | | 4. Validate schema 5. Stamp producer & time 6. Route to cell | | +------------------------------------------------------------------+ | | mTLS, acks=all | v | +------------------------------------------------------------------+ | | Broker Cells (Cell 1 .. Cell 3; 6 Kafka/KRaft brokers per cell) | ---------+ | - 3 replicas across AZ-1/2/3, min.insync.replicas = 2 | | - 24h hot NVMe SSD + tiered cold segments in encrypted S3/GCS | +------------------------------------------------------------------+ | | | Async Mirror (Standard topics) | Sync 3-Region Quorum (Critical tier) v v [Region B Cells] [Stretched Critical Cell: Reg A / B / C] Out-of-Band Control Plane (never on the hot path!): GitOps Repo + Admin API -> Policy Pusher | SPIFFE CA | KMS | Write-Once Audit AccountWhy put a gateway on publish, yet let consumers read straight from brokers? Publishing is the write boundary where untrusted bytes enter: a stateless gateway gives us one clean codebase to stamp verified identities, reject malformed schemas, enforce tenant rate limits, and route topics to isolated cells without exposing cell topology to producers. Consuming, by contrast, is read-only at 3x the byte volume (~1 GB/s compressed): brokers already enforce per-certificate read ACLs and byte quotas natively, and proxying stateful consumer-group rebalances and zero-copy page-cache reads through a middle tier would double network cost and add fragility for almost zero security gain.
Deep dive 1: delivery semantics, per-key ordering, and schema safety
Why at-least-once +
event_idis the right default - At-most-once commits the consumer's read position before processing, silently dropping security alerts if a consumer pod restarts mid-batch. - Global transactions everywhere add two-phase commit latency to every publish and still cannot prevent an external HTTP call or SQL update in a consumer from running twice without consumer-side coordination (covered in Challenge 3). - At-least-once holds data until at least 2 zones write it to disk (acks=all,min.insync.replicas=2, unclean leader election disabled) and commits consumer offsets after processing, tagging every event with a stableevent_idbefore the very first send so duplicates are trivial to detect.How per-key ordering survives a stateless gateway fleet Suppose a producer emits
State=QUARANTINEDthenState=CLEAREDforendpoint:srv-pay-07. Both hash to Partition 4 (hash("endpoint:srv-pay-07") mod P). Could Batch 1 hit a slow gateway while Batch 2 races ahead through a faster gateway and lands on Partition 4 out of order?We prevent reordering with two simple SDK rules: 1. Each producer pod keeps a long-lived HTTP/2 gRPC stream pinned to one healthy gateway instance, and allows at most 1 unacknowledged batch in flight per partition. Batch 2 is not sent until Batch 1 is durably acknowledged (~8–10 ms round trip; with 50 events/batch, one producer still achieves
100 batches/s * 50 = 5,000 events/sper partition!). 2. Between each gateway and the brokers, Kafka's native idempotent producer(producer_id, sequence_number)drops internal network-retry duplicates automatically. If a gateway crashes mid-flight and the SDK reconnects to a new gateway to resend Batch 1, either Batch 1 never reached the broker (no issue) or Batch 1 already landed first and the resend appends a harmless duplicate with the exact sameevent_id—never an out-of-order first arrival:Normal flow: SDK --[Batch 1 (e1, e2)]--> GW-1 --> Partition 4: [e1, e2] --ack--> SDK sends Batch 2 GW-1 timeout: SDK --[Batch 1 (e1, e2)]--> GW-1 (wrote [e1, e2], died before ack) SDK reconnects to GW-2, resends Batch 1 BEFORE sending Batch 2: Partition 4 log: [e1, e2, e1(dup), e2(dup), e3, e4] -> first-seen order is [e1, e2, e3, e4]!Schema compatibility and poison-pill events Every topic binds to a schema in the Schema Registry enforcing full compatibility (both backward compatible—new consumers can read old events—and forward compatible—existing consumers can safely ignore new optional fields added by upgraded producers). Backward compatibility alone is a classic trap: without forward compatibility, deploying a producer with a new field immediately crashes 20 downstream consumers still running yesterday's code! If a valid-schema event still triggers an application bug in a consumer (poison pill), the SDK retries 3 times with backoff and then follows the group's configured policy: route to a per-group dead-letter queue (DLQ) for unordered topics, or pause that single partition and page the on-call engineer when strict per-key ordering cannot skip an event.
Deep dive 2: defense-in-depth security controls
Because a security breach on shared messaging plumbing exposes all 40 teams at once, every threat gets a concrete cryptographic or architectural control:
Threat Concrete control Spoofed service identity Short-lived X.509 SPIFFE workload certificates (24h lifetime, auto-rotated at 12h by the node agent) over mTLS 1.3; the gateway stamps producer_principalfrom the verified cert.Unauthorized topic read/write Default-deny ACLs; explicit (principal, topic, produce|consume)grants require topic-owner Git approval (2-person approval onrestrictedtopics) and auto-expire for temporary access.Wire eavesdropping TLS 1.3 mandatory on every hop (SDK-to-gateway, gateway-to-broker, inter-broker, cross-region); plaintext ports disabled in binary config. Stolen disk or bucket exposure Encrypted NVMe volumes + envelope encryption per topic segment in private S3 buckets reachable only over VPC private endpoints. Compromised broker or rogue admin reading sensitive payloads End-to-end encryption (E2EE) on restrictedtopics: producer SDK encryptspayloadwith AES-256-GCM before sending; gateways and brokers see only opaque ciphertext, and schema validation runs inside the SDK prior to encryption.Admin credential compromise Human SSO + hardware MFA, zero standing SSH on brokers (just-in-time recorded break-glass sessions that page Security), and signed container images verified at deploy. Attacker covering their tracks Auth denials, ACL edits, KMS unwraps, and break-glass sessions stream via an independent agent (not over Kafka itself!) to an immutable object-lock bucket in a separate security cloud account. How envelope encryption works (and why it protects availability too) Calling a central Key Management Service (KMS) on 1,000,000 events/s would both melt the KMS and bring down messaging whenever KMS blips. Envelope encryption uses a two-tier key hierarchy:
[Master Key (KEK) inside KMS hardware] <-- Never leaves KMS; called only ~once/hour per node | wraps / unwraps v [Daily Per-Topic Data Key (DEK)] <-- Cached in broker/SDK RAM for 60 min; stored wrapped | AES-256-GCM encrypts at memory speed v [Log Segments & Restricted Event Payloads] (header records key_id so readers pick the right DEK)Keeping security controls from causing outages ("fail-static, never fail-open") If the Control Plane, Certificate Authority (CA), or KMS goes down, what happens? - Never fail-open (allowing unauthenticated or unauthorized requests when policy servers fail turns an outage into a breach!). - Instead, gateways and brokers fail-static: they keep serving existing workloads using their last-known signed ACL snapshot in memory, 24-hour certificates rotated at the 12-hour mark survive a 12-hour CA outage for running pods, and 60-minute cached DEKs survive transient KMS blips.
Deep dive 3: availability, multi-zone failover, and tenant isolation
Surviving zone and component failures automatically (
RPO = 0,RTO < 1 min) Every cell places 2 brokers and 1 KRaft metadata controller in each of the 3 AZs, with 1 partition replica per AZ. If AZ-2 loses power: 1. The surviving 2-of-3 controller quorum in AZ-1 and AZ-3 detects missing broker heartbeats within seconds and elects in-sync followers in AZ-1/AZ-3 as leaders for the ~1/3 of partitions previously led in AZ-2. 2. Because every acknowledged publish requiredmin.insync.replicas = 2, at least one surviving replica in AZ-1 or AZ-3 already holds every acknowledged byte (RPO = 0). 3. Zonal load balancers drop AZ-2 gateways; producer SDKs reconnect streams to AZ-1/AZ-3 and flush any unacknowledged in-flight batches from their 64 MB RAM buffer (backed by an optional 2 GB encrypted local disk spool for critical security agents). Under extreme overload, gateways shed load by priority class—throttlingbulklog topics first, thenstandard, preserving 100% capacity forcriticalsecurity topics.Six layers of multi-tenant isolation ("noisy neighbor" protection) 1. Namespace ownership: Team
paymentscan only create topics underpayments.*. 2. Distributed gateway token buckets: A token bucket is a rate limiter that refills credits at a steady rate (bytes/sandRPCs/s) up to a burst cap. Critically, a tenant's 30 MB/s quota is divided across the 30 gateways (1 MB/slocal share per gateway, rebalanced every few seconds from observed traffic)—setting the full 30 MB/s on each of 30 gateways would accidentally allow30 * 30 = 900 MB/s! 3. Broker-level second line of defense: Gateways tag broker writes with a per-tenantclient_idso native broker quotas catch a runaway tenant even if gateway quota sync lags. 4. Consumer & replay throttling: Per-principal fetch quotas and separate cold-storage read limits prevent one team's 30-day backfill from saturating broker NICs. 5. Cellular blast radius: Placing tenants onto separate 6-broker cells guarantees a broker bug or misconfigured workload in Cell 2 cannot touch tenants in Cells 1 and 3. 6. Cryptographic blast radius: Separate daily DEKs per topic ensure a single key exposure never unlocks another tenant's events.Live review challenge 1: "Swap self-hosted broker cells for a managed cloud service"
In the live review, an engineer pushes back: "Why is our team running 18 Kafka brokers per region ourselves? We should just buy a managed cloud Kafka service."
Step 1 — Restate the reviewer's underlying concern before arguing: "You're concerned that running stateful storage brokers ourselves eats engineering on-call bandwidth, and that slow OS/Kafka security patching by a small platform team could actually make us less secure than a dedicated cloud vendor. Is operational burden and patching speed your main worry, or total infrastructure cost?" (Assume they confirm operational burden and patching.)
Step 2 — Evaluate systematically against our non-negotiable security & availability bar:
Requirement Must hold to adopt managed brokers Verification in a 2-week bake-off Workload identity Supports mTLS with our SPIFFE CA (or IAM workload identity) + per-principal ACLs End-to-end PoC with our SDK Network & keys Private VPC endpoints only + customer-managed KMS keys (CMEK) we can revoke Security architecture review Availability Multi-AZ SLA >= 99.99% with acks=allandmin.insync.replicas=2Chaos test killing one AZ's ENIs Protocol fidelity Native Kafka protocol (idempotent writes, transactions, tiered storage, client quotas) Run SDK conformance + 1.5x load test Step 3 — Concede where they are right; hold firm with evidence where they are not: - Concede on the broker cells: If a managed Kafka offering passes the checklist above, we adopt it for the broker cells. Running commodity disk replication is not our competitive advantage—offloading broker upgrades and disk replacements genuinely improves patch hygiene, and keeping the Kafka wire protocol preserves zero lock-in for our SDKs. - Hold firm on keeping our custom Publish Gateway and SDK: A generic cloud API gateway cannot stamp SPIFFE identities into binary event envelopes, validate topic-bound Avro/Protobuf schemas, enforce cross-cell tenant routing, or coordinate SDK end-to-end encryption on
restrictedtopics. Keeping the thin stateless gateway gives us total ownership of our security invariants while letting a vendor run the heavy stateful disks.Live review challenge 2: "Walk through a total primary-region blackout"
A reviewer asks: "US-East goes completely dark. Walk me through exactly what producers and consumers see, what data is lost, how consumer offsets work in US-West, and who triggers failover."
Step 1 — Restate the concern: "You want concrete mechanics—not hand-waving—on four things during a full regional outage: data loss (RPO), producer recovery time (RTO) and capacity, how consumers resume without skipping events when cluster offsets don't match, and whether failover is automated or human-gated."
Step 2 — Walk through our two-tier regional architecture:
Tier Topology & Replication RPO RTO Extra Cost ------------------------------------------------------------------------------------------------ Standard Independent regional cells; async replicator < 5 sec < 5 min 1x cross-region (95% vol) copies Region A -> Region B as `us-east.<t>` egress (~333 MB/s) Critical Single cell stretched across 3 regions 0 bytes < 1 min 2x cross-region (5% vol) (1 replica + controller/region, min.isr = 2) egress + ~40ms RTT- What happens to producers: Workloads running only in US-East are down anyway. Multi-region services shift traffic to US-West, and any surviving producer SDK unable to reach US-East gateways for 30 seconds fails over to US-West gateways, flushing its buffered events preserving the original
event_ids. To ensure US-West does not melt under doubled load, capacity planning caps steady-state regional utilization at <= 50% in a 2-region footprint! - How consumers resume without missing events (offset translation): Partition offset
#900,412in US-East does not equal offset#900,412in US-West's mirrored topic! Our async replicator (like MirrorMaker 2) continuously emits(source_offset -> target_offset)checkpoint records per consumer group. Relocated consumers seek to the last checkpoint slightly behind their US-East commit, re-reading a few seconds of already-processed events (safe viaevent_iddeduplication) rather than skipping events. - What happens to the <5 seconds of un-mirrored Standard events? In 99% of "region outages" (power/BGP/control-plane failures), NVMe disks survive! When US-East recovers hours later, the replicator drains those stranded tail events into
us-east.<topic>—meaning they are delayed and out-of-order, not permanently lost (consumers detect late arrivals viaaccepted_at). Only a physical datacenter destruction loses those <5 seconds. - Hold firm against making 100% of topics synchronous: Adding a 40–70 ms cross-region round trip to every publish and doubling cross-region egress (~667 MB/s sustained peak) for routine debug/telemetry streams wastes millions per year; offering the
criticalstretched cell (RPO = 0) per topic lets teams pay that latency and bandwidth tax only where business risk demands it. Producer failover is automatic on health checks, while declaring a region permanently dead is a human incident-commander decision to avoid split-brain flaps.
- What happens to producers: Workloads running only in US-East are down anyway. Multi-region services shift traffic to US-West, and any surviving producer SDK unable to reach US-East gateways for 30 seconds fails over to US-West gateways, flushing its buffered events preserving the original
Live review challenge 3: "High-stakes command events must never trigger duplicate side effects"
Mid-review, the team adds a new requirement: "Billing charges and automated endpoint-isolation commands (~2,000 events/s across 5 topics) must execute once and only once—never dropped, never applied twice."
Step 1 — Restate and clarify boundaries honestly: "You need both zero loss and zero duplicate side effects on ~2,000 events/s. Let's be completely upfront about distributed systems physics: no message broker on earth can guarantee an external side effect happens once by itself, because a consumer can charge a credit card and crash 1 millisecond before acknowledging the broker! True effectively-once processing requires committing the business side effect and the 'processed' marker atomically together."
Step 2 — Concrete design additions (
processing_mode: effectively_once) 1. Transactional inbox pattern for database consumers (SDK helper library): The consumer writes theevent_idinto aninbox_processedtable inside the exact same ACID database transaction as its business state update, and commits the Kafka offset afterward:BEGIN TRANSACTION; INSERT INTO inbox_processed (event_id, processed_at) VALUES ('01JA7M2R...', NOW()) ON CONFLICT (event_id) DO NOTHING; -- Check rows_inserted: -- 0 rows -> duplicate redelivery! COMMIT immediately and advance Kafka offset. -- 1 row -> first time! Execute business mutation in the same transaction: UPDATE customer_balances SET balance_cents = balance_cents - 5000 WHERE id = 'acct_9'; COMMIT TRANSACTION; -- Now commit Kafka consumer offset (if pod crashes right here, redelivery hits 0 rows above!)- Stream-to-stream pipelines: When a service reads Topic X and writes derived events to Topic Y, it uses Kafka transactions (atomically committing output messages + input consumer offsets, with downstream consumers set to
isolation.level = read_committed). Because stateless Publish Gateways do not proxy stateful broker transactions, we record an explicit, narrow exception to Decision 2: approved stream processors receive mTLS grants to write transactions directly to their output cell, using SDK-side schema validation. - External HTTP APIs (e.g., Stripe or cloud firewall APIs): Pass the immutable
event_idin the downstream API'sIdempotency-Keyheader so the external system deduplicates retries natively.
Step 3 — Quantify the exact cost of this requirement change: - Database storage:
2,000 events/s * 86,400 s/day * 8 days(7-day topic retention + 1-day safety buffer) = ~1.38 billion rows. At ~100 bytes/row (UUID + timestamp + B-tree key), that requires ~140 GB across the consumers' databases. Partitioninginbox_processedinto daily child tables (inbox_2026_11_30) lets us drop expired days instantaneously viaDROP TABLEwith zeroDELETE/vacuum bloat! (Where a single fenced writer owns each key, storing onlylast_seq_numper key shrinks this to megabytes.) - Throughput & replay coupling: Adds ~2–5 ms per DB transaction, forbidsskip_to_dlqwithout human sign-off, and locks topic retention to<= inbox retentionso rewinding offsets cannot replay forgotten IDs.- Stream-to-stream pipelines: When a service reads Topic X and writes derived events to Topic Y, it uses Kafka transactions (atomically committing output messages + input consumer offsets, with downstream consumers set to
Decision log, open questions, and trade-off summary
Capturing an explicit decision log during the live review demonstrates disciplined engineering leadership and prevents the team from re-litigating settled debates next month:
# Architecture Decision Post-Review Status Rationale & Trigger to Revisit 1 Kafka-compatible broker cells Updated: Run 2-week managed-Kafka bake-off Offloads OS/broker patching while keeping wire-protocol portability; revert to self-hosted if CMEK or 99.99% SLA fails. 2 Publish Gateway on writes; direct broker reads Kept (with narrow exception for transactional stream processors) Centralizes write-side identity stamping, schema checks, and quotas without doubling 1 GB/s read traffic. 3 Async regional mirror (Standard) + 3-region sync cell (Critical) Kept (documented 50% regional capacity ceiling) Saves ~40 ms publish latency and 333 MB/s cross-region egress on 95% of volume while giving RPO = 0 where required. 4 At-least-once default + opt-in effectively_onceExtended (Challenge 3) Added SDK transactional inbox helper, daily table partitioning (~140 GB), and Idempotency-Keycontract.5 acks=all,min.isr=2, no unclean leader electionKept Brief partition write unavailability beats silently losing acknowledged security events. Tracked open action items - Product & Security leads (by Friday): Finalize the exact list of topics qualifying for the
criticalsynchronous 3-region tier andrestrictedE2EE classification. - Platform team (2-week sprint): Execute managed-Kafka chaos + security bake-off and report latency/cost numbers. - Consumer teams: Audit standard-tier consumers to confirm they handle delayed out-of-order events (accepted_at) gracefully after regional recovery.
Intuition & how it works
Think of a high-security, real-time event platform like an armored multi-vault courier network shared by 40 company departments. Every sender must present a short-lived cryptographic badge at a guarded front desk (the Publish Gateway), which stamps the sender's verified name onto the envelope, checks that the package fits safety rules (schema and rate quotas), and locks identical copies inside at least two separate fireproof vaults across town (availability zones) before handing back a receipt. For top-secret letters (restricted topics), the sender seals the message inside a locked box before handing it over, so not even the couriers or vault operators can read what is inside.
A naive setup—letting 300 microservices call one another directly over HTTP or share a single unguarded message broker—breaks down quickly under failure and attack. Direct service-to-service calls drop events whenever a receiver deploys or crashes; a single shared cluster lets one buggy team flood disk and network for all 40 teams; trusting a "producer_name" JSON field lets any compromised service impersonate security sensors; and checking a central permissions server on every single message turns a minor policy-database hiccup into a company-wide outage.
Here is how one telemetry event (evt_904 for endpoint:srv-pay-07) travels end to end—including surviving a sudden datacenter zone failure mid-flight:
1. Stamp & prepare (Producer SDK):
- Generates immutable UUIDv7 `evt_904` BEFORE sending, hashes `endpoint:srv-pay-07` -> Partition 4,
and sends batch over mutual TLS (mTLS) to Publish Gateway GW-1.
2. Verify & replicate (Gateway -> Cell 1 Brokers across 3 zones):
- GW-1 verifies pod cert, checks cached ACL + tenant token bucket, stamps verified identity,
and writes to Partition 4 Leader (AZ-1) with `acks=all` and `min.insync.replicas=2`.
- AZ-1 Leader writes to NVMe SSD and replicates to AZ-2 and AZ-3 followers -> returns ACK!
3. Survive failure & consume once:
- Seconds later, AZ-1 loses power! KRaft quorum promotes in-sync AZ-2 follower to Leader in <5s;
zero acknowledged bytes are lost (`RPO = 0`).
- Consumer `incident-correlator` polls AZ-2, inserts `evt_904` into its `inbox_processed` table
in the same DB transaction as its incident row, and commits its offset -> zero loss, zero double-fire!
In the live design review, apply the same clarity to human collaboration: always restate the reviewer's underlying risk in your own words first, concede gladly on commodity infrastructure (like swapping self-hosted Kafka disks for a vetted managed service), and hold firm with concrete math on core security and physics invariants (like keeping your identity-stamping gateway and requiring consumer cooperation for once-only side effects).
Key trade-offs
- Partition durability vs. write availability under double faults: Requiring
acks=all,min.insync.replicas=2(at least two up-to-date copies on disk before acknowledging), and disabling unclean leader election (never promoting an out-of-date replica to leader) guarantees zero silent loss of acknowledged events (RPO = 0), at the cost that if two of three zones fail simultaneously, affected partitions pause writes (buffered safely in producer SDK RAM/disk) rather than losing data. - Security dependencies vs. data-plane uptime ("fail-static"): Short-lived mTLS certificates (two-way cryptographic identity), central ACL grants, and a Key Management Service (KMS, hardware-backed key vault) shrink attacker blast radius, yet calling them per event would create single points of failure. Caching 24-hour certs (rotated at 12h), 60-minute unwrapped data keys, and last-known ACL snapshots (failing static, never failing open by allowing unverified traffic) keeps running pods healthy through control-plane outages, with the sole limitation that brand-new pods wait if the certificate authority is down >12 hours.
- Publish gateway + direct broker reads vs. proxying everything: Routing writes through stateless gateways centralizes identity stamping, schema checks, tenant quotas, and cell routing at modest cost (~333 MB/s compressed), whereas letting consumers read directly from brokers via native ACLs avoids doubling ~1 GB/s of fan-out read traffic and re-implementing consumer-group rebalancing.
- End-to-end encryption (E2EE) vs. server-side inspection: Encrypting
restrictedpayloads inside the producer SDK keeps secrets unreadable even to compromised brokers or platform admins, at the price that gateways can no longer inspect payloads (moving schema validation into the SDK) and consumers must manage decryption keys. - Asynchronous vs. synchronous cross-region replication: Async mirroring keeps publish latency local (<15 ms) and pays 1x cross-region bandwidth with an RPO (max lost/delayed window on region disaster) under 5 seconds, whereas a 3-region synchronous stretched cell achieves
RPO = 0at the cost of a cross-region network round trip (tens of milliseconds) on every publish and 2x cross-region egress—making synchronous replication right only for a smallcriticaltier. - Multi-cell isolation vs. single-cluster bin-packing: Splitting 18 brokers into 3 isolated 6-broker cells leaves slightly more idle headroom than one giant 12-broker cluster, in exchange for containing any bad rollout, controller bug, or noisy tenant to at most one fraction of teams.
- At-least-once default vs. opt-in effectively-once processing: Defaulting to at-least-once delivery with stable UUIDv7
event_ids stays fast and lightweight, while reserving the transactional inbox pattern (recordingevent_idin the consumer's database transaction) for the few topics where duplicate side effects cause real harm (~140 GB extra DB storage for 2,000 events/s over 8 days).
Common mistakes
- Treating security as an afterthought ("use TLS and auth"): Omitting workload identity issuance, who stamps
producer_principal, default-deny grant workflows, envelope key hierarchy, or tamper-proof audit storage in a separate cloud account fails the primary constraint of this problem. - Trusting producer-provided sender fields: Allowing clients to populate
producer_servicein JSON lets any buggy or compromised pod spoof high-privilege events; the gateway must overwrite identity from the verified mTLS certificate. - Promising "broker-only exactly-once" for external side effects: Kafka transactions only cover Kafka-to-Kafka pipelines; if a consumer charges a credit card or calls an external webhook and crashes before committing its offset, duplicate execution happens unless the downstream action uses an idempotency key or transactional inbox.
- Failing open—or calling KMS/ACL stores on every message: Calling policy or key servers per publish melts the control plane and causes total outages; conversely, bypassing auth checks when the policy server is unreachable turns an outage into a security breach.
- Breaking per-key order across stateless gateways: Sending multiple concurrent batches for the same partition across different gateway instances allows Batch 2 to overtake Batch 1; cap in-flight batches to 1 per partition on a pinned stream.
- Setting full tenant quotas independently on each gateway instance: Giving a tenant its full 30 MB/s limit on all 30 gateways accidentally grants 900 MB/s; each gateway must enforce
quota / active_gateways(plus broker-level tenant quotas as a backstop). - Enforcing only backward schema compatibility: Backward compatibility only guarantees new consumers can read old messages; without forward (full) compatibility, rolling out an updated producer immediately breaks existing live consumers.
- Getting defensive or rigid in the live review: Jumping straight into defending your diagram without first restating the reviewer's concern—or refusing to swap out undifferentiated broker operations when a managed service meets every security requirement—misses what the live review evaluates.
Follow-up questions
- Suppose a single onboarded team suddenly spikes to 10x its baseline publish rate—how do you shield every other tenant from degradation? First, the 30 stateless Publish Gateways enforce global per-tenant token buckets (
bytes/sandrequests/s, each gateway enforcing its1/30dynamic share), immediately rejecting excess writes above burst allowance withRESOURCE_EXHAUSTEDand aRetry-Afterheader so the runaway tenant buffers in its own pods instead of entering the brokers. Second, gateways attach a tenant-specificclient_idwhen writing to brokers so native broker produce quotas act as an independent backstop if gateway quota sync ever lags. Third, per-tenant storage caps and topic retention byte limits prevent disk exhaustion, while cell isolation ensures that even a catastrophic bug affects at most the subset of tenants sharing that 6-broker cell, paging the tenant's on-call team automatically. - How can you perform both routine and emergency rotation of storage encryption keys with zero service interruption? We use envelope encryption, where a hardware Key-Encryption Key (KEK) inside KMS wraps lightweight daily per-topic Data-Encryption Keys (DEKs) that actually encrypt log segments. For routine KEK rotation, we simply create a new KEK version in KMS and re-wrap the small stored DEK blobs in metadata—zero terabytes of event segments are rewritten, and old KEK versions remain enabled for unwrap until re-wrapping finishes. For scheduled daily DEK rotation, new log segments simply write the new
key_idin their header while readers cache both old and new DEKs to read historical segments seamlessly until retention expires. Only an active DEK compromise requires data re-encryption: we immediately mark the compromised DEKdecrypt_only, run a background job to rewrite cold S3 segments under a fresh DEK, and copy E2EErestrictedtopics into a fresh re-encrypted topic before revoking the old DEK. - When a subscriber group lags several hours behind the live stream, how do you detect the issue and help the team catch up safely? Track time lag (
current_time - accepted_atof the oldest uncommitted event per partition) rather than raw message counts—since 100,000 messages might be 10 seconds at peak or 4 hours overnight—and alert both on the consumer group's latency SLO and when lag approaches 50% of topic retention (before data ages out!). To catch up, the consumer team first scales out consumer pods up to the topic's partition count; older segments stream transparently from tiered object storage under per-group cold-read throttles so live tailing consumers are never starved of broker page cache or NIC bandwidth. If processing logic itself is too slow (e.g., unbatched DB calls), the team can batch downstream writes, temporarily spin up a parallel catch-up group on the recent timestamp window (seek(now - 5m)) while backfilling the multi-hour gap asynchronously, or migrate to a higher-partition.v2topic. - What cutover plan moves legacy publishers onto this event backbone without dropping messages or causing duplicate downstream actions? Start on the read side: update consumers to deduplicate by
event_idfirst, because zero-downtime cutovers always overlap briefly. Next, deploy a stateless bridge connector that tails the legacy broker and republishes events into the new platform using deterministicevent_ids hashed from(legacy_topic, legacy_partition, legacy_offset)—so even if the bridge restarts, retries generate identical IDs—allowing consumers to migrate to the new platform cleanly while producers still write to the old one. If any legacy consumers must move later, run a reverse bridge and stamp anorigin_systemheader on bridged records so neither bridge ever echoes an event in an infinite loop! Finally, shift producer pods one by one: drain the legacy bridge lag to zero before flipping each producer instance (preserving per-key ordering), verify per-minute event counts and rolling checksums across both systems, and decommission the legacy broker once traffic hits zero.
Follow-up questions
- Suppose a single onboarded team suddenly spikes to 10x its baseline publish rate—how do you shield every other tenant from degradation?
- How can you perform both routine and emergency rotation of storage encryption keys with zero service interruption?
- When a subscriber group lags several hours behind the live stream, how do you detect the issue and help the team catch up safely?
- What cutover plan moves legacy publishers onto this event backbone without dropping messages or causing duplicate downstream actions?
Similar questions
- Design an Asynchronous Multi-Engine File Malware Scanner
- Distributed Worker Pool for High-Throughput Template Rendering
- Counting Orthogonal Land Regions in a Matrix
- Priority Detection Queue With Put and GetNext
- TTL-Aware Key-Value Store and Networked Cache Architecture
- Highest Bottleneck Score in a Grid
More Crowdstrike interview questions
- Distributed Worker Pool for High-Throughput Template Rendering Medium
- Priority Detection Queue With Put and GetNext Medium
- TTL-Aware Key-Value Store and Networked Cache Architecture Medium Pro
- Conduct a Spoken Code Review of a Python Function with Tiered Severity Medium Pro
- Counting Orthogonal Land Regions in a Matrix Medium Pro
- Design an Asynchronous Multi-Engine File Malware Scanner Medium Pro
- Highest Bottleneck Score in a Grid Medium Pro