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.
Implement a proof-of-concept Python CLI rotate_secret that rotates a symmetric secret across a list of services by calling a provided secret store interface. Requirements: idempotence, canary rollout (rotate for a subset and validate), concurrency-safe updates, and rollback if validation fails. Assume the following interface:
class SecretStore:
def get_secret(self, service_name):
pass
def put_secret(self, service_name, secret, version):
pass
def validate_service(self, service_name, secret) -> bool:
pass
Implement rotate_secret(services: List[str], new_secret_generator, canary_fraction=0.05) that performs safe rotation with canaries and supports retry-safe behavior.
Sample Answer
Direct answer
A safe rotation tool is a small state machine with a durable journal. The tool moves through four recorded states: rotating while it is still pushing the new secret out, complete once every service has confirmed it, or, if something fails, rolling_back while it undoes a partial rotation, and rolled_back once every changed service is back on its old secret. In practice: mint the new secret once and record it, snapshot every service's current secret and version, roll out to a small canary group and validate, then roll out in batches with validation after each, and on any failure roll every changed service back. Idempotence (running the same rotation twice has the same effect as running it once) comes from the journal: a retry with the same rotation ID reuses the same secret, skips services already done, and never re-runs a finished rotation. Concurrency safety comes from a lease (a time-limited right to be the only actor allowed to run a rotation, that automatically expires if its holder crashes without releasing it) so only one rotation runs at a time, plus a compare-before-write that detects anyone else changing a secret mid-rotation. Rollback writes the old secret under a new, higher version so caches treat it as the newest value.
Assumptions the interface leaves open
get_secret(service)returns a(secret, version)tuple with an integer version.put_secretis not conditional (no compare-and-set), so the tool re-reads before each write and relies on a lease to be the only rotator. If the real store supports a conditional put, use it instead; it closes the small window between read and write.- Because this is a shared symmetric secret (the same key used by multiple services, for example to sign internal requests with HMAC, a hash-based message authentication code), services will be on different secrets during the rollout. That is only safe if each service accepts both the current and the previous secret while rotating. That dual-accept behaviour belongs in the services, and the canary is what proves it works.
rotation_id,storeandjournalare added as keyword arguments; the positional signature is as specified.
Design
| Requirement | Mechanism |
|---|---|
| Idempotence | Journal keyed by rotation_id; secret generated once and stored; per-service done list written after each successful put; finished rotations return immediately |
| Retry-safe after a crash | Deterministic service order; put is skipped if the store already holds exactly (new secret, target version); a crash during rollback resumes the rollback, never the forward rollout |
| Canary rollout | max(1, ceil(canary_fraction x n)) services first, validated before anything else changes |
| Concurrency-safe | A single rotation lease; compare-before-write raises a conflict if a service's version changed since the snapshot |
| Rollback | Restore each changed service's old secret, in reverse order, under version target + 1 |
Code
import math, secrets, threading
from typing import Callable, Dict, List, Optional
class SecretStore: # the interface given in the question
def get_secret(self, service_name): pass
def put_secret(self, service_name, secret, version): pass
def validate_service(self, service_name, secret) -> bool: pass
class RotationInProgress(Exception): pass
class ConflictError(Exception): pass
class RotationFailed(Exception): pass
class Journal:
"""Durable rotation state. In production: a DB row per rotation, updated with
conditional writes. Here: a dict guarded by a lock, plus a single rotation lease."""
def __init__(self):
self.records: Dict[str, dict] = {}
self.lease_holder: Optional[str] = None
self.mu = threading.Lock()
def acquire(self, rotation_id: str):
with self.mu:
if self.lease_holder not in (None, rotation_id):
raise RotationInProgress(f"rotation {self.lease_holder} holds the lease")
self.lease_holder = rotation_id
def release(self, rotation_id: str):
with self.mu:
if self.lease_holder == rotation_id:
self.lease_holder = None
def _put_if_unchanged(store, svc, expected_version, secret, version):
"""Compare-then-put. The given interface has no compare-and-set, so the lease makes
us the only rotator and this re-read catches writers that bypass the tool."""
current = store.get_secret(svc)
if current == (secret, version):
return # already done by an earlier attempt: retry-safe no-op
if current[1] != expected_version:
raise ConflictError(f"{svc}: expected v{expected_version}, found v{current[1]}")
store.put_secret(svc, secret, version)
def rotate_secret(services: List[str], new_secret_generator: Callable[[], str],
canary_fraction: float = 0.05, *, store: SecretStore,
journal: Journal, rotation_id: str, batch_size: int = 10) -> dict:
journal.acquire(rotation_id)
try:
rec = journal.records.get(rotation_id)
if rec is None: # first attempt: snapshot the old state and mint the secret ONCE
prev = {s: store.get_secret(s) for s in services}
rec = {"secret": new_secret_generator(), "prev": prev,
"target": {s: prev[s][1] + 1 for s in services},
"done": [], "state": "rotating"}
journal.records[rotation_id] = rec
if rec["state"] in ("complete", "rolled_back"):
return rec # a retry of a finished rotation changes nothing
if rec["state"] == "rolling_back": # died mid-rollback: finish it, never resume forward
_rollback(store, rec)
rec["state"] = "rolled_back"
return rec
ordered = sorted(services) # deterministic order so retries resume, not reshuffle
n_canary = max(1, math.ceil(canary_fraction * len(ordered)))
waves = [ordered[:n_canary]] + [ordered[i:i + batch_size]
for i in range(n_canary, len(ordered), batch_size)]
try:
for wave in waves:
for svc in wave:
if svc in rec["done"]:
continue
_put_if_unchanged(store, svc, rec["prev"][svc][1], rec["secret"], rec["target"][svc])
rec["done"].append(svc) # journal AFTER the put succeeds
bad = [s for s in wave if not store.validate_service(s, rec["secret"])]
if bad:
raise RotationFailed(f"validation failed on {bad}")
except (RotationFailed, ConflictError) as e:
rec["state"], rec["error"] = "rolling_back", str(e) # journal the decision first
_rollback(store, rec)
rec["state"] = "rolled_back"
return rec
rec["state"] = "complete"
return rec
finally:
journal.release(rotation_id)
def _rollback(store, rec):
for svc in reversed(rec["done"]):
old_secret, old_version = rec["prev"][svc]
# Restore the OLD value under a NEW, higher version so every cache treats it as newest.
store.put_secret(svc, old_secret, rec["target"][svc] + 1)
# ---------------- driver: an in-memory store with injectable faults ----------------
class FakeStore(SecretStore):
def __init__(self, services):
self.data = {s: ("initial-secret", 1) for s in services}
self.puts = 0
self.reject = set() # services whose validation fails
self.crash_on = set() # services whose next put "crashes the process"
self.on_validate = None # hook to interleave another actor
def get_secret(self, s): return self.data[s]
def put_secret(self, s, secret, version):
if s in self.crash_on:
self.crash_on.discard(s)
raise ConnectionError(f"process died while writing {s}")
self.puts += 1
self.data[s] = (secret, version)
def validate_service(self, s, secret):
if self.on_validate: self.on_validate(s)
return s not in self.reject and self.data[s][0] == secret
SERVICES = [f"svc-{i:02d}" for i in range(40)]
calls = {"n": 0}
def gen():
calls["n"] += 1
return f"secret-{calls['n']}-" + secrets.token_hex(4)
def summary(store): # count services per (secret, version); random suffix hidden
counts = {}
for sec, v in store.data.values():
key = (sec.rsplit("-", 1)[0] if sec.startswith("secret-") else sec, v)
counts[key] = counts.get(key, 0) + 1
return dict(sorted(counts.items()))
print("1. happy path")
st, j = FakeStore(SERVICES), Journal()
r = rotate_secret(SERVICES, gen, 0.05, store=st, journal=j, rotation_id="rot-A")
print(" state:", r["state"], "| puts:", st.puts, "| generator calls:", calls["n"], "|", summary(st))
print("2. retry of the same rotation id")
r = rotate_secret(SERVICES, gen, 0.05, store=st, journal=j, rotation_id="rot-A")
print(" state:", r["state"], "| puts:", st.puts, "| generator calls:", calls["n"])
print("3. canary fails validation")
calls["n"] = 0
st, j = FakeStore(SERVICES), Journal()
st.reject = {"svc-01"}
r = rotate_secret(SERVICES, gen, 0.05, store=st, journal=j, rotation_id="rot-B")
print(" state:", r["state"], "|", r["error"], "| puts:", st.puts, "|", summary(st))
print("4. crash mid-rollout, then retry")
calls["n"] = 0
st, j = FakeStore(SERVICES), Journal()
st.crash_on = {"svc-20"}
try:
rotate_secret(SERVICES, gen, 0.05, store=st, journal=j, rotation_id="rot-C")
except ConnectionError as e:
print(" first attempt died:", e, "| rotated so far:", len(j.records["rot-C"]["done"]))
r = rotate_secret(SERVICES, gen, 0.05, store=st, journal=j, rotation_id="rot-C")
print(" retry state:", r["state"], "| puts:", st.puts, "| generator calls:", calls["n"], "|", summary(st))
print("5. second rotation starts while the first is running")
calls["n"] = 0
st, j = FakeStore(SERVICES), Journal()
started, finish = threading.Event(), threading.Event()
def hold_once(svc):
if svc == "svc-00" and not started.is_set():
started.set(); finish.wait()
st.on_validate = hold_once
t = threading.Thread(target=rotate_secret, args=(SERVICES, gen, 0.05),
kwargs=dict(store=st, journal=j, rotation_id="rot-D"))
t.start(); started.wait()
try:
rotate_secret(SERVICES, gen, 0.05, store=st, journal=j, rotation_id="rot-E")
except RotationInProgress as e:
print(" rot-E refused:", e)
finish.set(); t.join()
print(" rot-D state:", j.records["rot-D"]["state"], "| generator calls:", calls["n"], "|", summary(st))
print("6. someone else writes a secret mid-rotation")
calls["n"] = 0
st, j = FakeStore(SERVICES), Journal()
def rogue(svc):
if svc == "svc-05":
st.data["svc-30"] = ("hand-edited", 7)
st.on_validate = rogue
r = rotate_secret(SERVICES, gen, 0.05, store=st, journal=j, rotation_id="rot-F")
print(" state:", r["state"], "|", r["error"], "|", summary(st))
print("7. crash during rollback, then retry")
calls["n"] = 0
st, j = FakeStore(SERVICES), Journal()
st.reject = {"svc-15"}
def crash_rollback(svc):
if svc == "svc-15":
st.crash_on = {"svc-07"}
st.on_validate = crash_rollback
try:
rotate_secret(SERVICES, gen, 0.05, store=st, journal=j, rotation_id="rot-G")
except ConnectionError as e:
print(" first attempt died:", e, "| journal state:", j.records["rot-G"]["state"])
r = rotate_secret(SERVICES, gen, 0.05, store=st, journal=j, rotation_id="rot-G")
print(" retry state:", r["state"], "|", summary(st))
Output:
1. happy path
state: complete | puts: 40 | generator calls: 1 | {('secret-1', 2): 40}
2. retry of the same rotation id
state: complete | puts: 40 | generator calls: 1
3. canary fails validation
state: rolled_back | validation failed on ['svc-01'] | puts: 4 | {('initial-secret', 1): 38, ('initial-secret', 3): 2}
4. crash mid-rollout, then retry
first attempt died: process died while writing svc-20 | rotated so far: 20
retry state: complete | puts: 40 | generator calls: 1 | {('secret-1', 2): 40}
5. second rotation starts while the first is running
rot-E refused: rotation rot-D holds the lease
rot-D state: complete | generator calls: 1 | {('secret-1', 2): 40}
6. someone else writes a secret mid-rotation
state: rolled_back | svc-30: expected v1, found v7 | {('hand-edited', 7): 1, ('initial-secret', 1): 9, ('initial-secret', 3): 30}
7. crash during rollback, then retry
first attempt died: process died while writing svc-07 | journal state: rolling_back
retry state: rolled_back | {('initial-secret', 1): 18, ('initial-secret', 3): 22}
The new secret contains random bytes, so summary hides the random suffix and prints how many services hold each (secret, version) pair; everything printed is deterministic.
Reading the results
- Happy path: 40 services,
ceil(0.05 x 40) = 2canaries, then batches of 10. 40 puts, generator called once, every service on version 2. - Retry of a completed rotation: no additional puts and no new secret. This is the idempotence property that makes it safe for an operator or a scheduler to re-run the command.
- Canary failure: svc-01 fails validation, so only the 2 canaries were changed. 4 puts total (2 forward, 2 rollback); those two now hold the original secret at version 3, the other 38 were never touched.
- Crash mid-rollout: the process dies writing svc-20 after 20 services succeeded. The retry uses the journalled secret (generator still called once) and finishes with exactly 40 successful puts, because the 20 already-done services are skipped.
- Concurrent rotations: the driver starts rot-D in a background thread and, via a
threading.Event, pauses it mid-validation on the very first service, so rot-E genuinely overlaps rot-D in wall-clock time instead of just running after it. While rot-D is running, rot-E is refused by the lease instead of generating a second secret and interleaving writes. - Out-of-band write: someone hand-edits svc-30 during the rollout. The compare-before-write sees version 7 where it expected 1, raises a conflict, and rolls back the 30 services already rotated (svc-00 to svc-29, now at version 3). svc-30 keeps its hand-edited value because the tool never overwrites something it did not expect.
- Crash during rollback: svc-15 fails validation after 22 services were rotated; the rollback dies partway. The journal says
rolling_back, so the retry finishes the rollback (22 services at version 3, 18 untouched at version 1) rather than resuming the forward rollout.
Key points
- Journal before acting on a decision. The state is set to
rolling_backbefore the first rollback write, and a service is added todoneonly after its put succeeds. Getting either order wrong makes a crash resume in the wrong direction. - Rollback moves the version forward. Writing the old secret back at its old version 1 would look older than version 2 to any cache or consumer that keeps the highest version it has seen, and they would keep the new secret.
- Validation happens per wave, so a problem that only appears at scale (a service type the canaries did not include) is still caught before the whole fleet changes.
Complexity
O(n) store operations for n services: one snapshot read and one read-plus-write per service, plus one validation each; a rollback adds at most one write per changed service. Memory is O(n) for the journal. Runtime is dominated by validation calls, which are sequential here; running each wave's validations in parallel shortens wall time without changing the logic.
Edge cases
canary_fractionof 0 or a single service still gets at least one canary.- Duplicate service names in the input: deduplicate before calling, otherwise a service is counted twice in the canary math.
- A service added to the list on retry is not in the snapshot; the tool would fail with a missing key. A retry must use the same service list, or start a new rotation ID.
- The lease here dies with the process only because the demo releases it in
finally. A real crash does not runfinally, so a production lease needs an expiry (for example 5 minutes, renewed while working) and a fencing token (a number that increases with each new lease, which the store rejects if it is older than the last one seen), so a paused old rotator that wakes up cannot write after its lease has passed to someone else. - Validation that is flaky (a transient timeout) causes a needless rollback; retry validation a small fixed number of times before declaring failure.
Trade-offs and pitfalls
- Rotating everything at once is simpler, but turns one bad secret format or one service without dual-accept into a fleet-wide outage.
- Generating the secret inside the per-service loop (a common bug) gives every service a different secret, which silently breaks a shared symmetric key.
- Retiring the previous secret is a separate, later step: only after every service is on the new version and has been for longer than any in-flight request or cached token can live.
- Store the journal somewhere durable and access-controlled: it contains the new secret in this demo; a production journal stores a reference to the secret in the secret store, not the value.
Design authentication and authorization propagation across hundreds of microservices. Discuss token formats (JWT vs opaque tokens), token exchange patterns for internal services, token refresh and revocation strategies, minimization of token bloat in headers, and patterns for enforcing fine-grained permissions in downstream services (authorization middleware, PDP/PAP, or policy-as-a-service).
Sample Answer
Direct answer
Use opaque tokens at the edge and short-lived, audience-scoped JWTs inside the mesh (the network of proxies that carries and secures service-to-service traffic across the estate), minted by a central token service through token exchange at each trust hop. The edge gateway turns the user's external token into an internal token that carries only who the user is and which service it is meant for, not every permission they hold. Downstream services authenticate the calling service with its workload identity (for example mTLS, mutual TLS where both sides present certificates), validate the internal token locally, and ask a policy decision point for fine-grained decisions, with a local sidecar cache (a small helper process deployed alongside each service instance, sharing its network so it can intercept and answer calls without a remote hop) to keep that off the latency critical path. Revocation is handled by keeping internal tokens to a few minutes and pushing revocation events for the rare cases that cannot wait.
Vocabulary first
- JWT (JSON Web Token): a signed, self-contained token. Any service holding the issuer's public key can verify it without a network call. Downside: once issued it is valid until it expires.
- Opaque token: a random string meaningful only to the issuer. Verifying it means calling the issuer (introspection, RFC 7662). Revocation is instant, but every check is a network call.
- Token exchange (RFC 8693): an OAuth 2.0 grant where a service presents a token it holds and receives a new token for a different audience, typically with narrower scope.
- PEP / PDP / PAP / PIP: the policy enforcement point (code that blocks or allows the request), policy decision point (evaluates the policy), policy administration point (where policies are authored and versioned) and policy information point (the source of attributes such as team membership).
Architecture
flowchart LR
U[Client] -->|opaque token| GW[Edge gateway]
GW -->|exchange| TS[Token service]
TS -->|internal JWT aud=orders| GW
GW -->|JWT + mTLS| O[Orders service]
O -->|exchange for aud=payments| TS
O -->|new JWT + mTLS| P[Payments service]
O -.->|check| SC1[Policy sidecar]
P -.->|check| SC2[Policy sidecar]
PAP[Policy admin and store] -->|bundles| SC1
PAP -->|bundles| SC2
1. Token formats: commit per boundary
| Boundary | Format | Why |
|---|---|---|
| Internet client to edge | Opaque access token (or a JWT validated only at the edge) | Clients are untrusted and tokens leak (logs, browser storage); opaque tokens can be revoked instantly and reveal nothing |
| Edge to internal services | Short-lived JWT (2 to 5 minutes), signed by the internal token service | Hundreds of services each verify locally with a cached public key, so there is no per-hop call to the issuer |
| Service to service | Workload identity (mTLS certificate) plus the propagated user JWT when acting on a user's behalf | mTLS proves which service is calling; the JWT proves on whose behalf |
Introspecting an opaque token on every internal hop does not scale: 20,000 requests per second fanning out through an average of 6 internal hops is 120,000 introspection calls per second against one service, which becomes the platform's single point of failure.
2. Token exchange for internal calls
Forwarding the user's original token unchanged through the call chain is the common anti-pattern: every downstream service receives a token that is valid at every other service (a replayable bearer credential: whoever holds the bytes can use it, with no extra proof that they are the party it was issued to), and a compromised low-value service can replay it against a high-value one.
Instead, each hop exchanges:
- Orders receives a JWT with
aud: orders. - To call Payments it presents that token plus its own workload identity to the token service and requests
aud: payments. - The token service checks policy ("may orders call payments on behalf of a user?") and returns a JWT with
aud: payments, the samesub(the user), and anact(actor) claim recording that orders is the intermediary. RFC 8693 definesactfor exactly this delegation chain.
Payments rejects any token whose aud is not payments, so a token stolen from Orders is useless against Payments. Cost: one extra call per cross-service hop, which you cache: the exchanged token is reusable for its lifetime for the same user and audience.
3. Refresh and revocation
- Internal tokens are not refreshed; they are re-minted. They live 2 to 5 minutes, so the worst-case window in which a revoked user keeps access internally is that lifetime.
- Refresh tokens exist only between the client and the authorization server, are rotated on every use (a reused refresh token signals theft and revokes the whole family), and never enter the mesh.
- Urgent revocation (account takeover, fired employee): the auth server publishes a revocation event (
subor session ID plus a timestamp) on a stream; sidecars and gateways keep a small in-memory deny set and reject any token for that subject issued before the revocation time. The set stays small because entries can be dropped once every token issued before them has expired.
4. Minimizing token bloat
Putting a user's permissions in the token is the fastest way to break the platform. Measured by encoding real JWTs (ES256: an elliptic-curve signing algorithm producing a compact, fixed 64-byte signature, versus RS256, an RSA signature that runs 256 bytes for a 2048-bit key; compact JSON): jwt_len builds the same three parts a real token has (a header naming the algorithm and key, a claim set, and a fixed-length signature), base64url-encodes each, and adds them up, once with a bare claim set and once with a growing list of permission strings appended to it, to measure how token size scales with how many permissions ride inside it.
import base64, json
def b64url(b):
return base64.urlsafe_b64encode(b).rstrip(b"=")
def jwt_len(claims):
header = {"alg": "ES256", "kid": "2026-09-a", "typ": "JWT"}
h = b64url(json.dumps(header, separators=(",", ":")).encode())
p = b64url(json.dumps(claims, separators=(",", ":")).encode())
sig = b64url(bytes(64)) # an ES256 signature is always 64 bytes (r || s)
return len(h) + 1 + len(p) + 1 + len(sig)
base = {"iss": "https://auth.internal", "sub": "user:48213", "aud": "orders-api",
"exp": 1790000000, "iat": 1789999100, "jti": "8f14e45fceea167a"}
print("minimal claims:", jwt_len(base), "bytes")
for n in (50, 200, 500):
fat = dict(base, perms=[f"tenant-{i:04d}:orders:read" for i in range(n)])
print(f"{n} permission strings:", jwt_len(fat), "bytes")
minimal claims: 319 bytes
50 permission strings: 2066 bytes
200 permission strings: 7266 bytes
500 permission strings: 17666 bytes
Each permission string like tenant-0004:orders:read is 23 raw characters; as one element of a JSON array that is 26 bytes (23 plus 2 quote bytes plus a comma), and base64url encoding then expands every 3 raw bytes into 4 encoded characters, a 4/3 blow-up, so each permission costs about 26 x 4/3 ~= 34.7 bytes in the final token. That matches the numbers above exactly: 200 permissions minus 50 is 7266 - 2066 = 5200 bytes over 150 permissions, 5200 / 150 ~= 34.7 bytes each. nginx's default buffer for one large request header line is 8 KB, so a user with a few hundred permissions starts getting unexplained 4xx errors at the proxy, and a 7 KB header repeated across 6 hops is 42 KB of overhead per request. The fix is structural, not compression: keep identity claims (sub, aud, exp, iat, jti, tenant, maybe a coarse role) in the token and resolve permissions at decision time from the PIP. Using ES256 rather than RS256 also helps: its signature is 64 bytes versus 256 bytes for a 2048-bit RSA key.
5. Fine-grained authorization downstream
Three options, and where each fits:
| Pattern | What it is | Use it when |
|---|---|---|
| Authorization middleware in each service | A shared library checks scopes and simple rules in-process | Coarse checks: "does this token have orders:write?" |
| Centralized PDP (policy-as-a-service) | Services call one authorization service per decision | Relationship-heavy rules ("can this user edit this document?") where the data is large and central |
| Distributed PDP: policy sidecar with pushed bundles | Policies authored centrally (PAP), compiled into bundles, pushed to a sidecar next to each service (Open Policy Agent, OPA: a widely used open-source policy engine that evaluates authorization rules written in its own policy language, is the common one) | The default for hundreds of services: sub-millisecond local decisions, no central runtime dependency |
Recommendation: middleware for coarse scope checks, a sidecar PDP for most fine-grained rules, and a central relationship service only for resource-level sharing graphs. Every decision is logged with the policy version that produced it so an auditor can reconstruct why access was granted.
Trade-offs and pitfalls
- JWTs trade revocation for scale. The honest statement of the design is "internal access can outlive revocation by at most the internal token lifetime", and that lifetime is the knob.
- Token exchange adds a dependency. If the token service is down, cross-service calls fail. Run it per region, cache exchanged tokens, and treat it with the same SLO (service-level objective) as the edge.
- Do not let services mint their own internal tokens. Only the token service holds signing keys; services only verify.
- Policy drift: sidecars running stale bundles make inconsistent decisions. Export the bundle version each sidecar is running and alert when any lags the published version beyond a threshold.
- Common wrong turn: using the same token for user identity and service identity. Keep them separate: the certificate says which service, the token says which user.
Design a key rotation protocol for asymmetric signing keys used to issue tokens across 1,000 services with 200k tokens in flight. Requirements: avoid downtime, let tokens signed with the old key keep verifying for a bounded period after rotation, and eventually retire the old key everywhere. Walk through how you would publish and roll over keys, how verifiers would handle the transition, and how SREs should monitor the rollout and roll back if something goes wrong.
Sample Answer
Direct answer
Rotate in three phases driven by two numbers: C, the longest time a verifier can go without refreshing its key set, and T, the maximum token lifetime. First publish the new public key alongside the old one and wait at least C until telemetry shows verifiers have it. Then switch signing to the new key. Then keep the old public key published for at least T (plus clock skew) so every token signed before the switch can still verify, and only then remove it and destroy its private key. Every token carries a kid (key ID) so verifiers pick the right key, and the whole rollout is watched through per-kid verification metrics, with rollback possible at every phase until the old private key is destroyed.
Terms
- Asymmetric signing: the issuer signs with a private key; verifiers check with the public key. Only the issuer needs protecting; verifiers can be many.
- JWKS (JSON Web Key Set): a published JSON document listing current public keys, each with a
kid. Tokens name thekidin their header (RFC 7517 defines the format). - Grace window: the bounded period after rotation when tokens signed by the old key still verify.
Setup and numbers
- 1,000 services, assume 20 instances each: 20,000 verifiers.
- 200,000 tokens in flight, maximum lifetime T = 60 minutes, so the issuer mints about 200,000 / 3,600 s, about 56 tokens per second.
- Verifiers cache the JWKS for C = 15 minutes. Refresh load is 20,000 / 900 s, about 22 requests per second: trivial, especially if the JWKS is a static file on a CDN (content delivery network).
- Allowed clock skew between issuer and verifiers: s = 5 minutes.
The protocol
sequenceDiagram
participant I as Issuer
participant J as JWKS endpoint
participant V as Verifiers
I->>J: Phase 1 publish K1 and K2, still sign with K1
V->>J: refresh within C
Note over V: telemetry shows K2 cached on most verifiers
I->>I: Phase 2 sign new tokens with K2
Note over V: K1 tokens still verify, grace window T plus skew
I->>J: Phase 3 remove K1
V->>J: refresh, K1 gone
I->>I: destroy K1 private key
Phase 1: pre-publish (duration at least C, ends on telemetry).
The JWKS now lists old key K1 and new key K2; the issuer still signs only with K1. Nothing verifies against K2 yet, so this phase cannot break anything. It ends when (a) at least C = 15 minutes have passed and (b) at least 99.9% of verifiers report K2 in their cached key set. Verifiers export a gauge (a metric that reports the current value, unlike a counter that only ever goes up) of the kid values they hold, so (b) is measured, not assumed.
Phase 2: switch signing (grace window at least T + s).
The issuer signs every new token with K2. A verifier that somehow missed the refresh sees an unknown kid and must refetch the JWKS immediately rather than reject. Verifiers accept K1 and K2 throughout. Old K1 tokens drain naturally: the last one issued just before the switch, say at 09:00:00, has exp (expiry) set to 10:00:00, 60 minutes later. Now add the skew: a verifier whose clock runs up to 5 minutes slow could, at the issuer's real time of 10:03, still read its own clock as 09:58 and correctly consider that token not yet expired. If K1 had already been removed from the JWKS at 10:00, that verifier would fail to find the key for a token it is right to still trust. So K1 must stay published for at least T + s, 65 minutes, not just T.
Phase 3: retire.
Remove K1 from the JWKS. Within another C = 15 minutes every verifier has dropped it. Confirm that K1 verification counts are zero, then destroy the K1 private key.
Minimum end-to-end time: 15 + 65 + 15 = 95 minutes. In practice run it over a day (pre-publish for hours, not minutes) because extra waiting costs nothing and absorbs stragglers.
How verifiers must behave
- Select the key by
kid; never try every key (that turns an unknown-kidattack into many signature checks). - On unknown
kid, refetch at most once per 30 seconds per instance. Rate limiting matters: an attacker spraying tokens with randomkidvalues could otherwise make 20,000 instances hammer the endpoint. With the limit, the worst case is 20,000 / 30, about 667 requests per second, which a CDN-served static file absorbs. - If the JWKS endpoint is unreachable, keep using the cached set (with an alert) rather than failing all verification.
- Pin the algorithm per key (from the JWKS entry), never from the token header, to block algorithm-substitution attacks: a forged token can set its own header to claim any algorithm it likes: the classic version names a symmetric algorithm (HMAC) instead of the real asymmetric one, then "signs" the token using the issuer's own public key, which anyone can read from the JWKS, as if it were a shared HMAC secret. A verifier that blindly trusts whatever algorithm the header names will hash the token with that same public value and get a matching signature, accepting a forgery. Pinning the algorithm to what the JWKS says that
kidactually uses closes that off.
Monitoring
| Signal | What it tells you | Alert when |
|---|---|---|
| Verifiers holding K2, as a share of fleet | Phase 1 readiness | below 99.9% after 2 x C |
Verification success rate by kid | Traffic shifting from K1 to K2 | any drop in overall success after the switch |
unknown_kid failures | A verifier did not refresh, or an attack | above baseline |
| K1 verifications after the switch | Drain progress | non-zero after T + s (something is minting with K1 or caching tokens too long) |
| JWKS endpoint request rate and errors | Refresh storms | sudden spikes |
Rollback
- During phase 1: remove K2 from the JWKS. No token was ever signed with it, so nothing breaks.
- During phase 2: switch signing back to K1, which is still published and whose private key still exists. Tokens already signed with K2 remain valid until they expire because K2 stays published. This is why the old private key is not destroyed until phase 3 has succeeded.
- After phase 3: rolling back means a new rotation, not a revert.
Compromised key: a different protocol
If K1 is rotated because it leaked, the grace window is the vulnerability: an attacker can mint K1 tokens for as long as verifiers accept K1. So remove K1 from the JWKS immediately, push a "refresh now" signal to verifiers instead of waiting for C, and accept that all 200,000 in-flight tokens become invalid. That forces re-authentication: if clients retry within 5 minutes, the issuer must absorb 200,000 / 300 s, about 667 issuances per second, about 12 times the steady 56 per second. Size the issuer, and give clients jittered retries (retries with a randomised delay, so thousands of clients invalidated at once don't all retry in the same instant and overwhelm the issuer), for that event before you need it.
Trade-offs and pitfalls
- Shorter T shortens every rotation and every compromise window, but raises issuance load and dependence on the issuer.
- Longer C reduces endpoint load but lengthens phase 1 and delays compromise response; push-based refresh (the issuer actively notifying verifiers the moment a key changes, instead of verifiers only finding out whenever their own polling interval C next comes around) gives you both.
- Double-signing (issuing each token under both keys) is only needed when verifiers cannot fetch key sets dynamically; with
kid-based JWKS it adds token size for no gain. - Common wrong turn: switching signing and publishing the new key in one step. For up to C minutes, some verifiers reject every new token.
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.
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 17 Distributed Systems Security and Trust interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.