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.
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 multi-region TLS termination strategy for a global API gateway with three goals: low latency for users, compliance with region-specific key residency rules, and the ability to provide end-to-end encryption when required. Describe where to terminate TLS (edge vs origin), your key management approach, and the SRE operational model for certificate issuance, rotation, and emergency key compromise.
Sample Answer
Direct answer
Terminate TLS at the edge by default, because a handshake with a server 20 ms away instead of 150 ms away is the biggest latency win you can buy. Then carve out two exceptions by hostname: regulated hostnames terminate only on in-region infrastructure, with their private keys held in that region's HSM (hardware security module) or cloud key management service and never exported, and end-to-end hostnames pass through the edge at layer 4 (layer 4 is the raw TCP connection: the edge forwards bytes without looking inside them, as opposed to layer 7, the HTTP level, where it can read and act on the request itself) so TLS terminates at the origin. Everything from edge to origin is re-encrypted with mutual TLS (mTLS, where both sides present certificates). Certificates are issued and rotated automatically via ACME, short-lived, with a rehearsed runbook for key compromise that can replace a certificate everywhere within an hour.
Why edge termination is the default
A new HTTPS connection costs one round trip for the TCP handshake and one for a TLS 1.3 handshake (TLS 1.2 needs two), before the first request byte is sent.
| Where TLS terminates | User RTT (round-trip time) | Setup before first request (TCP + TLS 1.3) |
|---|---|---|
| Origin in another continent | 150 ms | 2 x 150 = 300 ms |
| Edge PoP (point of presence) nearby | 20 ms | 2 x 20 = 40 ms |
The edge then reuses warm, long-lived connections to the origin (connections it keeps open and shares across many users' requests instead of opening and tearing one down per request), so the user never pays the long round trips for setup. Terminating at the edge also lets the edge do its layer 7 jobs: WAF (web application firewall) rules, rate limiting, caching, routing by path.
The cost: at the point of termination, traffic is plaintext in the edge's memory, and the edge holds (or can use) the private key. That is exactly what residency and end-to-end requirements object to.
The three tiers
flowchart LR
U[User] --> E{Edge PoP}
E -- "default: terminate, WAF, re-encrypt mTLS" --> O1[Origin any region]
E -- "regulated host: geo-pinned, in-region PoP only" --> R[In-region edge] --> O2[In-region origin]
R -. "signing request" .-> H[(In-region HSM / KMS key)]
E -- "e2e host: L4 passthrough by SNI" --> O3[Origin terminates TLS]
Tier 1: default (most APIs)
Terminate at the nearest PoP; keys are distributed to the edge fleet encrypted, decrypted only in memory. Re-encrypt to the origin with mTLS using an internal CA (certificate authority, the service that signs certificates), so a network observer between edge and origin sees nothing and the origin rejects anything that is not the edge.
Tier 2: key residency (for example, EU-regulated customers)
Two separate requirements get conflated here; separate them in the interview:
- Key residency: the private key must not leave the region. Solve it with remote signing: the edge performs the handshake, but the one operation that needs the private key (signing the handshake) is sent to a key server inside the region, backed by an HSM. The key never leaves. Several CDNs (content delivery networks) offer this as a product; you can also build it.
- Data residency: the decrypted traffic must not be processed outside the region. Remote signing alone does not satisfy this, because session keys (the symmetric keys the handshake negotiates, and that actually encrypt and decrypt the real traffic afterward) and plaintext still exist at whichever PoP terminated the connection. For that, route the regulated hostnames so termination only happens in-region, restricted to in-region PoPs via geo-DNS (DNS that returns a different answer depending on where the query came from) or anycast (one IP address announced from many PoPs, where the network itself routes each user to the nearest one).
Commit: for regulated hostnames, do both. The latency cost is small for users who are in the region, which is almost everyone the regulation covers; out-of-region users pay the longer round trip, and that is the price of compliance.
Tier 3: end-to-end encryption when required
Options, in order of preference for a strict "the edge must never see plaintext" requirement:
- Layer 4 passthrough: the edge reads only the SNI (server name indication, the hostname sent in clear in the TLS ClientHello, the very first message a client sends to start a TLS handshake, before anything is encrypted) and forwards the encrypted bytes to the origin, which terminates TLS. You lose edge caching, WAF and path routing for that host; move WAF and rate limiting to the origin.
- Application-layer encryption: keep edge termination, but encrypt sensitive payload fields with a key only the origin holds (for example JWE, JSON Web Encryption). The edge still routes by headers. Good for specific fields (card numbers, health data), not whole APIs.
"Re-encrypt at the edge" is not end-to-end, even though it is encrypted everywhere on the wire; say that explicitly.
Key management
- One key pair per hostname group (a set of hostnames that share a certificate and routing tier, for example all default-tier API hosts together) per region; no global wildcard certificate (one certificate valid for every hostname under a pattern like
*.example.com) whose key lives on every PoP (one leak compromises everything). - Regulated keys: generated inside the regional HSM, non-exportable, usable only by the regional key server's identity.
- Default-tier keys: generated centrally, wrapped (encrypted) under a per-region key-encryption key held in KMS, and unwrapped only in PoP memory.
- Internal mTLS between edge and origin uses a separate private CA with short-lived certificates (hours to days), so revocation is rarely needed.
SRE operational model
Issuance and rotation
- Automate with ACME (Automatic Certificate Management Environment, RFC 8555), the protocol public CAs use for automated issuance, and treat any manual step as a defect. The CA/Browser Forum has voted to shrink the maximum public certificate lifetime in steps from 398 days to 47 days between March 2026 and March 2029, so manual renewal will not survive.
- Renew at about two thirds of lifetime; roll out new certificates region by region with a canary PoP; keep the previous certificate deployable for fast rollback.
- Use two public CAs, pre-authorised via DNS CAA records (which list the CAs allowed to issue for your domain), so a CA outage or distrust event does not block renewal.
- Monitor: days-to-expiry for every certificate on every PoP (alert at 14 days, page at 7), handshake failure rate by PoP and by certificate, and Certificate Transparency logs for certificates issued for your domains that you did not request.
Emergency key compromise
A worked timeline, assuming a default-tier key leaked from one PoP:
- 0 to 15 minutes: generate a new key and CSR (certificate signing request); request a new certificate from the backup-ready CA; isolate the PoP.
- 15 to 45 minutes: deploy the new certificate to all PoPs holding that hostname group, canary first.
- After deployment: ask the CA to revoke the old certificate with reason key compromise. Revoke after the new one is live, or you cause an outage. Browser revocation checking is unreliable: most browsers "soft-fail," meaning that if the revocation check itself times out or the network is unreachable, they treat the certificate as valid rather than blocking the page, and many skip the check for performance reasons in the first place. So a revoked certificate often keeps working for whoever already has it cached, and containment really comes from replacement and short lifetimes, not revocation.
- Follow-up: find how the key left, and check whether other keys shared the same exposure path.
For regulated keys in an HSM, "compromise" usually means misuse of the signing service rather than key theft: revoke the offending identity's access to the key server first, then rotate.
Trade-offs and pitfalls
- Treating remote signing as data residency is the most common wrong answer.
- Passthrough everywhere for simplicity throws away the edge's security controls; use it only on hosts that require it.
- Certificate pinning in mobile clients (hard-coding, inside the app, exactly which certificate or public key it will accept, instead of trusting any certificate a public CA has signed) turns routine rotation into an outage; pin to a CA or public key set with a backup, or do not pin.
- What would flip the design: if nearly all traffic were from one region with strict residency, a regional-only termination model (no global edge) becomes simpler and loses little latency.
A root signing key used to mint service identity certificates was discovered to be compromised. You are the SRE lead. Produce an incident response and remediation plan: immediate containment and revocation steps, how to remove the compromised trust anchor, re-issue a new CA and rotate workload certificates at scale (millions of instances), communicate with external partners, and minimize downtime while making the system secure again. Discuss cryptographic constraints, rollback strategies, and monitoring to verify success.
Sample Answer
Direct answer
A compromised root is not something you can "revoke" in the usual sense: a root CA (certificate authority) is a trust anchor, a key every workload trusts because it is in their configured trust bundle, and the only way to stop trusting it is to remove it from every bundle. So the plan is: stop the bleeding (freeze the compromised key, hunt for attacker-minted certificates, shrink what the old root can vouch for), stand up a new root in a clean ceremony, run a short dual-trust window in which workloads trust both roots while every certificate is re-issued from the new one, then remove the old root everywhere and verify that nothing still presents or accepts it. Downtime is avoided by ordering: trust the new root first, re-issue second, distrust the old root last. The hard constraint is that during the dual-trust window the attacker's certificates are still trusted, so that window must be short and watched.
Phase 0: first hour, containment and scoping
- Declare the incident, name an incident commander, open a war room, start a timeline. Legal and communications join now, not later.
- Freeze the key: disable the compromised key in the HSM (hardware security module), revoke every credential and role that could invoke it, and stop all automated issuance that chains to it. Preserve logs and host images for forensics.
- Scope the compromise: was the key exfiltrated (copied out, so the attacker can sign anything, forever) or was the signing service abused (the key never left; the attacker could only request signatures during a known window)? The second case is much smaller: every certificate the attacker got is in your issuance logs.
- Hunt attacker certificates: compare every certificate seen in the wild (mesh proxy handshake logs: the connection logs a service mesh, the network of small proxies, one per workload, that carries and secures service-to-service traffic, writes each time its proxies complete a TLS handshake, the negotiation in which client and server exchange and verify certificates before encrypted traffic starts; plus load balancer logs) against your issuance log. Any certificate that chains to the root but is not in your log is attacker-minted and tells you what they are impersonating.
- Short-term guardrails while you prepare the replacement: tighten authorisation so that high-value services (payments, identity, secrets) accept only an allowlist of SPIFFE IDs (workload identity names under the SPIFFE standard, Secure Production Identity Framework For Everyone) or certificate serials (the unique serial number stamped on each certificate you issue, so you can allowlist exactly the ones your own issuance log shows as legitimate) you issued; raise alerting on new identities appearing.
Phase 1: build the new trust anchor
- Ceremony: generate the new root offline in an HSM with M-of-N custody (for example 3 of 5 custodians must be present), witnessed and recorded. Do not reuse any host, HSM partition, pipeline or credential from the old chain until forensics clears it.
- Design it to fail smaller next time: a certificate chain has three tiers: the root (the offline trust anchor itself), intermediates (subordinate CAs the root signs once, which do the day-to-day signing so the root never has to come online), and leaf certificates (the end-entity certificates a workload actually presents on a connection, signed by an intermediate). Keep the root offline and issue per-region or per-environment intermediates, each with a path length constraint of 0 (it can sign leaf certificates but not further CAs) and, where your clients enforce them, name constraints (limit which names or URI SANs, the subject alternative names that carry SPIFFE IDs, an intermediate may certify). A future intermediate compromise then affects one region, and the root never touches the network.
- Do not cross-sign the new root with the old one. Cross-signing means having one root issue a certificate over the other root's public key, so anyone who already trusts root A automatically trusts anything root B signs too; that is how you migrate trust between two healthy roots, but here it would let the untrusted old root vouch for the new one, handing the attacker a path back in.
Phase 2: dual trust, then rotate millions of workloads
flowchart LR
A[Bundle: old root only] --> B[Bundle: old + new root]
B --> C[Re-issue all leaf certs from new chain]
C --> D[Bundle: new root only]
D --> E[Verify: no old-chain handshakes]
C -. "rollback target" .-> B
Step A to B, push the new bundle. Every workload must trust the new root before anything presents a new-chain certificate, or handshakes fail. Distribute through the normal channel (the mesh's trust bundle distribution, SPIRE, the SPIFFE Runtime Environment, or the service mesh control plane) and gate the next step on telemetry: 100% of proxies reporting the new bundle version.
Step B to C, re-issue at scale. Workloads fetch new leaf certificates from the new intermediates. This plan commits to a 6-hour re-issuance window as the target (a business-hours window with slack for retries and backoff); 2 hours is shown only as the aggressive case worth checking your infrastructure against, not a promise the plan makes. Capacity arithmetic for 2 million instances:
6 h×3,600 s/h2,000,000 certs≈92.6 signatures/s (the committed target),2×3,6002,000,000≈277.8 signatures/s (the aggressive case)Split across regional intermediates both rates are modest, but verify each against your issuer's measured signing rate and your HSM's, and add jitter so 2 million agents do not stampede in the first minute. Roll out by ring (deploy in expanding waves, each one gated on the previous wave's health before the next starts): internal tooling, then one low-risk region, then the rest, with automatic pause on handshake-error spikes. Workloads keep serving while they rotate; existing connections complete, and new connections use the new certificate.
Step C to D, distrust the old root. Once telemetry shows no workload presenting an old-chain certificate, push bundles containing only the new root. This is the moment the attacker's certificates stop working.
Window length: this whole A-to-D sequence should be hours, not weeks. If automation allows, target same day. The window is your exposure.
External partners
- Notify partners who trust your root (federation, mTLS (mutual TLS) integrations where both sides present certificates, customer devices) with: what happened at a level legal approves, the new root's fingerprint (a short cryptographic hash of the root certificate, unique enough that comparing it byte for byte confirms a partner has the genuine new root and not a substitute), and a firm deadline for removing the old one.
- Deliver the fingerprint out of band (a signed advisory on a separate channel plus a phone confirmation between named contacts), never only in an email that could come from the attacker.
- Offer a validation endpoint partners can test against before the cutover; track each partner's status on a board. Partners who miss the deadline lose connectivity rather than keeping a compromised trust path open, and that decision is made in advance by an executive, not improvised.
Cryptographic constraints to plan around
- No CRL (certificate revocation list) or OCSP (Online Certificate Status Protocol) for roots. Revocation lists are signed by the issuer; a root's "revocation" would be signed by the compromised key itself. Bundle removal is the only mechanism.
- Every certificate issued under the old root is untrustworthy, including legitimate ones, because the attacker can mint identical-looking ones. Everything gets re-issued.
- Pinned and embedded roots (firmware, mobile apps, appliances, partner configs) cannot be updated by your control plane. Inventory them first; they set your real deadline.
- Clock skew: issue new certificates with a small backdated
notBeforeso slightly slow clocks do not reject them. - Algorithm choice: take the opportunity to use the current recommended key type (for example ECDSA, the elliptic curve digital signature algorithm, on P-256 or P-384) and plan how you would do this again; the rotation you are rehearsing now is also your future crypto-agility.
Rollback strategy
Rollback never means going back to trusting only the old root. The safe rollback target is the dual-trust state (B): if re-issued certificates break something, revert those workloads to their old-chain certificate, which still works in state B, fix, and retry. Keep bundle versions immutable and numbered so "roll back to bundle v41" is one command. Once you reach state D, rolling back re-opens the attacker's access, so it requires incident-commander sign-off.
Monitoring to verify success
- Bundle version per proxy (target 100% on each step before moving on).
- Handshakes by issuing chain: old-chain presentations should fall to zero before step D, and old-chain acceptances must be zero after it.
- Handshake failure rate per service and region during each ring (the canary signal for pausing).
- Certificates observed that are absent from the issuance log (should be zero on the new chain; any hit is a new incident).
- Partner cutover status and synthetic probes from partner-like clients.
Trade-offs and pitfalls
- Speed vs safety: a same-day rotation risks breakage; a slow one leaves the attacker trusted. Pre-built automation and quarterly root-rotation drills are what let you have both.
- Minimising downtime by skipping step A (pushing new certificates before new trust) is the classic self-inflicted outage.
- Forgetting non-mesh consumers (batch jobs, databases with client-certificate authentication, VPN concentrators) leaves pockets that break at step D or, worse, keep trusting the old root silently.
Extend CAP-style reasoning to include security properties (confidentiality and integrity), not just availability and consistency. For a multi-region user-data access service, describe scenarios where you would favor availability over integrity or confidentiality, and vice versa, propose concrete SRE-level metrics and SLOs that would let you measure your security posture the way you measure reliability, and explain how you'd enforce policy decisions during a network partition.
Sample Answer
Direct answer
CAP says that during a network partition (regions that cannot talk to each other) a system must choose between availability (every region keeps answering) and consistency (every answer reflects the latest write). Security state is data too: a permission revocation is a write, and every access check is a read of it. So during a partition, a region that keeps serving access checks may be serving stale permissions, which is a confidentiality or integrity failure, not just a consistency one. The practical answer is to stop making one global choice and instead classify operations by the harm a stale decision can do: low-risk reads stay available on cached policy within a staleness budget, while high-risk actions (anything that grants, moves money, exports data, or acts on a recent revocation) fail closed, meaning the system refuses the request rather than risk acting on stale or unverifiable policy, the opposite of fail open, where it would let the request through by default. Then measure security the way SREs measure reliability, with SLIs (service-level indicators) and SLOs (service-level objectives) for things like revocation propagation time and decisions made on stale policy.
Mapping CAP onto security properties
| CAP term | Security reading for a multi-region user-data service |
|---|---|
| Consistency | Every region enforces the current policy: a revoked user is denied everywhere, a changed ACL (access control list) applies everywhere |
| Availability | Every region keeps answering reads and writes, even while cut off |
| Confidentiality | Data is read only by principals (the identities, human users or services, that a policy grants or denies access to) currently entitled to it. Stale "allow" decisions violate it |
| Integrity | Data is changed only by entitled principals, and conflicting writes do not silently corrupt it. Accepting writes on both sides of a partition can violate it |
The key insight: confidentiality and integrity both depend on consistency of authorization state. If region B cannot hear from region A, B cannot know whether a revocation happened there. So "security-CAP" is really: during a partition, you cannot both keep every region answering and guarantee every answer honours the latest security change.
When to favour availability over confidentiality or integrity
- Reading low-sensitivity data with a recently valid decision. A user browsing their own public-profile settings in region B, with policy last synchronised 90 seconds ago. The worst case is that a user revoked in the last few minutes sees non-sensitive data they saw yesterday. Denying all traffic in a partitioned region to prevent that is a larger harm.
- Emergency or safety workflows. A hospital clinician reading a patient's allergy record during a partition: the harm from denial exceeds the harm from a stale grant. This is a documented, audited break-glass path (a deliberate override that is always logged and reviewed), not a silent fail-open.
- Appending audit events. Keep accepting audit writes locally during a partition and reconcile later; losing them is worse than delayed ordering.
When to favour confidentiality or integrity over availability
- Anything touching a recent revocation. If a user or credential was revoked, the reason is usually compromise. A partition is exactly when an attacker benefits from stale state.
- Privilege changes. Granting a role, creating API keys, changing sharing settings. Accepting these in a minority region, the side of a network partition that cannot reach a majority (quorum) of the other regions, and so cannot be sure its view of policy is current, risks a conflicting grant that survives reconciliation.
- Bulk or sensitive reads. Data exports, reads of regulated fields (health data, payment data), admin consoles.
- Money and irreversible actions. An integrity failure here cannot be reconciled away.
Enforcing policy during a partition
- Every policy decision point (PDP) carries a policy version and a freshness lease. Each region's PDP holds the last policy snapshot it received and a lease (a time-limited promise) renewed by the authoritative policy store, for example every 10 seconds with a 5-minute validity.
- Tier each operation at design time: tier 0 (low risk, may use stale policy up to 5 minutes), tier 1 (moderate, stale up to 30 seconds), tier 2 (grants, exports, admin, money: requires a lease that is current, which effectively means the region must be able to reach a quorum, a majority of regions).
- During a partition, when the lease lapses: tier 2 fails closed with a clear error ("temporarily unavailable, try again"); tier 1 fails closed after 30 seconds; tier 0 continues until its budget is exhausted, then fails closed too. Every decision taken on stale policy is logged with its policy version and staleness.
- Deny wins and revocations travel first. Revocations are replicated on a priority channel; any region that has received a revocation applies it immediately even if its full policy snapshot is older. A partitioned region can apply a denial it knows about but cannot grant anything new.
- Security-state writes need a quorum (2 of 3 regions). The minority side of a partition becomes read-only for policy, so two sides cannot make conflicting grants.
- Reconcile after healing: replay stale-policy decisions from the log against the policy that was actually current, and alert on any that would have been denied. This turns an invisible risk into a reviewable list.
Security SLIs and SLOs
An SLI is a measured quantity; an SLO is the target for it over a window. These are designed to be computed from telemetry the way latency and error-rate SLOs are:
| SLI | How to measure | Example SLO (30-day window) |
|---|---|---|
| Revocation propagation latency | Time from revoke write to the moment every region's PDP rejects that credential; measure continuously with synthetic canary credentials that are issued and revoked every minute and probed in every region | 99.9% of revocations enforced in all regions within 60 s |
| Stale-decision rate | Fraction of decisions made on any policy snapshot that is not the region's current one, i.e. served during a lease lapse (partition or slow propagation), whether or not that decision was still inside the tier's staleness budget | Below 0.01% of decisions |
| Unauthorized-access rate | Probes with revoked or out-of-scope canary credentials that were allowed | Zero; any single event pages |
| Fail-open count | Decisions where the PDP could not evaluate and allowed by default | Zero outside a declared break-glass |
| Policy version skew | Maximum difference between the newest and oldest active policy version across regions | Under 2 minutes at p99 (99th percentile) |
| Audit completeness | Events received by the audit store divided by events emitted (via per-source sequence numbers) | 99.99% within 5 minutes |
Worked example of an error budget (the amount of a metric's SLO you are allowed to "spend" in a period before you have breached it, the same idea SREs use for availability, applied here to a security metric): at 5,000 decisions per second, a 30-day window holds 5,000 x 86,400 x 30 = 12,960,000,000 decisions. A 0.01% stale-decision SLO allows 1,296,000 stale decisions in the month. Take a 10-minute (600 s) partition where region C, a third of traffic, serves tier-0 reads on stale policy: per step 3 above, tier 0 only continues until its 5-minute (300 s) budget is exhausted and then fails closed, so it serves stale-policy reads for 300 of those 600 seconds, not all 600. Assuming, for this illustration, that region C's traffic in that window is entirely tier-0 (tier 1 would already have failed closed after 30 s and tier 2 immediately, so neither adds to this count), that consumes about 5,000 / 3 x 300 = 500,000 decisions, roughly 39% of the month's budget in one event. That number is what turns "should we tighten tier-0 staleness?" from an opinion into a decision, exactly as error budgets do for availability.
With 20,000 revocations a month, the 99.9% revocation SLO allows at most 20 revocations to take longer than 60 s. Canary probes measure this continuously rather than relying on real revocations, which are too rare and too sensitive to serve as the only signal.
Trade-offs and pitfalls
- One global switch (fail open or fail closed for everything) is the most common wrong answer: it either lets a partitioned region serve revoked users, or turns every network blip into a full outage.
- Unbounded caching of allow decisions is fail-open in disguise. Every cached decision needs an expiry tied to the tier.
- Break-glass without review becomes the everyday path. Require a reason, log it, and review every use.
- Security SLOs need synthetic probes. Real attacks are rare, so an SLO computed only from real traffic will look perfect until the day it matters.
- Tiering is a product decision. Engineers propose the tiers; data owners and security sign off, because the question "is a 5-minute stale read of this data acceptable?" is a risk decision, not a technical one.
Design a distributed policy decision point (PDP) for authorization that must serve 1,000 decisions/sec with a 50ms latency SLA across three regions, while preventing privilege escalation during partitions. Describe how to store and replicate policies, your caching strategy at local PDPs, decision versioning, how to roll back a bad policy quickly, and the operational monitoring and audit logging compliance requires.
Sample Answer
Direct answer
At 1,000 decisions per second the hard part is not throughput, it is correctness across regions under a 50 ms budget. A cross-region round trip alone can use most of that budget, so every region must evaluate decisions locally from an in-memory copy of policy. I would keep policy as code in a single authoritative store, compile it into signed, immutable, versioned bundles, and distribute them to stateless (holding no durable state of its own between requests, so any instance can be replaced or added with no handoff) PDP (policy decision point: the component that answers "may subject S do action A on resource R?") instances in every region. Permission data (group memberships, relationships) replicates separately with a version token. Grants require a quorum (a majority, 2 of the 3 regions), revocations propagate on a priority path and "deny wins", and a region that loses contact with the quorum keeps serving only within a bounded staleness window before sensitive actions fail closed (are refused rather than risk granting something a fresher policy would deny). Rollback is repointing an "active version" pointer to the previous bundle, which takes one propagation cycle.
Requirements I am designing to
- 1,000 decisions/sec total, say split roughly evenly across three regions (about 333/sec each), with bursts of 3x.
- 50 ms p99 (99th percentile) decision latency, measured at the caller.
- No privilege escalation during partitions: a partitioned region must never grant something the authoritative policy would deny, beyond a small, measured staleness bound for low-risk reads.
- Fast rollback, and a full audit trail for compliance.
Architecture
flowchart TB
G[Policy repo<br/>reviewed and tested] --> B[Bundle builder<br/>compile, sign, version]
B --> S[(Bundle store<br/>immutable versions)]
P[Active-version pointer<br/>quorum across 3 regions] --> S
S --> R1[Region 1 PDPs]
S --> R2[Region 2 PDPs]
S --> R3[Region 3 PDPs]
D[(Permission data<br/>quorum writes)] --> R1
D --> R2
D --> R3
R1 --> L[Decision logs<br/>append-only audit]
R2 --> L
R3 --> L
Policy storage and replication
- Policy as code. Rules live in a version-controlled repository. Every change is reviewed, unit-tested against a suite of expected decisions, and compiled into a bundle.
- Bundles are immutable and signed. Each bundle has a content hash as its version and a signature from the build system. PDPs refuse unsigned or unverifiable bundles, so a compromised distribution channel cannot inject policy. Open Policy Agent (OPA, a widely used open-source policy engine) supports exactly this: signed bundles with a
.signatures.jsonfile and arevisionfield in the manifest. - One active-version pointer, written only through a quorum of the three regions, for example with etcd, a strongly consistent key-value store spanning them that uses Raft, a consensus protocol in which a majority must agree on each write. With 3 regions, a write needs 2, so a single partitioned region cannot change which policy is active.
- Permission data (who is in which group, who owns which document) is also written with quorum and carries a monotonically increasing data version (a number that only ever goes up, so comparing two version numbers always tells you unambiguously which is newer). Callers that just changed a permission can pass the returned version token, and the PDP answers only once it has data at least that fresh. Concretely: revoking Bob's access to a document returns
data_version: 4821; if the caller then shares a new secret with that same document a second later, it attachesdata_version: 4821(or later) to the follow-up read check, so a PDP replica still showingdata_version: 4820blocks and waits for fresher data (or forwards to one that has it) instead of answering from a copy that predates the revocation. This is the "new enemy" problem Google's Zanzibar paper (the 2019 paper describing the global authorization system behind Google Docs, Drive and similar products) describes: without it, a user removed from a document and then a new secret added to it could still read the secret from a stale replica.
Caching at local PDPs
Three layers, each bounded:
- The bundle itself is the cache. Each PDP holds the full compiled policy in memory. Evaluation is local computation with no network call.
- Permission data is held in a regional replica with a known replication lag, read from memory or a local store.
- Decision cache keyed by (subject, action, resource, bundle version, data version) with a short TTL (time-to-live), for example 5 seconds. Including both versions in the key means a new bundle or data change automatically invalidates old entries, with no invalidation protocol needed.
Latency budget (50 ms, illustrative split)
| Step | Budget |
|---|---|
| Caller to regional PDP (same region, one network hop) | 5 ms |
| Load-balancer and queueing headroom | 10 ms |
| Policy evaluation in memory | 5 ms |
| Permission-data lookup (regional replica) | 10 ms |
| Reserve for p99 tail | 20 ms |
These are budget allocations, not measurements. The point they make: there is no room for a cross-region call on the decision path, so any design where a PDP asks another region at decision time fails the SLA (service-level agreement).
Capacity
About 333 decisions/sec per region is small. Run at least 3 PDP instances per region across availability zones (physically separate data centers within the region, each with independent power and networking, so one zone failing does not take the others down with it) so losing a zone and doing a deploy at the same time still leaves capacity, and load-test to find the real per-instance ceiling rather than assuming one. A single modern instance could likely handle 333 decisions/sec alone, so the reason to run three per region is not throughput, it is that losing one zone or rolling a deploy must never drop capacity below what the SLA needs: capacity is set by availability, not by load.
Decision versioning
Every decision response and log record carries: decision_id, bundle_version (content hash), data_version, pdp_id, region, and the rule that matched. This lets you answer, months later, "why was this allowed?" by re-running the exact inputs against the exact bundle, and it lets monitoring detect a PDP answering on an old bundle.
Preventing privilege escalation during partitions
Privilege escalation during a partition happens in two ways, and the design blocks both:
- A stale allow: a revocation happened in region 1, region 3 has not heard. Mitigations: revocations replicate on a priority path separate from full bundles; deny rules override allow rules (so a PDP that has received a revocation applies it immediately); each PDP holds a lease (a time-limited authorization to keep serving) renewed from the quorum every 10 seconds. When the lease lapses, high-risk actions (grants, exports, admin) fail closed at once, and low-risk reads continue for a fixed budget (for example 5 minutes) with every such decision flagged in the log.
- A conflicting grant: the minority region accepts "make Bob admin" while cut off. Blocked because policy and permission writes require the 2-of-3 quorum; the minority side is read-only for security state.
Never fail open on PDP errors. If a PDP cannot evaluate, the answer is deny, and the fail-closed count is an alerted metric.
Rolling back a bad policy quickly
- Before it ships: policy unit tests, then shadow evaluation: the candidate bundle runs beside the active one on live traffic, and any decision that differs is logged. A diff rate above an agreed threshold (say 0.1% of decisions) blocks promotion.
- Staged rollout: activate in one region first, watch deny rate and error rate for 10 minutes, then the others.
- Rollback is writing the previous bundle hash to the active-version pointer (one quorum write). PDPs poll or are notified; with a 10-second poll interval, the fleet is back on the old policy within roughly one interval plus download time. Because bundles are immutable, "the old policy" is byte-for-byte what ran before.
- Break-glass: a documented, audited way to roll back even if the build pipeline is down, using a pre-signed last-known-good bundle.
Monitoring and audit logging
Operational metrics: decision latency p50 (median) and p99 (99th percentile, defined above) per region; bundle version per PDP and version skew across the fleet; lease age; deny rate and allow rate per application (a sudden change after a policy push is the fastest signal of a bad policy); fail-closed count; decisions served on stale data.
Audit log for compliance: one record per decision with timestamp, decision_id, subject, action, resource, result, matched rule, bundle_version, data_version, pdp_id. Sensitive input fields are masked before shipping (OPA's decision logs support masking via a policy). Records go to append-only storage with write-once retention, batched and hash-chained (each record's stored hash also incorporates the previous record's hash, so altering or deleting one entry breaks every hash that comes after it) so deletion or editing is detectable. Policy changes are audited separately: who changed what, who approved it, which tests ran.
Sizing the audit volume, assuming about 600 bytes per record:
1000 sdecisions×600 B×86,400 days=51.84 GB/day 51.84 GB/day×365≈18.9 TB/yearThat is manageable uncompressed and much smaller compressed. If a regulator needs every decision, log them all; sampling allows is a cost option only where policy permits it, and denies should always be kept.
Trade-offs and pitfalls
- Centralised PDP in one region is simpler and always consistent, but its cross-region latency breaks the 50 ms SLA and makes that region a single point of failure for all authorization.
- Long decision-cache TTLs make revocation slow; the cache TTL is part of the revocation SLO and must be sized from it.
- Treating the bundle as the only state forgets the permission data: most real escalations come from stale group membership, not stale rules.
- Skipping shadow evaluation means the first time you see a policy's effect is when users do.
Unlock Full Question Bank
Get access to all 12 Distributed Systems Security and Trust interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.