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 are reviewing the security posture of a shared caching layer (e.g. Redis) and message broker (e.g. Kafka) used by many services on a distributed platform. Walk through the security threats this kind of shared infrastructure is exposed to, and how you would design mitigations at the architecture level for each one you identify.
Sample Answer
Direct answer
A shared cache or message broker is a confused deputy waiting to happen. A confused deputy is a program that has more authority than the party it is currently acting for, and gets tricked into misusing that authority on that party's behalf; here, that means: dozens of services trust the data they read from it, yet any one of those services (or anything that steals its credentials) can usually write to it. The threats that matter are cross-tenant reads, poisoning (injecting or overwriting data other services trust), replay of old messages, denial of service by one noisy client, and plaintext exposure in transit, at rest and in backups. The architecture-level fix is to give every service its own identity with a namespace it alone may write to, authenticate every connection, sign or validate what crosses the shared component, and size the blast radius, how much damage one compromised component or credential can do, by deciding which tenants share a cluster at all.
Why "shared" changes the threat model
A cache inside one service is protected by that service's own boundary. A shared cache or broker is different in two ways:
- Trust is transitive. If the checkout service reads
price:sku-42from Redis and believes it, then anyone who canSET price:sku-42can change prices. The cache has become part of checkout's trusted computing base (the set of components a service implicitly relies on to behave correctly; anything in it can undermine the service's security if it is compromised), but it is administered for everyone. - Credentials are usually coarse. The classic deployment is one Redis password or one Kafka (a distributed log-based message broker: producers append messages to topics, and consumers read them back, usually in place of, or alongside, Redis) principal baked into every service's config. Compromise any one of 80 services and you hold write access to all 80 services' state.
A useful term here: blast radius means how much damage one compromised component or credential can do. Most of the mitigations below are ways of shrinking it.
Threat by threat
| Threat | How it happens on a shared component | Architecture-level mitigation |
|---|---|---|
| Unauthorized read / cross-tenant access | Shared credential; key or topic naming is only a convention; KEYS * or a wildcard consumer subscription reads everyone's data | One principal per service; Redis ACLs restricting each user to a key prefix; Kafka ACLs on prefixed topic names and consumer groups; default deny (Kafka must not run with "allow everyone if no ACL found") |
| Cache poisoning / message injection | A compromised or buggy producer writes a value another service trusts (a price, a session, a feature flag); a rogue producer publishes to a topic a payment consumer processes | Write permission only for the owning service; consumers validate against a schema, using a schema registry (a central service that stores the agreed message format so producers and consumers can check they agree on it) for Avro or Protobuf (compact, schema-based message-encoding formats, as opposed to free-form JSON); for high-value messages, the producer signs the payload so consumers verify origin independent of the broker |
| Replay | An attacker (or an operator resetting consumer offsets, the per-consumer bookmark of how far into a topic it has already read) re-delivers a captured "refund issued" or "grant role" message | Every message carries a unique ID and an issue timestamp; consumers keep a de-duplication store keyed by message ID for at least the replay window and reject messages older than a freshness bound; handlers are idempotent (applying the same message twice has the same effect as once) |
| Topic / key-space hijacking | A service creates a topic or key namespace another team expected to own, or rebinds a consumer group (a named set of consumers that share the work of reading a topic, each partition going to only one member) and steals partitions (the ordered, independently-read shards a Kafka topic is split into) | Topic and consumer-group creation is a platform operation, not a client permission; ACLs on Create, and on consumer groups, not just topics |
| Sensitive data at rest | Session tokens, personal data or access tokens sit in Redis memory, RDB/AOF persistence files (Redis's two on-disk formats: RDB is a periodic full snapshot, AOF is a log of every write, either of which lets Redis survive a restart), Kafka log segments, and backups for their full retention | Do not cache what you cannot afford to leak: cache references or tokenized values; encrypt persistence volumes and backups; for regulated fields, encrypt at the application layer with a per-tenant key so the broker only ever holds ciphertext |
| Eavesdropping in transit | Plaintext Redis protocol or Kafka PLAINTEXT listeners inside a "trusted" network | TLS on every listener, including replication and inter-broker traffic; client certificates or SASL (Simple Authentication and Security Layer, Kafka's pluggable auth framework) for identity |
| Dangerous admin commands | A client can run FLUSHALL, CONFIG SET, DEBUG, or Kafka DeleteTopics / AlterConfigs | Command-level ACLs: application users get data commands only; admin commands belong to a separate, audited operator identity |
| Noisy neighbour / denial of service | Noisy neighbour means one tenant's usage degrades another's, purely by sharing infrastructure, with no compromise needed: one service's hot key, huge values, or runaway producer exhausts memory, network or partitions and takes out every other service | Per-principal quotas (Kafka supports produce/fetch byte-rate and request-rate quotas per user or client ID); maxmemory and eviction policy chosen per cluster; for critical tenants, a separate cluster |
| Stale security state | A revoked service's credential still has a live, authenticated connection | Short-lived credentials, and on revocation actively kill sessions (CLIENT KILL USER, or rotate and drop the principal) instead of waiting for reconnect |
Worked example: prefix isolation you can run
The single highest-value change is replacing the shared password with per-service ACL users. This runs against a stock Redis 7 container:
docker run -d --name cache-demo redis:7-alpine
docker exec -i cache-demo sh <<'EOF'
# ACL SETUSER <name> <rules...>. 'on' enables the user (a new user starts disabled).
# '>orders-pw' sets that password (the '>' means "add this password"; '<' would remove one).
redis-cli ACL SETUSER orders-svc on '>orders-pw' '~orders:*' '+get' '+set' '+del'
redis-cli ACL SETUSER billing-svc on '>billing-pw' '~billing:*' '+get' '+set'
redis-cli --user billing-svc --pass billing-pw --no-auth-warning SET billing:invoice:77 paid
redis-cli --user orders-svc --pass orders-pw --no-auth-warning SET orders:1001 pending
redis-cli --user orders-svc --pass orders-pw --no-auth-warning GET billing:invoice:77
redis-cli --user orders-svc --pass orders-pw --no-auth-warning KEYS '*'
redis-cli --user orders-svc --pass orders-pw --no-auth-warning FLUSHALL
redis-cli --user orders-svc --pass orders-pw --no-auth-warning GET orders:1001
EOF
docker rm -f cache-demo
Output (executed on Redis 7.4):
OK
OK
OK
OK
NOPERM No permissions to access a key
NOPERM User orders-svc has no permissions to run the 'keys' command
NOPERM User orders-svc has no permissions to run the 'flushall' command
pending
Reading it: on turns the new user on (a freshly created ACL user starts disabled, on purpose, so an incomplete definition never silently grants access); >orders-pw sets its password; ~orders:* confines the orders service to its own key prefix, so it cannot read the billing invoice; +get +set +del is a command allow-list, so it cannot enumerate the key space or wipe the database. In production you would also disable the default user, load users from an ACL file managed by your secrets pipeline, and put TLS on the port. (Passwords on the command line are for the demo only.)
The Kafka equivalent, expressed as the actual ACL you would create with Kafka's kafka-acls tool:
kafka-acls --bootstrap-server localhost:9092 --add \
--allow-principal User:orders-svc \
--operation Write --topic orders. --resource-pattern-type prefixed
kafka-acls --bootstrap-server localhost:9092 --add \
--allow-principal User:orders-svc \
--operation Read --group orders-svc-group
This grants orders-svc Write on any topic whose name starts with orders. and Read on its own consumer group, and nothing at all on billing. topics, the same prefix-isolation shape as the Redis ACLs above.
Choosing the isolation level: commit to a tiered model
Namespacing inside one cluster (logical isolation) stops reads and writes across tenants but not resource starvation: one service can still exhaust the shared Redis's memory. So:
- Default: pooled cluster, per-service identity, prefix ACLs, quotas. Right for the long tail of internal services with ordinary data.
- Dedicated cluster for anything whose poisoning or outage is a business incident on its own: sessions, payment events, authorization caches. The cost is more clusters to operate; the gain is that a noisy or compromised neighbour physically cannot touch it.
- Per-tenant encryption keys where customers are the tenants and regulation or contracts require it, so deleting a tenant's key renders their residual data in logs and backups unreadable (sometimes called crypto-shredding).
What would flip the default toward dedicated clusters for everyone: a small number of services with very different trust levels (for example, a third-party-code plugin runner sharing a cache with the payments service). Mixing trust levels in one pool is the real risk, not sharing as such.
Trade-offs and pitfalls
- ACLs without identities are theatre. If all 80 services still load the same ACL user from a shared config file, prefix ACLs isolate nothing. The identity must be per service and delivered by the secrets system.
- Signing everything is expensive and rarely needed. Broker ACLs already stop outsiders; payload signatures earn their cost only where a consumer must not trust other legitimate producers (financial events, authorization changes).
- Replay protection needs state. A de-duplication window of 24 hours at 5,000 messages per second is 5,000 x 86,400 = 432 million IDs; at roughly 16 bytes per ID that is about 6.9 GB before overhead, so bound the window to what an attacker could realistically replay and pair it with a timestamp freshness check.
- Audit the shared component itself. Log authentication failures, ACL denials and admin commands, and alert on them; a burst of
NOPERMfrom one service is either a bug or a compromise. - Common wrong turn: relying on network segmentation ("it is only reachable inside the VPC (Virtual Private Cloud)"). Every service inside that network is exactly the population the threats above come from.
Stateless JWTs are widely used on your platform. You need a way to immediately invalidate a compromised token, at scale, without giving up the performance benefits that made you choose JWTs in the first place. Design a revocation system that balances correctness and performance, and explain how SREs would operate, monitor, and scale it.
Sample Answer
Direct answer
A JWT (JSON Web Token) is fast because any service can validate it locally with a public key, without calling the issuer. Revocation re-introduces shared state, so the design goal is to keep that state tiny, local and pushed, not queried. My design: short-lived access tokens (5 minutes) so the revocation list only has to remember tokens for 5 minutes, a denylist of revoked token IDs plus per-user "revoked before" timestamps that the auth service pushes to an in-memory copy in every gateway, and a propagation SLO (service-level objective) of a couple of seconds, with a fail-closed rule for sensitive routes when a gateway's copy goes stale. Long-lived sessions live in refresh tokens, which are always checked against the auth server's database, so revoking a session is authoritative there.
Why this is hard
- Stateless validation: the gateway checks the signature and the
exp(expiry) claim. Nothing in that check can learn that the token was stolen an hour ago. - "Immediately" needs a number. In a distributed system it means "within a bounded, monitored delay". I would commit to p99 (99th percentile) revoke-to-enforced under 2 seconds and alert above 5.
- Performance budget: the reason for JWTs is avoiding a network call per request. A design that calls a central revocation service on every request has quietly turned the JWT into an opaque token with extra steps.
The design
1. Bound the problem with token lifetime
Access tokens live 5 minutes; a refresh token (revocable, stored server-side) mints new ones. Now a revoked entry only needs to be remembered until the revoked token's own exp passes, after which the ordinary expiry check rejects it. The denylist's size is "revocations per 5 minutes", not "revocations ever".
2. Two kinds of revocation entry
| Entry | Key | Use | Removed when |
|---|---|---|---|
| Token denylist | jti (the JWT ID claim, unique per token) | One stolen token | Token's exp passes |
| Subject cutoff ("token version") | sub (user or service ID) plus a revoked_before timestamp | "Log this user out everywhere", password reset, compromised account | Max token lifetime after the cutoff |
A gateway rejects a token if its jti is denylisted or its iat (issued-at) is earlier than the subject's cutoff. The cutoff entry kills every outstanding token for a user with one record, which is what incident response usually needs.
3. Push, don't pull
sequenceDiagram
participant Admin as Security tool
participant Auth as Auth service
participant Bus as Revocation stream
participant GW as Gateway (in-memory set)
Admin->>Auth: revoke jti or subject
Auth->>Auth: write to durable store, assign sequence number
Auth->>Bus: publish entry with sequence
Bus->>GW: deliver within ~1 s
GW->>GW: add to local set, record last sequence
Note over GW: every request: signature + exp + local set lookup
Every gateway holds the full active set in memory and subscribes to a stream (Kafka, NATS, a lightweight open-source messaging system, or Redis Streams; any of the three does this job). Entries carry a monotonically increasing sequence number, so a gateway knows if it missed one and re-syncs from a snapshot. The per-request cost is a hash-set lookup, which keeps JWT performance intact.
4. Optional: a Bloom filter when the set is big
If revocations get large (for example a mass logout of a million users), ship a Bloom filter: a compact bit array that answers "definitely not revoked" or "possibly revoked". It has false positives but no false negatives. On "possibly", the gateway asks the authoritative store. Sizing, with n entries and false-positive rate p:
m=−(ln2)2nlnpwhere m is the number of bits in the filter and ln is the natural logarithm (log base e). For n=106 and p=10−4: ln(10−4)≈−9.21, so m≈(106×9.21)/0.4805≈19.2 million bits, roughly 2.4 MB. The number of hash functions that minimises false positives for a given m and n is k=(m/n)ln2: here m/n≈19.2, so k≈19.2×0.693≈13 hash functions. At that false-positive rate, only 1 in 10,000 valid requests pays a remote lookup.
5. Convergence without a central coordinator: a CRDT revocation set
A senior candidate should be able to raise this option, though it is not required to answer the question well; the push-based denylist in steps 1 to 3 is the core design. A CRDT (conflict-free replicated data type) is a data structure whose replicas can be updated independently and merged in any order, always converging to the same value. A revocation set is a natural fit because revocation is monotonic: you add, you essentially never "un-revoke" within a token's lifetime. So each region's auth node keeps a grow-only set of jti -> exp, and replicas exchange updates by gossip: periodically, each node picks a peer and exchanges what it has, rather than relying on one central broadcaster, so the set still converges even if some nodes cannot reach each other directly. Merge is set union (keeping the later exp). Each node also keeps per-node logical counters (a version vector, one counter per node recording how many updates from that node you have applied). The sketch below merges full state on every exchange, which is simple and correct but sends more data than necessary; in a real deployment, the version vector is exactly what lets two nodes compare "how many updates have I seen from node X" and request only the entries the other is missing, instead of resending everything each round. Expiry uses the token's own exp claim, set by the issuer, so garbage collection does not depend on trusting each node's local clock beyond a small skew allowance.
Runnable sketch (Python 3, no dependencies):
class RevocationSet:
"""Grow-only set of revoked token IDs (jti), each kept until the token's own exp."""
def __init__(self, node):
self.node = node
self.entries = {} # jti -> exp (unix seconds, from the token itself)
self.clock = {} # node -> highest counter seen (version vector)
def revoke(self, jti, exp):
self.entries[jti] = max(exp, self.entries.get(jti, 0))
self.clock[self.node] = self.clock.get(self.node, 0) + 1
def merge(self, other): # union + pointwise max: commutative, associative, idempotent
for jti, exp in other.entries.items():
self.entries[jti] = max(exp, self.entries.get(jti, 0))
for n, c in other.clock.items():
self.clock[n] = max(c, self.clock.get(n, 0))
def is_revoked(self, jti):
return jti in self.entries
def gc(self, now, skew=60): # safe: an expired token is rejected by the exp check anyway
self.entries = {j: e for j, e in self.entries.items() if e + skew >= now}
us, eu, ap = RevocationSet("us"), RevocationSet("eu"), RevocationSet("ap")
us.revoke("jti-A", exp=1_000_300)
eu.revoke("jti-B", exp=1_000_600)
# Partition: ap has seen nothing yet
print("ap before merge:", ap.is_revoked("jti-A"), ap.is_revoked("jti-B"))
# Gossip in different orders still converges
ap.merge(eu); ap.merge(us)
us.merge(eu); eu.merge(us)
print("converged:", us.entries == eu.entries == ap.entries, sorted(ap.entries))
print("version vector at ap:", dict(sorted(ap.clock.items())))
ap.merge(us) # re-delivery is harmless
print("after duplicate merge:", sorted(ap.entries))
ap.gc(now=1_000_400)
print("after gc at t=1_000_400:", sorted(ap.entries))
Output:
ap before merge: False False
converged: True ['jti-A', 'jti-B']
version vector at ap: {'eu': 1, 'us': 1}
after duplicate merge: ['jti-A', 'jti-B']
after gc at t=1_000_400: ['jti-B']
Why not a full add/remove CRDT? Supporting "remove" (un-revoke) needs an observed-remove set with tombstones: instead of a value simply vanishing, "remove" is recorded as its own entry (a tombstone) that has to be seen and outrank every earlier "add" for that key, which is the standard way CRDTs make delete-then-re-add behave correctly under out-of-order merges. It opens a dangerous race: a stale remove can resurrect a stolen token. If un-revocation is ever needed, issue the user a new token instead. I would use the CRDT for cross-region replication of the authoritative set (it survives partitions and needs no leader), and still push the merged result to gateways as in step 3.
Worked example
A platform with 50 million active users, 5-minute access tokens, and a bad day of 2,000 individual revocations per minute. The active jti set holds at most about 2,000 x 5 = 10,000 entries plus a skew allowance; at under 100 bytes per entry that is about 1 MB per gateway. Subject cutoffs for a mass incident (say every user in one tenant, 200,000 users) add 200,000 small records, still a few MB. No Bloom filter needed; it becomes worthwhile only when the set reaches millions.
How SREs operate, monitor and scale it
- Key metrics: revoke-to-enforced latency measured by a canary, a synthetic, fake-but-realistic probe run continuously in production so you get a steady measurement instead of waiting for a real revocation (revoke a synthetic token every 10 seconds, probe every gateway, time until 401); per-gateway
last_applied_sequencelag behind the stream head; set size; snapshot age; share of requests hitting the authoritative store. - Staleness policy: if a gateway's sequence lags by more than a threshold (say 10 seconds), it fails closed on high-risk scopes (payments, admin) by calling the auth service directly, and keeps serving low-risk reads. Decide this per route in advance, not during an incident.
- Cold start: a new gateway loads a snapshot plus the stream from the snapshot's sequence before it takes traffic; readiness probes (the orchestrator's check for "is this instance actually ready to serve," used to hold new instances out of the load balancer until they pass it) enforce this.
- Scale: the stream's fan-out, how many downstream subscribers one stream has to deliver every message to, is the only thing that grows with gateway count. Thousands of subscribers on one topic is routine for the streaming systems named above; if not, add a regional relay tier.
- Runbook for a real compromise: revoke by subject cutoff (covers tokens you don't know about), rotate the signing key if the key itself leaked (every token becomes invalid; publish the new public key through the JWKS endpoint, the JSON Web Key Set URL gateways fetch keys from), and verify with the canary.
Trade-offs and pitfalls
- Shorter token lifetimes vs refresh load. 5-minute tokens with 10 million concurrent sessions means about 33,000 refreshes per second (10,000,000 / 300). Check the auth service can take that before shortening further.
- Revoking only by
jtimisses tokens you have not seen; the subject cutoff is the incident-response tool. - Fail-open everywhere makes the revocation system decorative during exactly the outages attackers exploit; fail-closed everywhere turns a stream hiccup into a platform outage. Split by route risk.
- What would flip the design: if you need revocation guarantees in milliseconds with strict consistency on every request, stop using self-contained tokens on that path and introspect instead.
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.
You need to build a tamper-evident, globally-consistent audit trail for security events that supports efficient range proofs and legal requests. Requirements: per-region append-only chains, a way to verifiably merge them across regions with proofs, efficient queries for time ranges and per-entity history, and operational tooling for SREs to generate proofs for auditors. Walk through the data structures and storage backends you would use, your indexing strategy, and how you'd manage retention and proof generation.
Sample Answer
Direct answer
Model each region's audit trail as a Merkle-tree transparency log, the structure Certificate Transparency (the public, append-only logging system browsers use to catch mis-issued TLS certificates) uses (RFC 6962): events are appended as leaves (the tree's bottom-level entries, one per event), and every so often the region publishes a signed tree head, a signature over the tree's root hash (a single hash that commits to the contents of every leaf beneath it) and size. Anyone holding a signed head can check two things with a handful of hashes: that a given event is in the log (an inclusion proof) and that today's log is an append-only extension of yesterday's (a consistency proof). To merge regions verifiably, a global log takes each region's signed head at fixed epochs (say every minute) as its own leaves, producing one global root per epoch that commits to all regions at once. Event data lives in write-once object storage, a separate index serves time-range and per-entity queries, and proof generation is a tool SREs run on demand for auditors.
The data structures
Hash chain vs Merkle tree. A hash chain (each record includes the hash of the previous one) is tamper-evident, but proving that event #5,000,000 is in the log means handing over everything after it. A Merkle tree hashes events in pairs, then pairs of pairs, up to one root. Proving one event is included takes one sibling hash per level, about ⌈log2n⌉ hashes:
| Log size | Sibling hashes in an inclusion proof | Proof size (SHA-256) |
|---|---|---|
| 1,000 | 10 | 320 bytes |
| 1,000,000 | 20 | 640 bytes |
| 8.64 billion (one day at 100k events/s) | 34 | 1,088 bytes |
Per-region append-only log. Each region runs its own log (append-only by construction: the log server only appends leaves, and consistency proofs let anyone detect a rewrite). Leaf = canonical serialisation of the event (encoding it into bytes in one fixed, unambiguous order, so hashing the same event twice always produces the same hash; here: event ID, entity ID, actor, action, timestamp, payload hash).
Verifiable cross-region merge. Regions do not share one total order in real time; forcing one would make every write wait on a cross-region round trip. Instead, at each epoch boundary, each region's signed head becomes a leaf in the global epoch tree, in a fixed region order. The global root for epoch 1042 therefore commits to exactly which events every region had at that moment. A proof for any event is a pair: inclusion in its regional tree, plus inclusion of that regional head in the global tree.
flowchart TB
subgraph US[us region log]
U1[events] --> UR[signed head us]
end
subgraph EU[eu region log]
E1[events] --> ER[signed head eu]
end
subgraph AP[ap region log]
A1[events] --> AR[signed head ap]
end
UR & ER & AR --> G[Global epoch tree, root per minute]
G --> W[(WORM archive + external witnesses)]
Runnable demonstration (Python 3, standard library)
This follows RFC 6962's hashing: leaves are hashed with a 0x00 prefix and interior nodes with 0x01, so a leaf can never be passed off as an interior node.
import hashlib
def H(b): return hashlib.sha256(b).digest()
def leaf(d): return H(b"\x00" + d) # RFC 6962 leaf hash
def node(l, r): return H(b"\x01" + l + r) # RFC 6962 interior hash
def split(n): # largest power of 2 < n
k = 1
while k * 2 < n: k *= 2
return k
def root(items):
if len(items) == 1: return leaf(items[0])
k = split(len(items))
return node(root(items[:k]), root(items[k:]))
def prove(items, i): # audit path for item i
if len(items) == 1: return []
k = split(len(items))
if i < k: return prove(items[:k], i) + [("R", root(items[k:]))]
return prove(items[k:], i - k) + [("L", root(items[:k]))]
def verify(item, path, expected_root):
h = leaf(item)
for side, sib in path:
h = node(h, sib) if side == "R" else node(sib, h)
return h == expected_root
# Regional logs for one epoch (a minute of events per region)
regions = {
"us": [f"us|{i}|user:42|login".encode() for i in range(5)],
"eu": [f"eu|{i}|user:7|export".encode() for i in range(3)],
"ap": [f"ap|{i}|svc:billing|keyread".encode() for i in range(6)],
}
region_roots = {r: root(ev) for r, ev in regions.items()}
# Global epoch tree: leaves are (epoch, region, regional root), fixed region order
epoch = 1042
g_leaves = [f"{epoch}|{r}|".encode() + region_roots[r] for r in sorted(regions)]
global_root = root(g_leaves)
# Proof that eu event #2 is in the globally committed epoch
ev = regions["eu"][2]
p1 = prove(regions["eu"], 2)
gi = sorted(regions).index("eu")
p2 = prove(g_leaves, gi)
ok1 = verify(ev, p1, region_roots["eu"])
ok2 = verify(g_leaves[gi], p2, global_root)
print("regional inclusion:", ok1, "| proof hashes:", len(p1))
print("global inclusion: ", ok2, "| proof hashes:", len(p2))
# Tamper: someone edits the stored event after the root was signed
tampered = b"eu|2|user:7|view"
print("tampered event verifies:", verify(tampered, p1, region_roots["eu"]))
# Proof size grows with log2(n), not n
import math
for n in (1_000, 1_000_000, 8_640_000_000):
print(f"n={n:>13,} -> about {math.ceil(math.log2(n))} sibling hashes, {math.ceil(math.log2(n))*32} bytes")
Output:
regional inclusion: True | proof hashes: 1
global inclusion: True | proof hashes: 2
tampered event verifies: False
n= 1,000 -> about 10 sibling hashes, 320 bytes
n= 1,000,000 -> about 20 sibling hashes, 640 bytes
n=8,640,000,000 -> about 34 sibling hashes, 1088 bytes
The demo omits signatures to stay short; production signs every published root with a key in an HSM or KMS (below). It does not omit consistency proofs.
Walking through the proof, by hand
split(n) finds the largest power of two strictly less than n. That is how RFC 6962 shapes an unbalanced tree for any size: the left side is always a perfect subtree of size k, and the right side (n - k items) is built the same way, recursively. For the eu region above, 3 events, split(3) = 2, so the tree is node( node(L0, L1), L2 ): leaves 0 and 1 pair up first, and leaf 2 hangs directly off the root.
That is why prove(regions["eu"], 2) (the proof for event index 2) returns exactly one sibling instead of the ceil(log2(3)) = 2 you might expect from a balanced tree: at the top level, index 2 is not less than k = 2, so the function takes the ("L", root(items[:2])) branch and recurses into prove(items[2:], 0), a single-item list, which returns []. The whole proof is that one ("L", ...) entry: the combined hash of leaves 0 and 1, labelled L because it sits to the left of leaf 2 when they are joined.
verify() starts from leaf(item) and folds in each sibling in the order the proof lists them: "R" means the sibling is combined on the right (node(h, sib), used when the proved leaf was in the left half at that level), "L" means it is combined on the left (node(sib, h), used here). One fold with the leaves-0-1 hash on the left reproduces the root, so verify returns True.
Consistency proof and range proof, worked small
Both are missing from the demo above; here they are, small enough to read in full and to run on their own (repeating the leaf/node/split/root helpers from the first demo).
import hashlib
def H(b): return hashlib.sha256(b).digest()
def leaf(d): return H(b"\x00" + d)
def node(l, r): return H(b"\x01" + l + r)
def split(n):
k = 1
while k * 2 < n: k *= 2
return k
def root(items):
if len(items) == 1: return leaf(items[0])
k = split(len(items))
return node(root(items[:k]), root(items[k:]))
def consistency_proof(items, m): # proves size-m tree is a prefix of size-n tree
n = len(items)
return _subproof(items, m, n, True)
def _subproof(items, m, n, b):
if m == n:
return [] if b else [root(items)]
k = split(n)
if m <= k:
return _subproof(items[:k], m, k, b) + [root(items[k:])]
return _subproof(items[k:], m - k, n - k, False) + [root(items[:k])]
def verify_consistency(m, n, proof, old_root, new_root):
proof = list(proof)
def rec(m, n, b, claimed_old):
if m == n:
if b:
return claimed_old, claimed_old
h = proof.pop()
return h, h
k = split(n)
if m <= k:
right = proof.pop()
oh, nh_left = rec(m, k, b, claimed_old)
return oh, node(nh_left, right)
left = proof.pop()
oh, nh_right = rec(m - k, n - k, False, claimed_old)
return node(left, oh), node(left, nh_right)
oh, nh = rec(m, n, True, old_root)
return oh == old_root and nh == new_root
def range_proof(items, start, end): # boundary hashes for the contiguous range [start, end]
n = len(items)
needed = []
def walk(lo, hi):
if hi <= start or lo > end:
needed.append(root(items[lo:hi]))
elif lo >= start and hi - 1 <= end:
return
else:
k = split(hi - lo)
walk(lo, lo + k); walk(lo + k, hi)
walk(0, n)
return needed
def verify_range(range_items, start, end, n, needed, expected_root):
needed = list(needed)
def rebuild(lo, hi):
if hi <= start or lo > end:
return needed.pop(0)
if lo >= start and hi - 1 <= end:
return _root_sub(range_items[lo - start:hi - start])
k = split(hi - lo)
return node(rebuild(lo, lo + k), rebuild(lo + k, hi))
def _root_sub(sub):
if len(sub) == 1: return leaf(sub[0])
k = split(len(sub))
return node(_root_sub(sub[:k]), _root_sub(sub[k:]))
return rebuild(0, n) == expected_root
# 1. Consistency proof: the eu region's log grows from 2 events to 3.
eu_old = [f"eu|{i}|user:7|export".encode() for i in range(2)]
eu_new = [f"eu|{i}|user:7|export".encode() for i in range(3)]
old_root, new_root = root(eu_old), root(eu_new)
cproof = consistency_proof(eu_new, 2)
print("consistency proof, 2 events -> 3 events: hashes needed =", len(cproof))
print("verifies (append-only holds):", verify_consistency(2, 3, cproof, old_root, new_root))
rewritten = [b"eu|0|user:7|EDITED-LATER", eu_new[1], eu_new[2]] # attacker edits event 0, still grows to 3
fake_new_root = root(rewritten)
print("same proof against a silently rewritten history:", verify_consistency(2, 3, cproof, old_root, fake_new_root))
# 2. Range proof: prove events 1..3 of a 5-event log, nothing omitted from the middle.
five = [f"us|{i}|svc:billing|keyread".encode() for i in range(5)]
five_root = root(five)
rproof = range_proof(five, 1, 3)
print()
print("range proof for events[1..3] of 5: boundary hashes needed =", len(rproof))
print("verifies with the real 3 events:", verify_range(five[1:4], 1, 3, 5, rproof, five_root))
tampered_middle = [five[1], b"us|2|svc:billing|EDITED", five[3]]
print("verifies if the middle event is edited:", verify_range(tampered_middle, 1, 3, 5, rproof, five_root))
dropped_middle = [five[1], five[3]] # attacker returns only 2 of the 3 claimed events
try:
ok = verify_range(dropped_middle, 1, 3, 5, rproof, five_root)
except IndexError:
ok = False
print("verifies if the middle event is silently dropped:", ok)
Output:
consistency proof, 2 events -> 3 events: hashes needed = 1
verifies (append-only holds): True
same proof against a silently rewritten history: False
range proof for events[1..3] of 5: boundary hashes needed = 2
verifies with the real 3 events: True
verifies if the middle event is edited: False
verifies if the middle event is silently dropped: False
For 3 leaves, proving events 0 and 1 haven't been disturbed while a third is appended needs only 1 hash: the new leaf hangs directly off the old root (the same unbalanced shape explained above), so that old root itself is the one sibling the consistency proof supplies. For the range proof, the 5-event log splits as node(node(node(L0,L1),node(L2,L3)),L4); proving events 1 to 3 needs the hash of L0 (the left edge of the first proved leaf) and the hash of L4 (everything to the right of the range), 2 boundary hashes. Handing over 2 hashes instead of leaf 2's own separate inclusion proof is what proves the auditor's own copy of events 1, 2 and 3 is complete: drop or edit any one of the three and the reconstructed root stops matching, exactly as the last two lines show.
Storage backends
| Layer | Backend | Holds |
|---|---|---|
| Log server | A transparency-log implementation (Google's open-source Trillian is the established one) or a small custom service backed by a relational database | Leaf hashes, tree state, signed heads |
| Event payloads | Object storage with WORM (write once, read many) retention, for example S3 Object Lock in compliance mode, where no user including the account root can delete or shorten retention on a locked version | Batched event files (Parquet, a compressed columnar file format well suited to large batches of structured records), keyed by region/epoch |
| Tree tiles | Same WORM storage | Precomputed subtree hashes so proofs are generated without recomputing the tree |
| Query index | Columnar store (a database that stores each column of data together rather than each row, which is fast for aggregate and filter queries over specific fields) or search engine (ClickHouse, OpenSearch) | Pointers from (entity, time) to (region, epoch, leaf index) |
Indexing strategy
The index is for finding events; the log is for proving them. The index never needs to be trusted, because every result can be proved against a signed head.
- Time ranges: leaves are appended in time order within a region, so a range maps to a contiguous leaf-index range per region. Store
epoch -> (first_leaf, last_leaf)per region; a time-range query is a lookup plus a scan of that slice. - Per-entity history: a secondary index
(entity_id, timestamp) -> (region, leaf_index). For each hit, generate an inclusion proof. Across regions, order by timestamp and then region, and state that cross-region order within one epoch is by timestamp, not causality. - Range proofs: for "all events in [t1, t2]", deliver the contiguous run of leaves plus the sibling hashes along the left edge of the first leaf and the right edge of the last leaf (worked small, with real code and output, in "Consistency proof and range proof, worked small" above); the auditor hashes the delivered events together with those boundary siblings and must reproduce the signed root exactly. That proves nothing was omitted from the middle of the range, which a list of separate inclusion proofs cannot.
Retention, legal hold and compliance
- Defensible retention policy: each event class has a documented retention period (for example seven years for security events), applied as a default retention on the WORM bucket. Deletion happens only by automated expiry after the lock lapses, and each expiry batch is itself an audit event.
- Legal holds: a legal hold on a locked object keeps it immutable beyond its retention date until explicitly removed. Legal-hold search runs on the index ("all events for entity X or matter Y"), then places holds on the matching object versions, and records the hold list as a signed manifest so you can later prove what was held and when.
- Deletion vs immutability: privacy law may require erasing a person's data from a log you promised never to change. Resolve it with crypto-shredding: encrypt each entity's payloads with its own data key and put only the ciphertext hash in the tree. Destroy the key and the content is unreadable, while every proof still verifies.
- Integrity proof via key management: signed heads are signed by a key in a KMS or HSM (key management service or hardware security module) the log operators cannot export; the KMS's own access log shows every signing call. For an external audit you hand over the public key, the signed heads, and the KMS log showing the key was used only by the log service. That is what turns "our logs are intact" into evidence.
- Witnessing: publish each global root to independent witnesses (another team's account, a partner, or a public timestamping service). A log operator who rewrites history would need to fork every witnessed head, which consistency checks expose.
Operational tooling for SREs
audit-proof event <event_id>: returns the event, its regional inclusion proof, the regional signed head, the global inclusion proof and the global signed head, packaged with a standalone verifier script the auditor runs themselves.audit-proof range --entity X --from t1 --to t2: the events plus range proof.- A continuous monitor that fetches every new signed head, checks consistency with the previous one, and pages if any check fails or a region stops publishing heads (a stalled log can hide events as effectively as a rewritten one).
- Quarterly drill: hand a colleague playing auditor a proof package and have them verify it with nothing but the public key.
Trade-offs and pitfalls
- One global log is simpler to prove but puts a cross-region round trip on every append; per-region logs with an epoch merge keep writes local and delay only the global commitment by one epoch.
- Trusting the index is the common mistake; every answer to an auditor must be backed by a proof, not a query result.
- Signing key loss breaks nothing retroactively but stops new heads; keep a documented key rotation that signs the transition with both keys, and retain old public keys for the full retention period.
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.
Unlock Full Question Bank
Get access to all 13 Distributed Systems Security and Trust interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.