Identity, Authentication, and Access Management Questions
Designing and operating identity and access control systems. Covers authentication protocols and standards (OAuth, SAML, OIDC, MFA), authorization models (RBAC, ABAC), identity lifecycle and privilege management, IAM architecture and automation, and access control across cloud and on-premises environments. The 'who can do what' control plane, distinct from cryptographic key management.
Explain secure mechanisms for storing and injecting secrets (API keys, DB passwords, signing keys) into CI/CD pipelines and runtime environments. Compare secrets vaults (HashiCorp Vault), cloud KMS, environment variables, and sealed secrets. Describe how to rotate secrets, audit access, and handle secrets in ephemeral build agents and containers.
Sample Answer
Direct answer
Treat "where does this secret live at rest" and "how does it get to the process that needs it at runtime" as two separate design questions. A secrets vault, such as HashiCorp Vault, or a cloud KMS (key management service) should hold the secret and hand it out on demand to an authenticated, authorized caller; environment variables and sealed secrets are injection mechanisms, not storage systems, and are only as safe as whatever actually populated them. The one rule that overrides all these choices: a secret a client application, a browser tab or a mobile app, can read is not really secret anymore, so nothing meant to stay confidential should ever ship inside client-side code or a mobile app bundle.
Structured elaboration
Secrets vaults (HashiCorp Vault). A dedicated service that stores secrets, authenticates callers via an auth method, for example a Kubernetes ServiceAccount token, a cloud IAM (identity and access management) role, or AppRole, Vault's own app-oriented auth mechanism, and can generate dynamic secrets on demand, a fresh, short-lived database credential minted per request, rather than only serving one static, pre-stored value shared forever. Vault's PKI (public key infrastructure) secrets engine can extend the same dynamic-issuance model to signing keys and certificates too, not just database or API credentials. This is the strongest option when you need audit trails, fine-grained access policy, and genuinely rotating, not just periodically-changed, credentials.
Cloud KMS. Primarily an encryption-key management service, not itself a general secrets store, though many teams use "encrypt the secret with a KMS-managed key, store the ciphertext somewhere ordinary, a config file, a database row, cloud storage" as a pattern. This gives strong at-rest protection and centralized control and rotation for the encryption key, but you still need your own access-control layer around who can request decryption, and it doesn't natively give you dynamic or ephemeral secrets the way a vault does.
Environment variables. The simplest injection mechanism: the orchestrator, a CI/CD (continuous integration/continuous delivery) system or the container runtime, populates an environment variable from wherever the actual secret is stored. Real weaknesses: environment variables are often visible to anything that can read the process's environment, including child processes, some debugging or introspection tools, and historically some logging or crash-reporting integrations that dump the full environment on error, and they tend to end up in shell history or CI logs if not handled carefully. Treat an environment variable as a delivery mechanism for a short-lived value fetched just-in-time from a vault or KMS, not as the secret's actual home.
Sealed secrets (for example, the Kubernetes Sealed Secrets controller pattern). Lets you encrypt a secret client-side with a public key so the encrypted blob is safe to commit to source control for GitOps, and only the controller running in-cluster, holding the matching private key, can decrypt it back into a normal Kubernetes Secret. This solves "how do I safely check a secret into git for GitOps" specifically; it does not solve dynamic or rotating credentials, since once decrypted, it's a normal static Kubernetes Secret with the same properties and limitations as any other, and it doesn't provide the fine-grained per-caller access policy a vault does.
Rotating secrets. Static secrets (environment variables, sealed secrets, KMS-encrypted blobs) need an explicit rotation process: generate a new value, update every place it's stored or injected, confirm all consumers picked it up, retire the old value, the same graceful-rollover discipline used when rotating signing keys, never delete the old value until every consumer has definitely moved to the new one. Dynamic secrets from a vault sidestep most of this, because each secret is minted fresh per lease, "rotation" becomes closer to "just don't renew the lease," with no fleet-wide coordinated update required.
Auditing access. A vault or KMS gives a built-in audit log of every access, who or what requested which secret, when. Environment-variable and sealed-secrets approaches don't have this by default, since once the value is injected, there's no ongoing mediation to log against. If audit trails matter, and for regulated data they usually do, that alone can be the deciding factor toward a vault-based design.
Ephemeral build agents and containers. A CI/CD build agent that spins up for one job and disappears should fetch secrets just-in-time: authenticate to the vault using a credential scoped to that one pipeline run, for example a short-lived OIDC (OpenID Connect) token the CI/CD platform itself issues, fetch exactly what that job needs, use it, and let it expire with the agent, rather than baking secrets into a long-lived build image or a persistent agent's disk, where they'd outlive any single job and accumulate as stale, hard-to-audit standing risk.
The explicit server, SPA, and mobile comparison.
- Server-side application: can safely hold a real secret, a vault-issued dynamic credential, or an injected environment variable populated just-in-time, because the code and its runtime environment are never sent to the end user; the secret never leaves infrastructure you control.
- Single-page application (SPA, a JavaScript application running in the user's browser): anything shipped to the browser, including anything embedded in the JavaScript bundle even if "hidden" via minification or a build-time substitution, is fully readable by the end user, through browser developer tools, the network tab, or the bundle itself. An SPA can hold, at most, a public identifier meant to be seen, like a public API key scoped specifically for client use with its own narrow, rate-limited permissions, never a real secret. Any privileged operation an SPA needs must be proxied through a server-side component that holds the actual secret.
- Mobile application: similarly, anything embedded in a compiled mobile app binary can be extracted by a sufficiently motivated attacker, through decompilation or runtime instrumentation. A mobile app is closer to "distributed to an untrusted environment" than "server-side," even without a literal browser developer-tools panel. The same rule applies: no real secret ships inside the app binary, and privileged operations go through a backend.
- The overriding rule across all three: never ship anything meant to stay confidential to a client, browser or mobile, because "client-side" is definitionally an environment the operator does not fully control, and the end user, or anyone examining their device or traffic, can eventually read it.
Worked example
A data-engineering ETL (extract, transform, load) job runs nightly and needs a database credential to connect to a source Postgres database; it previously used a static password stored in a config file. Migrating to Vault: the job authenticates to Vault at startup using a scoped auth method, for example an AppRole tied specifically to this job's CI/CD pipeline identity, or a Kubernetes ServiceAccount if it runs as a scheduled job in-cluster. Vault's database secrets engine, pre-configured with admin credentials to the Postgres instance, mints a brand-new, unique database username and password pair scoped to a lease of, say, 1 hour, comfortably longer than the job's expected runtime. The job connects using that freshly-minted credential, runs its extract, transform, and load work, and finishes. The credential's lease expires, or the job explicitly revokes it on completion, and Vault automatically drops that database user, so there's no standing credential to rotate on a schedule at all, because a fresh one is minted per run and none of them outlive a single job.
Trade-offs and pitfalls
Treating environment variables as the secret's home rather than a delivery mechanism is the most common way secrets end up leaking, through crash dumps, debug endpoints, child-process inheritance, or simply landing in CI logs when a step accidentally echoes the environment.
Choosing sealed secrets and believing you've solved rotation is a common misunderstanding: you've solved "safe to store the encrypted value in git," not "how does this secret get updated across every consumer."
Baking secrets into a long-lived build image "for convenience" in a supposedly ephemeral CI/CD pipeline defeats the point of ephemeral agents, since the image itself now carries the secret indefinitely, in every registry and every layer cache, even after the agent that used it is gone.
The client-side violation, shipping what was meant to be a server-side secret into an SPA bundle or mobile binary "temporarily, just to get something working," is one of the most common real-world secret leaks precisely because it's trivially discoverable, not a sophisticated attack, and "temporarily" rarely gets cleaned up before it's found.
Design single sign-on (SSO) and single logout (SLO) across multiple web applications and multiple identity providers (SAML and OIDC). Explain front-channel vs back-channel logout mechanisms, how you'd correlate sessions across apps, and how to handle IdP unavailability or failure modes without leaving orphaned sessions.
Sample Answer
Direct answer
Correlate every application's local session to the identity assertion that created it via a single shared identifier, a Security Assertion Markup Language (SAML) NameID plus SessionIndex, or an OpenID Connect (OIDC) sid (session ID) claim, so a single logout event issued by either protocol's identity provider (IdP) can be mapped back to every application session it created, regardless of which protocol established it. Logout must propagate through BOTH front-channel (browser-mediated redirects or iframes, reaching sessions the user's current browser can still touch) and back-channel (server-to-server calls, reaching sessions a redirect chain won't, background jobs, other devices, closed tabs) mechanisms, and every session must carry an absolute maximum time-to-live (TTL) as a backstop, so an IdP outage during logout can orphan a session for, at most, a bounded window, never indefinitely.
Structured elaboration
Session correlation across apps
- The correlating identifier is protocol-specific: SAML federates identity via a NameID plus a SessionIndex, a per-IdP-session identifier included in the original assertion; OIDC federates it via the ID token's
sidclaim. Each application, on establishing its local session from either assertion type, must persist that correlating identifier alongside its own local session record. - A central session registry, keyed by the correlating identifier rather than any one app's own session id, maps "this IdP session" to "every local app session it created", exactly what a logout event needs to fan out to: the IdP issues one logout event naming one correlating identifier, and the registry resolves it to N app sessions to terminate.
Front-channel vs back-channel logout
- Front-channel logout: the IdP, or a gateway, redirects, or loads via a hidden iframe, the user's current browser through each app's own logout endpoint in sequence, SAML's
LogoutRequest/LogoutResponsevia the HTTP-Redirect or HTTP-POST binding, or OIDC's front-channel logout via each relying party's registered logout URI loaded in an iframe. This reaches any app whose session lives in the SAME browser session actively completing the logout. - Back-channel logout: the IdP calls each app's logout endpoint directly, server-to-server, independent of the user's browser, SAML's back-channel
LogoutRequestvia the SOAP binding, or OIDC's back-channel logout via a signed logout token posted to each relying party's back-channel logout endpoint. This is the ONLY mechanism that reaches sessions the browser-redirect chain cannot: a session on a different device, a session in a background tab the user never revisits, or a mobile app's session with no browser redirect surface at all. - A front-channel-only implementation is a common, incomplete-by-construction shipped bug: it looks correct in the common case, one browser, one active tab, and silently leaves every OTHER session, another device, a background tab, an app the browser navigated away from mid-chain, live and orphaned.
sequenceDiagram
participant U as User
participant App1 as App A
participant App2 as App B
participant IdP as Identity Provider
U->>App1: Click logout
App1->>IdP: Front-channel logout request
IdP->>App2: Back-channel logout token (server to server)
App2-->>IdP: Session invalidated ack
IdP-->>App1: Front-channel logout response
App1-->>U: Redirect to logged-out page
Handling IdP unavailability without orphaned sessions
- A back-channel logout call to an app that's temporarily unreachable must be retried, not fired-and-forgotten; queue it with backoff and track delivery per correlating-identifier-and-app pair, so a transient failure doesn't silently leave that one app's session alive indefinitely.
- Every session, independent of whether logout propagation ever successfully reaches it, must carry its own absolute maximum lifetime, a hard session TTL requiring re-authentication once elapsed regardless of activity. This is the backstop bounding the worst case: even a completely failed logout fan-out, every back-channel call permanently failing, leaves an orphaned session alive for at most that TTL, never forever.
- Run a periodic reconciliation job comparing the session registry's "logout events issued" log against "sessions actually confirmed terminated", and re-attempt delivery for any gap, so a retry queue that silently exhausted its attempts doesn't go unnoticed indefinitely.
- If the IdP ITSELF is unavailable, not just one app's back-channel endpoint, new logins for the affected identity fail clearly, but this does not, by itself, terminate EXISTING sessions; existing sessions rely on the TTL backstop above, not an emergency broad logout the down IdP couldn't issue anyway.
Worked example
A concrete failure trace: App B's back-channel logout endpoint is unreachable at the moment logout fires.
- The user logs out via App A. The IdP's front-channel redirect updates App A's own session immediately.
- The IdP's back-channel call to App B times out.
- A retry queue schedules redelivery with exponential backoff, attempts at 1, 2, and 4 seconds after the first failure.
- Cumulative retry window:
1 + 2 + 4 = 7 seconds. If all three attempts fail, the periodic reconciliation job, running on its own separate schedule, detects the "issued but not confirmed" gap and re-queues delivery. - Worst case, if reconciliation also cannot reach App B (a prolonged outage), App B's session survives only until its own absolute session TTL, for example 8 hours, elapses. That TTL, not the retry logic, is the actual upper bound on how long the orphaned session can live, and it holds regardless of how badly the redelivery path fails.
Trade-offs and pitfalls
- Correlating on a SAML SessionIndex or OIDC
sidonly works if every app actually persists it at session-creation time; a legacy app that stores only its OWN session id and discards the IdP's correlating identifier cannot be reached by any logout fan-out at all, no protocol-level fix helps if the correlating id was thrown away at login. - Back-channel logout requires each app to expose a network endpoint reachable by the IdP, not hidden behind the user's own browser session, a real infrastructure requirement, firewall rules, service discovery, that front-channel-only deployments never had to solve. Teams sometimes skip back-channel specifically because standing this up is real work, which is exactly how the front-channel-only gap above ships.
- A hard absolute session TTL as the ultimate backstop is a genuine trade-off against convenience, even a perfectly legitimate, continuously active session eventually forces re-authentication. The alternative, no absolute TTL at all, means a failed logout fan-out has no bound whatsoever, an orphaned session that lives forever, strictly worse for a control whose entire purpose is bounding exposure.
- Mixing SAML and OIDC IdPs on the same platform means the correlation layer has to normalize two structurally different logout wire formats, XML-based SAML requests and responses versus JSON/JWT-based OIDC logout tokens, into one internal event shape. Under-testing this normalization layer itself, rather than each protocol's logout independently, is where cross-protocol SSO/SLO bugs actually tend to live.
Design a secure break-glass process for emergency privileged access that minimizes risk of abuse. Include required approvals, ephemeral credential issuance, session brokering/recording, forced post-usage attestation, cryptographic one-time tokens, and integration with SSO and PAM while maintaining forensic-grade audit trails.
Sample Answer
Direct answer
Break-glass design has to resolve one paradox: the access must be fast enough to be actually usable during a real emergency, yet harder to abuse than the normal privileged-access path it bypasses. The way to resolve it is to stop trying to control abuse at the moment of the request (which is inherently time-pressured and cannot bear much friction) and instead concentrate every control on what happens when the access is used: required approval that runs in parallel with issuance rather than blocking it, a single-use ephemeral credential, a fully brokered and recorded session, and a mandatory after-the-fact accounting that the requester cannot skip.
Structured elaboration
Trigger and required approvals. A requester invokes emergency access through the normal single sign-on (SSO, one login trusted across many applications) portal, authenticated with multi-factor authentication (MFA, proving identity with more than one independent factor, such as a password plus a hardware token). Two approval shapes are common and can be combined: a fast-track that grants access immediately for genuinely time-critical cases but requires a secondary on-call approver to be notified in parallel (their approval is recorded even though it did not gate the grant), and a gated path for less time-critical emergencies that waits for that approval within a short SLA (for example 5 minutes) before falling back automatically to a named secondary approver group so the request is never blocked by one unavailable person.
Ephemeral credential issuance. The credential minted for the session is scoped to exactly the target system and action needed, valid for a short fixed window (commonly 15-60 minutes), and never handed to the user directly: it is held by the session broker (below) and used on the requester's behalf. This bounds the blast radius of a stolen or leaked credential to a window that has almost certainly already closed by the time anyone could misuse it.
Cryptographic one-time tokens. The approval step produces a signed, single-use token, conceptually a JSON Web Token (JWT)-style structure: a payload naming the requester, the target, the approval chain, and an expiry, plus a cryptographic signature over that payload. Because it is single-use and bound to the specific session (via a nonce, a random value used exactly once to prevent replay) and ideally to the requesting device's own attested identity, a captured token cannot be replayed to open a second, unauthorized session.
Session brokering and recording. All privileged access flows through a broker (a jump host or proxy) rather than directly to the target system. The broker holds the actual ephemeral credential, enforces command filtering (blocking or flagging destructive commands outside the stated emergency scope), and records the session (keystrokes and, where feasible, screen video). This is what converts "trust the engineer" into "verify what the engineer did," and it is what makes the subsequent audit trail forensic-grade rather than a self-reported summary.
Forced post-usage attestation. When the session ends, the requester must submit a short structured attestation (what was done, why, and the outcome) within a fixed SLA (for example, 4 hours). Missing that deadline is not a soft reminder: it should automatically disable the account and open a security incident, because an emergency real enough to justify bypassing normal access controls is also real enough to justify a mandatory accounting of what happened.
Integration with SSO and PAM. SSO supplies the identity and MFA at the front door; privileged access management (PAM, the system that vaults, brokers, and rotates privileged credentials) supplies the actual credential vaulting, session brokering, and rotation. Break-glass is best understood as a specific, heavily-instrumented mode of the same PAM infrastructure used for routine privileged access, not a separate system with its own credential store to keep in sync.
Forensic-grade audit trails. Every event (request, approval decision, token issuance, session start and every recorded action, attestation submission or its absence) is written to an append-only store, ideally with per-event cryptographic signing or a periodically-published hash chain, so a tampering attempt after the fact is detectable rather than merely against policy. This is shipped to the security information and event management (SIEM) platform so it feeds both real-time alerting and later incident review from the same source of truth.
Worked example
sequenceDiagram
participant U as On-call Engineer
participant S as SSO with MFA
participant G as Gating Policy Engine
participant AP as Approver
participant PAM as PAM Credential Vault
participant B as Session Broker
participant L as Immutable Audit Log
U->>S: Authenticate with MFA
U->>G: Request emergency access plus reason
G->>AP: Notify for approval, SLA timer running
AP-->>G: Approve
G->>PAM: Mint one-time cryptographic token
PAM-->>U: Ephemeral credential, held by broker only
U->>B: Connect via broker using token
B->>L: Stream session recording and command log
Note over U,B: Session ends
U->>B: Submit post-usage attestation
B->>L: Attestation recorded, or auto-disable if missed
Concretely: at 02:14 an on-call site reliability engineer (SRE) invokes break-glass on an internal administrative portal during a production outage, authenticating with MFA. The gating engine notifies the secondary on-call as required approver; the fast-track path grants the SRE a session immediately (the outage is actively causing customer impact) while the approval request runs in parallel with a 5-minute SLA. At 02:16 the secondary on-call approves from their phone; this approval is logged even though it did not block the grant. The PAM vault mints a token scoped to the one affected production host, valid until 02:44 (30 minutes). All commands the SRE runs are proxied and recorded by the broker. At 02:41 the outage is resolved and the session is closed. By 06:41 (a 4-hour attestation SLA), the SRE must have submitted what was done and why; if that has not happened, the account is automatically disabled and a security incident is opened, independent of whether the emergency access itself was legitimate.
Trade-offs and pitfalls
The core trade-off is exactly the paradox in the direct answer: a fully gated approval (wait for a human before any access) is more resistant to abuse but can fail the emergency it exists to serve if the approver is asleep or unreachable, while a fully ungranted "trust and record" fast-track is more available but leans entirely on after-the-fact detection. Most mature designs use the fast-track for genuinely time-critical categories and the gated path with an automatic fallback approver group for everything else, rather than picking one mode for all emergencies.
A common pitfall is treating the frequency of break-glass invocations as noise instead of a signal: if a team invokes it every week, that is not an emergency-access system working correctly, it is a sign that the normal just-in-time elevation process is too slow or too narrow, and every invocation should be reviewed with that question in mind, not just for individual abuse.
A second pitfall is a soft attestation SLA: "please fill this out when you get a chance" reliably decays to never, at which point the forensic trail has a hole exactly where it matters most. The auto-disable consequence has to be real and automatic, not a manager follow-up email, or the control exists on paper only.
A third pitfall is issuing the ephemeral credential directly to the user instead of keeping it broker-held: a credential the user can see and copy can be exfiltrated even if it is short-lived and single-use, defeating the point of not persisting long-lived secrets. The broker-held pattern (the user authenticates to the broker, the broker authenticates to the target) is what actually prevents this, and it is worth calling out explicitly because it is easy to design a "correct-looking" flow that quietly hands the secret to the wrong party.
Design a hybrid approach that allows near-instant revocation of stateless JWTs (issued with 2-hour TTL) for a global user base. Discuss options like token introspection, short TTLs, revocation blacklists, distributed caches, pub/sub invalidation, and the cost/performance trade-offs for each. Recommend a concrete architecture and justify it.
Sample Answer
Direct answer
No single option (token introspection, short TTLs (time-to-live, how long a token stays valid), a revocation blacklist, or a distributed cache) makes a stateless JWT (JSON Web Token) revocable instantly and cheaply on its own; each trades away either the "no network call" property that made JWTs attractive in the first place, or the promptness of the revocation. The workable answer is a hybrid: keep verifying the JWT's signature locally for speed, add a fast, small, false-positive-tolerant local pre-check (a Bloom filter of recently revoked token IDs) that almost always says "definitely not revoked" for free, and fall back to an authoritative store only for the rare token the pre-check flags as possibly revoked, with revocation events fanned out to every service instantly over pub/sub.
Structured elaboration
| Option | How it works | Cost / performance trade-off |
|---|---|---|
| Token introspection | Every request calls the authorization server (or a shared store) to check validity | Fully authoritative and instantly consistent, but adds a network round trip to every single request, which does not scale to a fleet of independently-scaling microservices verifying millions of requests per second |
| Short TTLs alone | Shrink the token lifetime so a revoked-but-not-yet-caught token expires quickly on its own | Bounds the damage window without any extra infrastructure, but does not give "near-instant" revocation; a 2-hour TTL (as given) still leaves up to 2 hours of usable access after revocation with no other mechanism |
| Revocation blacklist (a plain list of revoked token IDs, checked exactly) | Every service checks the presented token's ID against a shared list of revoked IDs | Exactly correct (no false positives), but the list itself is a single shared store every verification now depends on, and it grows without bound unless pruned by token expiry |
| Distributed cache | Replicate the revoked-ID set (or the blacklist) into a fast in-memory cache near each service | Removes most of the network latency of a remote lookup, but still costs memory proportional to the number of outstanding revocations, and a cache miss still needs to fall back to something authoritative |
| Pub/sub invalidation | Broadcast each revocation event to every interested service the instant it happens | Near-instant propagation with a single event per revocation (not a poll), but delivery is not guaranteed against a dropped connection or a service that was briefly down, so it needs a fallback path for what it misses |
The recommended hybrid architecture:
flowchart LR
Client[Client request + JWT] --> Svc[Microservice: verify JWT signature + local Bloom filter check]
Svc -- jti possibly revoked --> Store[(Redis: authoritative revoked-jti set)]
Store -- confirmed revoked --> Svc
Svc -- jti not in filter --> Allow[Request proceeds]
Publisher[Logout / admin revoke event] --> Store
Store --> Bus[[Pub/Sub: revoked jti]]
Bus --> Svc
Rebuild[Periodic filter-rebuild job] --> Store
Rebuild --> Broadcast[[Broadcast refreshed Bloom filter]]
Broadcast --> Svc
Each service verifies the JWT's signature locally (no network call, the fast path that handles the overwhelming majority of requests), then checks the token's jti (JWT ID, a unique identifier claim) against a small in-memory Bloom filter of recently revoked IDs. A Bloom filter can have false positives (occasionally flagging a valid token as "maybe revoked") but never false negatives (a truly revoked token is always flagged), which is exactly the asymmetry this problem needs: the rare false positive costs one extra authoritative lookup against Redis, while a false negative would mean a revoked token silently still working, which is not acceptable. Revocation events (logout, admin action, a compromised-token report) write to the authoritative Redis store and are pushed over pub/sub to every service instantly, so the filter reflects new revocations within the pub/sub propagation delay; a periodic rebuild job re-derives the Bloom filter from the authoritative store as a fallback for any service that missed a pub/sub message (a dropped connection during a brief outage), bounding the worst case to the rebuild interval rather than leaving a permanent gap.
The authorization-decision-caching variant. The same propagation mechanism (write to an authoritative store, then push an invalidation event over pub/sub, with a periodic rebuild as the fallback for anything the fan-out missed) generalizes beyond pure token validity: a service that caches full authorization decisions ("can user X do Y on resource Z") rather than just "is this token still valid" needs the identical pattern to keep those cached decisions from going stale after a permission changes, just with the cache holding decision results instead of a revoked-ID Bloom filter. The freshness guarantee is the same shape either way: instant in the common case via the event, bounded by the rebuild/refresh interval in the worst case.
Worked example
Scenario (explicitly pinned, not measured production data): a global user base of 300 million registered accounts, with 20 million peak concurrent sessions. Assume 0.5% of active sessions generate a revocation event per hour (logout, password change, admin action); with the given 2-hour access-token TTL, the system must keep at most 2 hours' worth of revocations "hot" in the pre-check at any time.
import hashlib
import math
import random
random.seed(42)
DAU_active_sessions = 20_000_000
revocation_rate_per_hour_fraction = 0.005
token_ttl_hours = 2
revocations_per_hour = DAU_active_sessions * revocation_rate_per_hour_fraction
N = int(revocations_per_hour * token_ttl_hours) # steady-state outstanding revoked-jti set
P_TARGET = 0.001 # target false-positive rate
M = math.ceil(-(N * math.log(P_TARGET)) / (math.log(2) ** 2)) # bit array size
K = round((M / N) * math.log(2)) # hash function count
class BloomFilter:
def __init__(self, m_bits, k_hashes):
self.m, self.k = m_bits, k_hashes
self.bits = bytearray((m_bits + 7) // 8)
def _positions(self, item):
h1 = int.from_bytes(hashlib.sha256(item.encode()).digest()[:8], "big")
h2 = int.from_bytes(hashlib.sha256((item + "salt").encode()).digest()[:8], "big")
for i in range(self.k):
yield (h1 + i * h2) % self.m
def add(self, item):
for pos in self._positions(item):
self.bits[pos // 8] |= (1 << (pos % 8))
def __contains__(self, item):
return all(self.bits[pos // 8] & (1 << (pos % 8)) for pos in self._positions(item))
bf = BloomFilter(M, K)
revoked_ids = [f"revoked-jti-{i}" for i in range(N)]
for rid in revoked_ids:
bf.add(rid)
all_found = all(rid in bf for rid in revoked_ids) # must be True: zero false negatives
valid_ids = [f"valid-jti-{i}" for i in range(1_000_000)]
false_positives = sum(1 for vid in valid_ids if vid in bf)
empirical_fp_rate = false_positives / len(valid_ids)
print(f"m={M:,} bits, k={K}, n={N:,}, target p={P_TARGET}")
print(f"all {N:,} revoked ids still detected (zero false negatives): {all_found}")
print(f"empirical false-positive rate over {len(valid_ids):,} valid ids: {empirical_fp_rate:.5f}")
print(f"filter size: {M/8/1024/1024:.2f} MB")
Output (actually run, unmodified):
m=2,875,518 bits, k=10, n=200,000, target p=0.001
all 200,000 revoked ids still detected (zero false negatives): True
empirical false-positive rate over 1,000,000 valid ids: 0.00102
filter size: 0.34 MB
At this scale, holding 200,000 outstanding revoked token IDs costs roughly 0.34 MB of memory per service instance, small enough to replicate to every instance in the fleet, and the empirically measured false-positive rate (0.00102) lands right at the targeted 0.001, meaning only about 1 in 1,000 valid-token checks ever pays the extra Redis round trip, while every actually-revoked token is caught with certainty.
Trade-offs and pitfalls
The hybrid design's core trade-off is tunable: a smaller false-positive target (P_TARGET) needs more bits per entry, trading memory for fewer unnecessary Redis round trips, and this is a knob to revisit as traffic and revocation-rate assumptions change, not a constant to set once. A common pitfall is forgetting the periodic-rebuild fallback and treating pub/sub as sufficient by itself; any message bus can drop a message during a network partition or a brief consumer outage, and without a rebuild path that gap becomes a silent, permanent hole rather than a bounded one. Another is sizing the filter for the wrong window: it only needs to hold revocations for the outstanding token lifetime (here, 2 hours), not for the system's entire history, since a token from before that window has already expired on its own and revoking it again is meaningless.
Outline a secure and automated employee onboarding workflow from HR source-of-truth to application provisioning: include identity creation, role assignment, SCIM provisioning, MFA enrollment, access approvals, initial access review, and audit trail generation. Mention common automation tools and how to handle exceptions.
Sample Answer
Direct answer
Build onboarding as a single event-driven workflow triggered when the HR system of record marks a new hire active, where each downstream stage, identity creation, role assignment, SCIM (System for Cross-domain Identity Management) provisioning, MFA (multi-factor authentication) enrollment, access approvals, an initial access review, and audit trail generation, is its own idempotent, individually-retriable step rather than one monolithic script, so a failure partway through never corrupts or requires redoing the steps that already succeeded.
Structured elaboration
Identity creation. The HR system is the source of truth, and the trigger should be the new hire's actual start date being reached, not just the record being entered, since entering a future hire's record weeks early should not create a live, usable account before they've started. The canonical directory identity is keyed to a stable, immutable identifier from HR, typically an employee ID, never a name or email, since both can change or be reused.
Role assignment. Derive initial group membership and role from HR attributes (department, job code, manager, location) via a mapping table maintained by IT and security, not case-by-case manual decisions; this table is what lets onboarding scale past a handful of hires a week, and it needs periodic review since job codes and org structure drift over time.
SCIM provisioning. Push the identity and its initial roles to downstream applications via SCIM (RFC 7644) from the identity provider, so each application doesn't need its own bespoke onboarding integration. Every provisioning event should be idempotent on the application's external identifier, retried on transient failure, and reconciled periodically against the source directory to catch an application whose SCIM connector silently stopped working.
MFA enrollment. Enforce enrollment of at least one multi-factor authentication method before first productive login where possible, as part of a guided first-login flow, with a defined, bounded grace window rather than either blocking day-one productivity outright or allowing indefinite unenrolled access. The recovery path for "lost the only enrolled device" needs to require a second, independent verification channel; a help-desk phone reset that bypasses MFA entirely is a well-known initial-access vector and should never be the sole recovery mechanism.
Access approvals. Baseline, low-risk access (email, core collaboration tools) can be auto-granted without a human approval gate, since it's needed day one and carries little risk. Anything beyond that baseline should require an explicit approver, normally the hiring manager or the specific resource owner, recorded before the grant happens, not after; onboarding time pressure is exactly the condition under which this gate gets skipped if it isn't built as a hard requirement rather than a suggestion.
Initial access review. Run a first, new-hire-specific access review roughly 30 to 60 days after start, rather than waiting for the organization's standard annual recertification cycle. Onboarding automation is precisely where over-provisioning creeps in, whether from a mapping table that's slightly too broad or a one-off manual grant made during a rushed first day that never gets revisited, and catching it at 30 to 60 days is far cheaper than catching it a year later.
Audit trail generation. Every one of the stages above (identity creation, role assignment, each provisioning event, MFA enrollment, each approval decision, the review outcome) should write an immutable, timestamped record with actor and justification, stored separately from the operational identity store so a compromised administrator account cannot quietly erase its own trail. This is the artifact that answers "why did this person have this access" during an incident investigation or a compliance audit months later.
Common automation tools. Identity governance and lifecycle platforms orchestrate the HR-to-identity-provider-to-application pipeline end to end; SCIM is the provisioning wire protocol most modern applications speak natively; workflow or ticketing tools handle the human approval steps with their own audit trail; infrastructure-as-code and configuration-management tooling covers any system old enough or niche enough to lack native SCIM support but that still needs its account creation automated rather than done by hand.
Handling exceptions. Contractors and other hires who never appear in the HR system need a separate, narrower onboarding path with an expiry date built in from day one, since there is no HR termination event to trigger their offboarding automatically. Rehires need logic that reuses or correctly re-provisions an existing identity rather than either creating a duplicate account or silently reinstating stale old access. When the standard role-mapping table doesn't match a new hire's actual job (mapping lag is inevitable as org structure evolves), the fix should be a logged, time-bounded exception requested through the same pipeline, not a manager or admin quietly hand-editing group membership outside it, which is exactly how the pipeline's own audit trail develops a gap.
Worked example
Priya joins as a Financial Analyst on a Monday. Her HR record activates Sunday night when her start date is reached, triggering identity creation keyed to her employee ID. The role-mapping table, keyed on job code "FIN-ANALYST," assigns her to the Finance-Analyst group, granting the finance department's core SaaS tools plus baseline email and collaboration access with no approval gate needed for the baseline piece. SCIM provisioning pushes her identity and role to four downstream applications overnight. Monday morning, her first login walks her through guided MFA enrollment before she reaches any application. Because her manager already recorded approval for the finance-tool access during the hiring requisition itself, there is no day-one blocking approval step still pending. At day 45, the new-hire access review flags one unrelated legacy reporting tool grant on her account; investigation shows the role-mapping table's "FIN-ANALYST" entry had accumulated that grant as a stale leftover from a role reorganization two years earlier, and it's removed.
Trade-offs and pitfalls
The most damaging pitfall is triggering account creation the moment an HR record is entered rather than at the actual start date, which produces live credentials for someone who may start months later or never start at all. A close second is applying the same approval gate to baseline and privileged access alike: either day-one productivity is needlessly blocked, or, worse, privileged access gets rubber-stamped through the same fast path meant for email accounts. Skipping the reconciliation job is a quiet, compounding risk: a SCIM connector that silently breaks for one application can leave months of manual workaround access nobody is tracking. The core trade-off in the design is between a centralized, HR-attribute-driven mapping table, which is easy to audit but can lag real organizational change, and allowing manager overrides, which stay more current with reality but are harder to audit consistently unless every override is itself logged with the same rigor as the automated path.
Unlock Full Question Bank
Get access to all Identity, Authentication, and Access Management interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.