Distributed Systems Security and Trust Questions
Security problems that exist because a system is distributed: keeping trust state correct while it propagates across many services, clusters and regions. Covers credential, token and certificate revocation under eventual consistency and network partitions; fleet-wide rotation of signing keys, secrets and trust anchors without outages (key rollover and grace windows, canary rotation, recovery from a compromised root); distributed authorization (replicated policy decision points, cached decisions, fail-open versus fail-closed when an auth dependency degrades); propagating caller identity and permissions through service call chains; tamper-evident audit trails across services and regions (hash chains, Merkle proofs, ordering events with imperfect clocks); Byzantine and partially trusted participants; cross-cluster and cross-organization trust federation; securing shared distributed components such as caches and message brokers against injection, replay and cross-tenant access; protecting data in transit across region boundaries; and tenant isolation as a security blast-radius boundary. Steady-state mTLS, service-mesh identity and network segmentation mechanics are covered by zero-trust service-to-service security; single-system cryptography and KMS basics by applied cryptography.
You need to build a distributed auditing pipeline that collects security events from 200 services across three regions at a sustained rate of 100k events per second. Requirements: tamper-evident storage, per-entity ordered audit history, low-latency querying for investigations, seven-year retention, and resilience to partitions. Walk through ingestion, transport, storage choices, cryptographic integrity controls, and how SREs would operate restores and audit queries.
Sample Answer
Direct answer
Treat the audit pipeline as three tiers joined by a durable log: a local, disk-buffered collector in every region, a partitioned append-only log (Kafka-style: Kafka is a distributed log system where writes are split into ordered partitions, each an append-only sequence that many readers can replay from the beginning) keyed by entity ID so each entity's events stay in order, and tiered storage: a hot search index for recent investigations and immutable columnar files (data stored column by column rather than row by row, which lets an analytical query read only the columns it needs and compresses far better than row-oriented storage) in write-once object storage for the seven-year archive. Integrity comes from a hash chain per log partition plus a signed checkpoint every minute, written to storage nobody (including administrators) can rewrite. Regions keep accepting events through a network partition and forward them when the link heals, because an audit system that drops events during an outage is failing exactly when it matters.
Requirements and the load you are designing for
At 100k events per second, assume an average event of 1 KiB (a JSON record with actor, action, resource, source IP and a few tags). That assumption drives everything, so say it out loud in the interview.
100,000×86,4008.64×109×1024 B8.85 TB×2,557 days=8.64×109 events/day≈8.85 TB/day raw≈22.6 PB raw over 7 years(2,557 days is 7 years including two leap days.) Sustained ingest is about 102 MB/s in total, roughly 34 MB/s per region if traffic splits evenly. Audit JSON compresses well in a columnar format; if you assume a 5:1 ratio the archive is about 4.5 PB, at 8:1 about 2.8 PB. Measure your own ratio on a day of real data before committing a budget, because this is the single largest cost line.
Ingestion: never lose an event at the edge
- Emit at the source with a schema. Each of the 200 services writes events through a small shared library that stamps an event ID (a UUID, used later for de-duplication), the entity ID (user, tenant, resource), a producer sequence number, and a hybrid logical clock timestamp (a timestamp that combines wall-clock time with a counter so events stay causally ordered even when clocks drift slightly).
- Local agent with a disk buffer. A node-level collector, any of the standard off-the-shelf log-shipping agents (Vector, Fluent Bit or an OpenTelemetry Collector; the choice between them matters far less than getting the "buffer to disk before acknowledging" behaviour right) accepts events over a local socket and persists them to disk before acknowledging. If the regional log is unreachable, the agent keeps buffering.
- At-least-once, then de-duplicate. At-least-once delivery means an event may arrive twice but is never silently dropped. The storage layer drops duplicates by event ID. Exactly-once across 200 services and three regions is not worth its coordination cost here; idempotent storage gives the same observable result.
Transport: a partitioned log per region
Each region runs its own log cluster. The partition key is the entity ID, so all events for user:42 land on one partition and are stored in the order the partition received them. That is what gives "per-entity ordered history" cheaply. Two caveats worth naming:
- Ordering is per entity per region. If
user:42acts in the US and EU in the same second, merge the two streams at query time by hybrid logical clock timestamp, then by region, then by sequence. Do not pretend a global total order exists; build one only if a regulator demands it, and then with a sequencer per entity home region. - A hot entity (a service account doing 5,000 actions per second) can overload one partition. Detect it and sub-partition that entity by
entity_id + bucket, recording the bucket so the query layer knows to merge.
Cross-region replication (for example Kafka MirrorMaker 2, a Kafka component that continuously copies topics from one cluster to another) copies each regional log to a second region asynchronously so a regional loss does not lose history.
flowchart LR
S[200 services] --> A[Node agent with disk buffer]
A --> K[Regional log keyed by entity ID]
K --> C[Chainer: hash chain + minute checkpoint]
C --> W[(WORM object storage, Parquet)]
C --> I[(Hot search index, 90 days)]
C --> N[Signing service, HSM-backed key]
K -. async replication .-> R[Log in second region]
Storage choices
| Tier | Holds | Technology shape | Why |
|---|---|---|---|
| Log | 7 days | Kafka or equivalent, replication factor 3 (every partition is kept as 3 identical copies on 3 different brokers, so losing 1 or 2 machines loses no data) | Replay buffer; primary logs alone are about 186 TB across the three regions (below); the fleet total including the cross-region replica is closer to 372 TB |
| Hot | ~90 days | Search or OLAP (online analytical processing) store (OpenSearch or ClickHouse: either a stock search engine or a stock analytical database will do this job) indexed by entity ID, actor, time | Sub-second investigation queries |
| Archive | 7 years | Parquet files (a compressed, columnar file format built for exactly this "store once, scan selectively later" pattern) partitioned by date/region/entity_bucket in object storage with a WORM lock | Cheap, immutable, still queryable with a SQL engine such as Trino (any engine that can run SQL over files in object storage works; Trino is just a widely used example) |
Reconciling the log-tier number with cross-region replication. "186 TB" (8.85 TB/day x 7 days x replication factor 3, rounded) is the storage for each region's primary log only, summed across all three regions. The cross-region replica described above (MirrorMaker copying each region's log to a second region) is a separate, additional set of topics living in another region's cluster, and if that replica is kept at the same replication factor 3 and the same 7-day retention as the primary, it costs the same again: another 8.85 TB/day x 7 days x 3 is about another 186 TB. So the log tier's real fleet-wide total is closer to 372 TB, not 186 TB. If that is too much, the cheaper option is to hold the replica at replication factor 1 (it is a DR copy of data the primary region also still has, not the only copy) or a shorter retention than 7 days, since its job is "replace a lost region," not "serve replays."
WORM (write once, read many) means the storage rejects overwrites and deletes until a retention date passes. On AWS this is S3 Object Lock in compliance mode, in which no user, including the account root user, can delete or shorten retention on a locked object version. That property is what makes the archive defensible, not just convenient.
Cryptographic integrity controls
The threat is an insider or attacker who edits or deletes audit rows to hide what they did. Controls, in order:
- Hash chain per partition. A single "chainer" consumer per partition computes
h_n = SHA-256(h_{n-1} || canonical_event_n), where||means concatenation (joining the two values end to end into one string before hashing) andcanonical_event_nis the event serialised the same fixed way every time (so the same event always hashes to the same bytes), and storesh_nwith the event. Changing, removing or reordering any event breaks every later hash. - Signed checkpoints. Every minute the chainer builds a Merkle root (a single hash summarising all events in that minute, with short proofs that any one event is included) over the partition heads and has it signed by a key held in an HSM (hardware security module) or a cloud KMS (key management service). The chainer never sees the private key; it can only request signatures, and every request is itself logged.
- Anchor outside the blast radius. Write each signed checkpoint to the WORM bucket in a separate account owned by the security team, and optionally publish the daily root to an external party (a partner or a public timestamping service). Now tampering requires compromising the pipeline, the signing key and the separate account.
- Verify continuously. A verifier job re-reads a random sample of archived files daily, recomputes the chain and compares it with the signed checkpoints. Integrity nobody checks is only a claim.
Resilience to partitions
A region that loses its link keeps working because every hop buffers: agent disk, then the regional log. Size the buffers for the longest outage you will tolerate. At about 34 MB/s per region, a 24-hour isolation means roughly 2.9 TB of backlog, which fits comfortably in a 7-day log. When the link heals, replication catches up; the hash chains are per region, so no cross-region coordination is needed to keep integrity.
How SREs operate restores and audit queries
- Audit query path. Investigators query the hot tier by entity and time range. For older data, the query engine prunes Parquet partitions by date and entity bucket, so a query for one user over one month reads a small slice, not petabytes. Every audit query is itself audit-logged (who looked at whose history).
- Restores. A restore is "re-hydrate a time range from the archive into a scratch index". The runbook: pick the range, copy Parquet files from WORM storage (reads are allowed; the lock only blocks writes), verify the hash chain and checkpoint signatures before loading, then index. Refuse to load a range that fails verification and page the security on-call.
- Drills. Run a restore drill monthly on a random historical day, and track two SLOs (service-level objectives): end-to-end ingest lag (for example p99, the 99th percentile, under 60 seconds from emit to hot index) and restore time for one day of one region.
- Key and retention operations. Rotate the checkpoint signing key yearly and keep old public keys for the full seven years, because a 2026 checkpoint must still verify in 2033. Expired data is removed by a lifecycle policy (an automated storage rule that deletes or moves objects once they cross an age threshold, so nobody has to remember to do it) after the lock lapses, never by hand, and legal holds override deletion.
Trade-offs and pitfalls
- Per-entity order vs throughput. Keying by entity costs you hot-partition handling. Keying by random ID balances load but forces a sort for every entity query; for an audit system, the entity key is the right default.
- Signing every event is tempting and wasteful: 100k signatures per second through an HSM is expensive and slow. Chain and sign checkpoints instead; tamper evidence is equivalent.
- Hot index is not the record. The index can be rebuilt and may be edited by operators; only the WORM archive plus signed checkpoints is authoritative. Say this explicitly or auditors will question every search result.
- Common miss: forgetting that the pipeline's own admin actions (retention changes, key rotation, replays) are audit events too, and must flow through the same pipeline.
You operate a multi-tenant control plane where API keys and control APIs are currently shared across all tenants. Design an architecture that minimizes the blast radius if a single tenant is compromised, and explain how you would migrate off the shared-key model and what that isolation costs you versus what it buys you.
Sample Answer
Direct answer
With one shared API key, the blast radius (everything a single compromised credential can reach) of any tenant compromise is every tenant, because the control plane cannot tell tenants apart. The fix is to make the tenant a property of the credential, not of the request: issue per-tenant, short-lived, narrowly scoped credentials; derive the tenant ID from the authenticated identity and enforce it on every control-plane call; encrypt each tenant's data under its own key; and group tenants into cells (independent copies of the control plane, each serving a subset of tenants) so that even an infrastructure-level compromise reaches one cell, not everyone. I would migrate by running per-tenant credentials alongside the shared key, attributing and shadow-enforcing first (running the new tenant check and logging what it would have blocked, without actually blocking anything yet), moving tenants in waves, and revoking the shared key last. The cost is more keys, more deployment units and more operational work; what it buys is turning "one leak exposes all tenants" into "one leak exposes one tenant".
Why the shared model is so dangerous
Today, a request says "act on tenant 42" and carries the shared key. The control plane checks the key (valid) and trusts the tenant ID in the request. So:
- Anyone holding the key can act as any tenant by changing one parameter.
- A compromise of tenant 42's automation (a leaked CI (continuous integration) pipeline secret, a malicious insider at that customer) is a compromise of all tenants.
- You cannot revoke access for one tenant without breaking every tenant, so in an incident you are forced to choose between leaving the attacker in and a platform-wide outage.
- Audit logs cannot say which tenant actually made a call, which makes incident scoping guesswork.
Target architecture
flowchart LR
T[Tenant workload] -->|per-tenant short-lived token| GW[API gateway]
GW -->|tenant ID from token| CP[Control plane in cell 3]
CP --> AZ{Tenant check<br/>resource.tenant == token.tenant}
AZ -->|match| DS[(Tenant data<br/>encrypted with tenant key)]
AZ -->|mismatch| DENY[Deny and alert]
CP --> KMS[Key service<br/>per-tenant keys]
Layer 1: identity per tenant
- Each tenant gets its own credentials, ideally exchanged for short-lived tokens (for example 15-minute tokens from a token service) so a stolen token expires quickly. Long-lived API keys, where unavoidable, are per tenant, hashed at rest, scoped to specific actions, and rotatable without touching other tenants.
- Scopes per credential: a CI deploy key can deploy, but cannot read secrets or manage users.
Layer 2: authorization bound to the tenant
- The control plane takes the tenant ID from the verified token only. Any tenant ID in a URL or body must match it, or the call is denied and logged as a cross-tenant attempt.
- Every data-access path filters by tenant at the lowest layer possible (row-level security in the database, meaning the database itself filters rows by tenant, or per-tenant schemas) so an application bug that forgets the filter still cannot return another tenant's rows.
Layer 3: per-tenant encryption keys
- Envelope encryption: each tenant's data is encrypted with data keys that are themselves encrypted by a tenant-specific master key in the key service. A policy on each master key allows its use only by that tenant's workloads.
- A bug that returns the wrong ciphertext, or a stolen backup, does not yield another tenant's plaintext, and crypto-shredding (deleting the tenant's master key) is a clean offboarding.
Layer 4: cells and namespace isolation
- Cell-based architecture: split the control plane into N independent cells, each with its own database, queues and credentials to the underlying infrastructure. A small routing layer maps tenant to cell. A compromise of a cell's service account (a non-human identity that infrastructure code authenticates as, distinct from a human user's login), or a bad deploy, is limited to that cell's tenants.
- Tenant workloads run in their own namespaces (Kubernetes' isolated groupings of resources within one cluster; or full separate accounts, for high-value tenants) with network policies (Kubernetes rules that control which pods may talk to which, enforced by the cluster network itself) that deny cross-namespace traffic by default.
- This is the classic tenancy spectrum: pool (all tenants share infrastructure, separated by identity and data filters), silo (each tenant gets dedicated infrastructure) and bridge (a mix, for example pooled compute with siloed data). I would use pool within a cell for most tenants and silo for the few tenants whose contracts or regulators require it.
Layer 5: detection and containment
- Alert on cross-tenant denials (any occurrence is suspicious), unusual call volumes per tenant, and tokens used from new networks.
- Automated quarantine: a single action revokes all of one tenant's tokens and keys and freezes its control-plane writes, without affecting any other tenant. This is the capability the shared key made impossible.
Migration plan
- Inventory and attribute. Log every call made with the shared key with enough context (source network, user agent (the identifying string a client sends describing what software made the request), workload identity, the tenant ID it claimed) to know who uses it and for what. Typical finding: a few internal tools legitimately act across tenants; these become separately scoped operator identities with their own audit.
- Issue per-tenant credentials in parallel. Both the shared key and the new credentials work. SDKs (the client libraries customers install to call your API) and docs switch to the new model.
- Shadow enforcement. For calls with new credentials, evaluate the tenant check and log "would deny" without blocking. Fix false positives (usually legitimate cross-tenant operator workflows).
- Enforce per tenant, in waves. Once a tenant is fully on its own credentials, turn on enforcement for that tenant and disable the shared key for that tenant ID. Start with internal and low-risk tenants, then the rest.
- Deadline and cutoff. Publish a date; the remaining users get direct help. On the date, stop accepting the shared key, then rotate and destroy it (assume it has already leaked; it has been in many hands).
- Introduce cells afterwards as a separate project. Moving tenants between cells is a data migration; doing it together with the credential change doubles the risk in each step.
What it costs versus what it buys
Worked example with 500 tenants split into 10 cells of 50:
| Question | Shared key | Per-tenant credentials | Per-tenant credentials + 10 cells |
|---|---|---|---|
| Tenants exposed by one tenant's leaked credential | 500 | 1 | 1 |
| Tenants exposed by one compromised control-plane service account | 500 | 500 | 50 |
| Tenants affected by a bad deploy | 500 | 500 | 50 (if deploys roll cell by cell) |
| Credentials to manage | 1 | 500+ | 500+ |
| Control-plane deployments to operate | 1 | 1 | 10 |
Costs: credential lifecycle for hundreds of tenants (issuance, rotation, revocation, support tickets when a customer loses a key); per-tenant keys in the key service (per-key and per-request charges scale with tenant count); a fixed baseline cost for every cell (each cell's database and queues cost money even when mostly idle); deploy pipelines that must roll across cells; cross-cell features (global search, billing) get harder. Benefits: a single customer's compromise is contained to that customer; containment is a one-tenant action instead of a platform-wide outage; audit logs can scope an incident precisely; enterprise customers' security questionnaires get concrete answers.
My recommendation is per-tenant identity, tenant-bound authorization and per-tenant keys for everyone now, since they are cheap relative to the risk they remove, and cells once the tenant count or the value of the largest tenants makes a platform-wide incident unaffordable. Full silo per tenant only where a contract or regulator requires it, because at 500 tenants the fixed per-silo cost multiplies by 500.
Trade-offs and pitfalls
- Per-tenant keys with a shared admin path (one super-credential used by support tooling) recreates the original problem. Operator access must be scoped, time-bound and approved.
- Trusting the tenant ID in the request body after the migration is the most common way this design quietly fails.
- Cells without cell-aware deploys give no deploy-safety benefit; roll changes one cell at a time.
- Noisy neighbours (tenants that consume so much shared capacity, CPU, bandwidth, connections, that they degrade service for others on the same infrastructure) are an isolation problem too: without per-tenant rate limits, one compromised tenant can still degrade others even if it cannot read their data.
You need a secure leader election and state replication scheme for a global control plane spanning five regions, where some nodes may behave maliciously (Byzantine). Choose an algorithm (e.g., PBFT, HotStuff), justify it for this use case, and describe the authentication and cryptographic protections, quorum sizes and performance implications, and the operational monitoring and recovery procedures to detect and handle malicious nodes.
Sample Answer
Direct answer
I would run a HotStuff-family protocol (the lineage behind DiemBFT, the consensus protocol originally built for Meta's Diem payments project, which uses a rotating leader and linear-cost leader changes) on 10 replicas, 2 per region, each operated in a separately administered failure domain. Ten replicas tolerate f=3 Byzantine faults with quorums of 7, which covers a whole region going dark (2 crashed replicas) plus one malicious replica at the same time. Every vote is signed with a per-replica key held in an HSM (hardware security module), votes are aggregated into quorum certificates, a quorum certificate being a single compact proof that at least 2f+1 replicas voted for the same thing, so nobody has to carry all their individual signatures around separately, transport is mTLS (mutual TLS), and equivocation (signing two conflicting votes) is automatically turned into evidence that ejects the replica. The price is roughly half a second of commit latency; that is per commit, not per second of throughput, because commits pipeline (explained below), so a control plane that changes configuration tens of times per second can still keep up.
Why BFT here, and why HotStuff over PBFT
The question stipulates malicious nodes, so crash-fault consensus (Raft, Paxos) is out: a single lying Raft leader can replicate forged entries. Both PBFT and HotStuff organise time into views: a view is one leader's term, during which that replica proposes and the others vote. A view change is the handoff from one leader to the next, whether that is routine (HotStuff) or triggered by a timeout on a suspected-bad leader (PBFT). Among BFT protocols:
| PBFT (Practical Byzantine Fault Tolerance) | HotStuff family | |
|---|---|---|
| Normal-case messages per decision (n = 10, idealised count) | pre-prepare 9 + prepare 81 + commit 90 = 180 (all-to-all) | 3 voting phases x 18 + decide 9 = 63 (leader-to-all, all-to-leader) |
| Leader change (view change) | Heavy: each replica sends proofs of what it prepared; message size grows with n, so about O(n^3) bits in total (the total bits sent grows roughly with the cube of the replica count, not just with n itself) | Linear: the new leader carries one quorum certificate |
| Leader rotation | Only on suspicion of failure | Every view by design |
| Commit latency | Lower (about 1.5 quorum round trips) | Higher (about 3.5 quorum round trips; two-phase variants such as HotStuff-2 reduce this) |
Justification for this use case: a malicious leader is the main performance attack in BFT. It stays within the rules while being slow or dropping selected requests, so no one can prove misbehaviour. PBFT keeps a leader until replicas time out on it and then pays an expensive view change; HotStuff rotates leaders every view and makes the change cheap, so a bad leader costs one view, not an outage. At 10 replicas the message count is not the deciding factor; the cheap, routine leader change is. What would flip it: a latency-critical path (sub-100 ms commits) with a stable, trusted-hardware leader, where PBFT's fewer round trips win.
Quorum sizes
For n replicas tolerating f Byzantine faults you need n≥3f+1, and quorums of 2f+1 guarantee any two quorums share at least f+1 replicas, so at least one honest replica is in both and blocks conflicting decisions:
n=10overlap of two quorums⇒f=⌊(10−1)/3⌋=3,q=2f+1=7≥2q−n=14−10=4=f+1Why not one replica per region (n = 5)? Then f=1 and the quorum is 4 of 5: losing one region uses the entire fault budget, and a single malicious node during a regional outage breaks liveness, meaning the system stops making progress (no decision can ever reach quorum), as opposed to a safety failure where it makes a wrong decision. Why not 7 (f = 2)? With 2 replicas in some regions, one regional outage again consumes the whole budget. Ten, 2 per region, is the smallest layout that survives "one region down plus one attacker".
Performance implications (illustrative numbers)
Assume illustrative round-trip times from the current leader: about 1 ms to its regional peer, then 70, 90, 140 and 200 ms to the other four regions. The leader needs 7 votes: 2 from its own region, 2 at 70 ms, 2 at 90 ms, and the 7th from the 140 ms region. So one quorum round trip, the time for the leader to broadcast and hear back from enough replicas to reach quorum, is about 140 ms.
Where the phase multipliers come from: the message-count row above already showed each protocol's phase structure. Basic HotStuff runs three sequential voting phases (prepare, pre-commit, commit), each of which is a full quorum round trip because the leader must broadcast and then wait for 2f+1 signed votes back before moving on, plus a final decide phase where the leader just broadcasts the completed quorum certificate and does not wait for any reply, so that phase costs about half a round trip (message travels out; no return trip is needed): 3×1+1×0.5=3.5 quorum round trips. PBFT's pre-prepare is the leader's own proposal and is not itself a voted round; it only starts the clock. The prepare phase is one full quorum round trip. The commit phase, however, can complete for the client as soon as 2f+1 commit votes are in, and because commit votes start arriving while the tail of the prepare round trip is still in flight, in the common case the two phases overlap into roughly one and a half round trips rather than two:
HotStuff commit≈3×140+0.5×140=490 ms,PBFT≈1.5×140=210 msBoth multipliers are illustrative, consistent with the phase counts above, not a formal proof; the qualitative point, that HotStuff pays roughly twice the round trips of PBFT per commit, is what drives the design trade-off below.
Throughput is decoupled from per-commit latency by pipelining: chained HotStuff starts the next proposal while the previous one is still collecting votes, so the 490 ms figure is the time for one commit to complete, not a cap on how many commits per second the system can sustain. This is an optimisation layered on top of the core protocol, not something the correctness argument depends on. Batching many control-plane writes into one proposal further raises effective throughput. Signature verification is the CPU cost; aggregating votes into one threshold signature (a single signature that only a quorum, not any individual replica, can produce, so it proves "2f+1 replicas signed this" without listing every signature separately) or aggregate signature (BLS, Boneh-Lynn-Shacham, signatures allow this) keeps quorum certificates compact. Put the leader-rotation schedule in region order so leaders rotate toward users rather than always paying the worst-case geometry.
Authentication and cryptographic protections
- Per-replica identity: each replica has its own signing key, generated in and never exported from an HSM or TPM (trusted platform module), and a certificate from a CA (certificate authority) dedicated to the control plane. No shared keys: a shared key lets one compromised node speak for all of them.
- Signed votes and proposals: every proposal and vote carries the view number, a block hash (a fingerprint of the exact proposed state, so a vote is provably for one specific proposal and not some other one with the same view number) and the signer's ID, so they cannot be replayed into a different view.
- Transport: mTLS between replicas prevents outsiders from injecting traffic; it does not replace vote signatures, because an insider has a valid TLS certificate.
- Client requests signed by the submitting operator or service, and authorised by policy that is itself part of the replicated state, so a malicious replica cannot invent requests.
- Membership changes go through consensus, and require the same 7-of-10 quorum, so an attacker cannot add Sybil replicas (fake identities) to grow past f.
- Independent domains: different operators, cloud accounts and ideally deployment pipelines per region pair. If one CI/CD (continuous integration and delivery) pipeline can push code to all 10, f=3 is fiction.
Monitoring: detecting malicious nodes
| Signal | What it catches |
|---|---|
| Equivocation proofs (two valid signatures from one replica on conflicting blocks in one view) | Provable Byzantine behaviour; auto-open an ejection proposal |
| Per-replica vote participation and vote latency | Selective silence, slow-voting attacks |
| Per-leader view success rate and timeouts | Leaders that stall or censor; feed into leader reputation so repeat offenders are skipped |
| Invalid-signature or malformed-message counts by sender | Forgery attempts, compromised keys |
| State-hash comparison across replicas at each checkpoint (a periodic, quorum-signed snapshot of the replicated state that later recovery and forensics can trust, taken every so many decisions rather than after every single one) | Divergent state (a replica applying different results) |
Treat attributable evidence (equivocation, invalid signatures) differently from suspicion (slowness). Evidence justifies automatic ejection; suspicion only lowers a replica's leader priority and pages a human, because an attacker could otherwise induce slowness in honest nodes to get them ejected.
Recovery procedures
- Eject: a membership-change proposal removes the replica and its key; it needs a 7-of-10 quorum. Now n=9 and f drops to 2, so restore the count quickly.
- Forensics before reuse: snapshot the ejected host; assume its key is compromised, revoke its certificate and never re-admit that key.
- Rebuild: provision a fresh replica from a clean image in the same failure domain, generate a new HSM key, and have it state-sync from a checkpoint signed by 2f+1 replicas, so it cannot be fed a forged snapshot by one bad peer.
- Re-admit via another membership change, back to n=10.
- If more than f replicas were compromised, BFT's guarantees are gone: freeze writes, pick the last checkpoint certificate you trust, rotate every replica key, and rebuild from that checkpoint. Rehearse this, because it is the scenario the protocol cannot handle for you.
Trade-offs and pitfalls
- Common-mode compromise (one bug, one image, one admin team) defeats any replica count; diversity is a design requirement, not polish.
- Latency budget: half a second per commit is fine for configuration and policy; do not put per-request data-plane decisions through this path. The data plane reads committed state locally.
- Cost of f = 3: 10 replicas plus HSMs across five regions; if the real threat is one compromised node, not region-plus-attacker, 7 replicas is a defensible cheaper choice, and saying so shows judgement.
Service A depends on AuthService B to authorize requests. B starts showing increased latency and intermittent errors after a deployment. As the on-call SRE, propose a strategy for A to keep handling requests without opening a security hole: should A deny by default or fail open, and how would you decide and implement the default behavior based on SLOs and risk?
Sample Answer
Direct answer
The default is fail closed: if Service A cannot get an authorization decision, it denies. But fail-closed does not have to mean "every request fails". A should serve recently cached decisions for a bounded time (sometimes called "fail static": neither blindly allowing everything like fail open, nor blindly denying everything like plain fail closed, but serving the last known-good answer for a bounded time and only denying once even that runs out; it behaves like a variant of fail closed because a cache miss still denies), deny on a cache miss, and classify routes so that only a small, explicitly approved set of low-risk read paths may fail open. As the on-call engineer, the first action is operational rather than architectural: roll back B's deployment, because it is the change that caused the problem. The fail-open or fail-closed choice is decided in advance, per route, from the cost of a wrong allow versus the cost of a wrong deny, and implemented in configuration so on-call never makes it under pressure.
Terms
- Fail open: when the dependency fails, allow the request. Preserves availability; risks unauthorized access.
- Fail closed (deny by default): when the dependency fails, deny. Preserves security; costs availability.
- SLO (service-level objective): the reliability target, for example 99.9% of requests succeed over 30 days. The permitted failures are the error budget.
- Circuit breaker: a client-side switch that stops calling a failing dependency for a while, so a struggling service is not overwhelmed by retries. The naming borrows from electrical circuits and is easy to misread: "open" means broken, no current (calls) flows through, so an open circuit is the one that has stopped calling B; "closed" means current flows normally, calls go through as usual. A third state, often called half-open, periodically lets one test call through to check whether B has recovered, without yet trusting it fully.
First 15 minutes on call
- Correlate and roll back. B's errors started after a deploy; roll B back. That fixes the cause; everything below limits the damage while it happens.
- Check A's behaviour is the designed one: are timeouts firing, is the circuit open, is the cache serving?
- Watch both sides of the trade: A's error rate (availability) and the rate of cached or degraded allows (security exposure).
The decision framework
For each route, compare the expected cost of each failure mode:
| Route | Wrong allow means | Wrong deny means | Policy on auth failure |
|---|---|---|---|
| Transfer money, change permissions, export data | Fraud, breach, regulatory incident | User retries later | Fail closed, no cache (or cache of at most a few seconds) |
| Read own account data | Minor, user already authenticated | Visible outage | Fail closed with cached decisions, e.g. up to 5 minutes stale |
| Public or catalog content already visible to logged-in users | Almost none | Outage of the main product | Fail open allowed, with explicit product and security sign-off, logged |
The rule of thumb: fail open only where the data would be acceptable to show any authenticated user anyway. If you cannot say that out loud, the route fails closed.
Why the cache changes the answer: error-budget arithmetic
Suppose A has a 99.9% availability SLO over 30 days: 30 x 24 x 60 = 43,200 minutes, of which 0.1% = 43.2 minutes of full outage is the budget. B returns errors on 5% of calls for 2 hours (120 minutes):
- Fail closed, no cache: 5% of A's requests fail for 120 minutes, equivalent to 0.05 x 120 = 6 minutes of full outage, which is 6 / 43.2, about 14% of the month's budget.
- Fail closed with a decision cache at 90% hit rate: only misses call B, so 0.05 x 0.10 = 0.5% of requests fail, equivalent to 0.005 x 120 = 0.6 minutes, about 1.4% of the budget.
The cache buys most of the availability that fail-open would, without allowing anything that was not already allowed recently. That is why "fail closed plus bounded cache" is the default, and fail-open is the exception.
Implementation in A
flowchart TD
R[Request] --> C{Fresh cache hit?}
C -->|yes| D[Use cached decision]
C -->|no| BR{Circuit open?}
BR -->|no| CALL[Call B with 150 ms timeout, 1 retry]
CALL -->|decision| D2[Use and cache it]
CALL -->|error or timeout| ST{Stale entry within max staleness?}
BR -->|yes| ST
ST -->|yes| D3[Use stale decision, log degraded]
ST -->|no| POL{Route fails open?}
POL -->|yes, approved| AL[Allow, log and alert]
POL -->|no| DENY[Deny with 503]
- Timeouts: a tight timeout (for example 150 ms against B's normal p99, 99th-percentile latency, of 40 ms) so a slow B does not exhaust A's threads. Slowness is a failure mode, not just errors.
- Retries: at most one, with jittered backoff (randomised delay). Unbounded retries turn B's partial failure into a total one.
- Circuit breaker: open when B's error rate exceeds, say, 20% over 10 seconds; while open, go straight to the cache path; probe periodically to close: at intervals (for example every 30 seconds) let a single test call through in this half-open state; if it succeeds, close the circuit and resume calling B normally, if it fails, stay open and try again next interval.
- Two-tier cache TTL: a soft TTL (for example 30 seconds) after which A refreshes normally, and a hard maximum staleness per route (for example 5 minutes) that A may use only while B is failing. Cached denies are kept short so a new grant is not blocked.
- Revocations still apply: A subscribes to a revocation stream and evicts affected entries even while B is down; stale-serving must never resurrect a revoked permission.
- Return 503, not 403, on an auth-dependency failure so clients retry later and dashboards do not confuse an outage with real denials.
- Configuration, not code: the per-route policy and max staleness live in reviewed config, with a pre-approved, time-boxed "degraded mode" switch that on-call can flip under a documented runbook.
Longer-term: remove the synchronous dependency
A per-request network call to B is the root of the dilemma. Moving common decisions to a local policy engine fed by policy bundles from B, pre-computed, versioned packages of policy rules and data that B publishes periodically for A to load and evaluate locally, means B's outage affects only bundle freshness, not live decisions, and the fail-open or fail-closed question arises far less often.
Trade-offs and pitfalls
- Fail-open as a quiet default is the classic vulnerability: an attacker who can degrade B (a flood of expensive requests) gains access to A. Every fail-open route must be explicit, logged and alerted.
- Stale allows have a bounded risk, not zero. Max staleness is the knob; tie it to how quickly revocations must take effect for that route.
- Retry storms during B's recovery can knock it over again; keep the circuit breaker's probing gradual.
- Common wrong turn: deciding the policy during the incident. The decision belongs in the design review, with the numbers above.
Why are tamper-evident and append-only audit logs important for a distributed system? As an SRE, describe how you would design audit logging across services and regions so logs can't be silently altered or deleted, how you'd keep events correctly ordered per entity, and what operational controls you would put in place to preserve logs during an incident.
Sample Answer
Direct answer
Audit logs are the record you use to answer "who did what, when" after something goes wrong. That makes them the first thing an attacker (or a panicking insider) wants to edit. Append-only means records can be added but never changed; tamper-evident means that if someone does change or delete a record, verification detects it. Across services and regions, the design is: each service writes events with a per-entity sequence number to a replicated log (an ordered sequence of events copied to multiple machines, so no single machine failure loses it and no single operator holds the only copy), events are chained by hashes, the chain head is regularly anchored somewhere the writers cannot modify, and the storage itself enforces retention that no operator can override.
Why it matters in a distributed system
- Forensics: after a breach you must reconstruct what happened across many services. If the log can be silently edited, you cannot trust any conclusion.
- Compliance: standards such as PCI DSS (Payment Card Industry Data Security Standard) and SOC 2 (a widely used security-controls audit report) require audit trails protected from modification.
- Distributed makes it harder: many writers, many regions, clocks that disagree, and many operators with access to some part of the pipeline.
Design
1. Making changes detectable: hash chains
Each record stores the hash of the previous record, so changing any record changes every hash after it. This short program shows what a chain catches and what it does not:
import hashlib, json
GENESIS = "0" * 64 # placeholder "previous hash" used only for the first entry, which has no real predecessor
def entry_hash(prev_hash, event):
body = json.dumps(event, sort_keys=True, separators=(",", ":"))
return hashlib.sha256((prev_hash + body).encode()).hexdigest()
def append(log, event):
prev = log[-1]["hash"] if log else GENESIS
log.append({"event": event, "prev": prev, "hash": entry_hash(prev, event)})
def verify(log):
prev = GENESIS
for i, rec in enumerate(log):
if rec["prev"] != prev or rec["hash"] != entry_hash(prev, rec["event"]):
return f"broken at entry {i}"
prev = rec["hash"]
return "ok"
log = []
append(log, {"seq": 1, "actor": "alice", "action": "role.grant", "target": "bob:admin"})
append(log, {"seq": 2, "actor": "bob", "action": "export", "target": "customers.csv"})
append(log, {"seq": 3, "actor": "alice", "action": "role.revoke", "target": "bob:admin"})
head = log[-1]["hash"]
print("clean log:", verify(log), "| head", head[:12])
# 1) edit an event in place
log[1]["event"]["target"] = "nothing.csv"
print("after edit:", verify(log))
log[1]["event"]["target"] = "customers.csv"
# 2) delete the incriminating entry and re-link the next one
forged = [log[0], dict(log[2], prev=log[0]["hash"])]
print("after delete + relink:", verify(forged))
# 3) delete it and recompute every later hash: the chain verifies again...
rebuilt = []
for rec in (log[0], log[2]):
append(rebuilt, rec["event"])
print("after full rewrite:", verify(rebuilt), "| head", rebuilt[-1]["hash"][:12])
# ...which is why the head hash must be anchored somewhere the writer cannot change
print("head matches anchored copy:", rebuilt[-1]["hash"] == head)
clean log: ok | head 1537d687119a
after edit: broken at entry 1
after delete + relink: broken at entry 1
after full rewrite: ok | head 8cf5f38f565b
head matches anchored copy: False
The third case is the important lesson: a hash chain alone does not stop someone with write access from rebuilding it. It only becomes tamper-evident when the head hash is anchored: copied every few minutes to a place the log writers cannot change (a separate account's locked storage, another organization, or a public transparency log, a shared append-only log, such as the one behind Certificate Transparency, that many independent parties can audit). This is a scale optimisation, not a change to the core idea above: instead of anchoring every single event's hash (expensive at high volume), events are batched into a Merkle tree (a tree of hashes whose single root commits to every event in the batch) and only that one root is anchored. A Merkle proof then shows a specific event was in a batch using about log2(n) hashes, which is 20 hashes for a batch of one million events, instead of handing over all one million. If your system's volume is low enough to anchor every event's hash directly, you do not need this step at all.
2. Making changes impossible at the storage layer
- Write to storage that enforces immutability, for example Amazon S3 Object Lock in compliance mode, where no user, including the account root, can delete or overwrite an object before its retention date.
- Put the audit store in a separate account owned by the security team, so compromising a production account does not grant delete rights.
- Replicate to a second region so losing one region does not lose the trail.
3. Keeping events ordered per entity
Wall clocks across servers drift by milliseconds or more, so timestamps alone cannot order two events that happened close together. Instead:
- Route all events for one entity (a user, an account, a resource) through one partition of the log. A partition is one independently ordered slice of the log; the log is split into many partitions (think separate lanes) so it can scale, and every event for a given entity ID is routed, by that ID, to the same lane every time. Within a partition, order is total: every event in that one lane has an unambiguous before-and-after position. Order is not directly comparable across two different partitions.
- The writer for that entity assigns a monotonic sequence number (1, 2, 3...). A gap reveals a missing event; a duplicate reveals a replay.
- Keep the wall-clock timestamp for humans, but use the sequence number for ordering. For causality across entities, a hybrid logical clock (a timestamp that never goes backwards and carries causal order: if event X caused event Y, Y's clock value is guaranteed to be greater than X's, so a reader can tell cause from effect even when the events sit in different partitions) is the usual addition.
In the example, seq 1, 2, 3 show that Bob's export happened while he had admin, even if the servers' clocks disagreed.
4. Operational controls during an incident
- Separation of duties: the people responding to an incident cannot delete or modify audit data; audit-store admin is a different role with its own approval.
- Legal hold: a flag placed on specific records that overrides the normal retention schedule, so declaring an incident and applying a hold guarantees those logs cannot be deleted, even by an expiry job, until the hold is explicitly lifted.
- Protect the pipeline, not just the store: agents buffer locally if the pipeline is down, and a gap in a service's sequence numbers raises an alert. An attacker's first move is often to stop logging, so "a service stopped sending audit events" is itself a high-priority alert.
- Continuous verification: a job re-verifies chains against anchored heads and pages on any mismatch.
Trade-offs and pitfalls
- Immutability versus data-protection deletion rights: you cannot delete a person's data from a compliance-locked log. Log IDs rather than personal data, or encrypt personal fields with a per-person key you can destroy.
- Per-entity ordering is cheap; global ordering is expensive. A single global sequence becomes a throughput bottleneck. Order per entity and accept that cross-entity order is approximate.
- Common wrong turn: relying on "only admins can delete". The threat model includes admins.
Unlock Full Question Bank
Get access to all 23 Distributed Systems Security and Trust interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.