Every running service needs secrets it is not allowed to have in plaintext: the database password it connects with, the API key for the payment gateway, the TLS private key it serves traffic with. For years the industry put these in environment variables, in a config.yml checked into git, in a Kubernetes Secret that is just base64 (not encryption, encoding). All of these share one fatal property: the secret is static, long-lived, and copied into a dozen places, so when it leaks you often do not even know, and rotating it means a coordinated redeploy of everything that touched it. A secret management service exists to invert that: secrets live in one encrypted store, services fetch them at runtime over an authenticated channel, each fetch comes with a lease (a time-bounded right to use the secret), and the service renews the lease before it expires or the credential dies. Rotation stops being a fire drill and becomes the steady state.

The interviewer will let you describe a nice encrypted key-value store and then ask the question that reorganizes the whole design: where does the key that decrypts the vault live? If it is on the same disk as the ciphertext, a single disk theft is game over - the attacker has both the lock and the key. The correct answer is envelope encryption: the data is encrypted with a key that is itself encrypted with a master key that never resides on the same disk as the ciphertext, ideally never in plaintext on any disk at all. And you have to do this while keeping decryption under a millisecond, because high-throughput services fetch secrets on hot paths and cannot eat a network round-trip to an HSM per read. That tension - master key maximally isolated, decryption maximally fast - is the spine of this design. Let me build it the way I would in an interview: requirements, sizing, architecture, then take the hard parts naive-first and evolve them.

Functional Requirements (FR)

In scope:

  • Encrypted secret storage. Store arbitrary secrets - database passwords, API keys, TLS certificates and private keys - encrypted at rest. The storage backend must never hold plaintext, and must be useless to an attacker who steals only the disk.
  • Authenticated access. A client (a service, a pod, a CI job, a human) authenticates, and gets back only the secrets its policy allows. No ambient access; every read is authorized against an identity and a policy.
  • Leases on every secret. A read returns the secret plus a lease: a TTL and a lease ID. The client must renew before expiry to keep using it, or treat the secret as expired. This makes every credential time-bounded by construction.
  • Dynamic secrets. For backends that support it (databases, cloud IAM), the vault generates a fresh, unique credential per client on demand - create a new DB user with a short TTL - instead of handing out one shared static password. When the lease ends, the vault revokes that credential.
  • Rotation. Rotate static secrets (the “root” DB password, signing keys) on a schedule or on demand, and rotate the vault’s own encryption keys, without downtime and without clients holding a now-dead secret.
  • Transit (encryption as a service). Let a service send plaintext and get ciphertext back (and vice versa) so the vault does the crypto and holds the keys; the app never sees the key material at all.
  • Audit. Every access, every lease grant, every revocation is logged immutably. “Who read the payments API key, when” must be answerable.

Explicitly out of scope (state it to own the scope):

  • The cryptographic primitives. I will pick and justify AES-256-GCM, a KDF, an HSM/KMS for the root - I am not inventing a cipher. Rolling your own crypto is how you become a breach post-mortem.
  • Identity provider internals. I will integrate with existing auth (Kubernetes service-account JWTs, cloud IAM, OIDC, mTLS) but I am not designing the IdP itself.
  • The HSM hardware. I assume a hardware security module or cloud KMS exists to guard the ultimate root key. I design how the vault uses it, not its silicon.
  • Full PKI as a product. The vault can act as a CA and issue certs; designing the whole certificate lifecycle UI/UX is its own system. I cover issuance and rotation mechanics.

The single decision that drives everything: the master key and the ciphertext must never share a fate. Envelope encryption, a vault that spends most of its life sealed, and leases that make every secret ephemeral all fall out of that one constraint.

Non-Functional Requirements (NFR)

  • Scale: ~50,000 client services/pods across an org, each fetching a handful of secrets at startup and renewing leases periodically. ~500,000 total stored secret entries (static + certs + config), plus a continuously churning population of dynamic credentials. Read-heavy by far.
  • Latency: a cached secret read (and transit decrypt) must be under 1ms server-side for the hot path - this is the headline target and it dictates that decryption cannot touch the HSM per request. Cold reads (decrypt from storage) p99 under ~10ms. Dynamic secret generation (create a new DB user) is allowed to be slower, tens to low hundreds of ms, because it is rare per client.
  • Availability: 99.99% on the read/renew path. A vault outage must not immediately break running services - a secret with a live lease keeps working until its TTL. But a prolonged outage eventually expires leases, so this is “degrade over the lease window,” not “instant death.”
  • Consistency: strong consistency for the control operations - a policy change, a secret write, a revocation must be linearizable (you cannot have a revoked credential still readable from a stale replica). The backing store must be a consensus store (Raft).
  • Durability: losing the vault’s data or its key material is catastrophic. Target 11 nines on the encrypted storage, and - critically - the key hierarchy must be recoverable only through a deliberate, quorum-gated unseal, never by a single operator or a single stolen disk.
  • Security posture: the threat model assumes the storage backend is fully compromised (disk stolen, DB dumped). Confidentiality must hold against that. A compromised vault process is a harder tier handled by sealing, short leases, and audit. Blast radius of any single leaked credential is bounded by its short TTL.

Back-of-the-Envelope Estimation (BoE)

Real numbers, because they push the design toward an in-memory key cache and a read-through decrypt path.

Clients and secrets:

Client services / pods            ~50,000
Secrets fetched per client start  ~5     (db creds, 2 api keys, tls cert, config)
Stored static secret entries      ~500,000
Avg secret plaintext size         ~1 KB  (a cert/key is larger, ~4 KB; a token tiny)

Request rate (read-dominated):

Startup/rollout reads:
  50,000 pods * 5 secrets, rolling over ~a deploy window.
  A full fleet redeploy in ~10 min:
     50,000 * 5 / 600s  ≈ 420 reads/sec burst from restarts alone.

Lease renewals (steady state, the real baseline load):
  Each live lease renews at ~1/3 of its TTL. With ~250,000 live leases
  (5 per pod * 50,000) and a 1h TTL -> renew every ~20 min:
     250,000 / 1200s  ≈ 210 renewals/sec steady.

transit encrypt/decrypt (if used on hot paths):
  This can dwarf everything. A service decrypting a field per request at
  1,000 req/s * even 100 such services = 100,000 ops/sec.
  -> THIS is why sub-ms, in-memory-key decryption is non-negotiable.

Writes (secret create/update, rotation): rare, maybe ~10/sec. Tiny.

The shape: reads and transit ops dominate by orders of magnitude; writes are a rounding error. So we optimize the read/decrypt path brutally and can afford an expensive, strongly-consistent write path.

Storage:

Static secrets:   500,000 * ~1.5 KB (ciphertext + IV + tag + metadata) ≈ 0.75 GB
Encrypted. Trivially small - fits in RAM, let alone on disk.

Audit log (the real storage driver):
  Every read/renew/revoke logged. ~(420 + 210) ≈ 630 security-events/sec
  steady, bursting higher. ~630 * 86400 ≈ 54M events/day.
  At ~0.5 KB/event ≈ 27 GB/day  -> ~10 TB/year of audit.
  -> audit log is shipped off-box to cheap append-only storage, not kept in the vault.

Key cache (the thing that makes sub-ms work):

The hot item is not the secrets - it is the DECRYPTED data-encryption keys.
Keyring: a handful of active + retired encryption keys, ~32 bytes each.
Per-secret data keys (if per-secret): up to 500,000 * 32 B ≈ 16 MB.
-> The entire working key set fits in process RAM. Decryption is a memory
   lookup + an AES-GCM op (~microseconds on AES-NI), no network, no HSM call.

That last box is the whole trick: once unsealed, the keys the vault needs live in RAM, so decryption is CPU-local and sub-millisecond. The HSM is touched only at unseal and at root-key rotation, not per read.

High-Level Design (HLD)

The system is a cluster of vault nodes fronting a strongly-consistent storage backend, with a key hierarchy that keeps the master key off the ciphertext disk. A node spends its life in one of two states: sealed (holds ciphertext but cannot read it - no decryption key in memory) or unsealed (the master key has been reconstructed in memory and the node can serve). Sealing is the core safety property: a freshly started or compromised-and-restarted node is inert until a quorum unseals it.

The logical components:

  • API / request router. Terminates TLS, routes to auth, policy, and the secret engines. Stateless.
  • Auth methods. Pluggable: Kubernetes SA JWT, cloud IAM, OIDC, AppRole, mTLS. Exchanges an external identity for a short-lived vault token scoped by policy.
  • Policy engine. Maps a token’s identity to a set of path-based capabilities (read/create/update/delete on secret/payments/*). Every request is checked here.
  • Secret engines. The pluggable backends behind paths: a KV engine (static secrets), a database engine (dynamic DB creds), a PKI engine (issue certs), a transit engine (encrypt/decrypt as a service).
  • Key management / barrier. The envelope-encryption core. Holds the keyring in memory when unsealed; every read/write to storage passes through this barrier, which encrypts on the way down and decrypts on the way up.
  • Lease manager (expiration manager). Tracks every lease, its TTL, and its revocation hook; expires and revokes on schedule; handles renewals.
  • Storage backend. A consensus store (integrated Raft, or Consul/etcd). Holds only ciphertext. This is the thing we assume can be stolen.
  • Seal / unseal subsystem. Reconstructs the master key at startup from a quorum of key shares (Shamir) or from an auto-unseal KMS/HSM.
  • Audit backend. Append-only, off-box sink for every operation.
         Clients (pods, CI, humans, machines)
                      │  TLS + vault token
                      ▼
 ┌──────────────── VAULT CLUSTER (active + standby nodes) ────────────────┐
 │                                                                        │
 │  ┌──────────┐   ┌───────────┐   ┌──────────────┐                       │
 │  │   API /  │──►│   Auth    │──►│   Policy     │  authn -> token        │
 │  │  router  │   │  methods  │   │   engine     │  authz -> capabilities │
 │  └────┬─────┘   └───────────┘   └──────┬───────┘                        │
 │       │  authorized request            │                               │
 │       ▼                                ▼                               │
 │  ┌──────────────── SECRET ENGINES ───────────────────────┐             │
 │  │  KV | Database(dynamic) | PKI(certs) | Transit(crypto) │            │
 │  └───────────────────────┬───────────────────────────────┘             │
 │                          │ every storage op                            │
 │                          ▼                                             │
 │             ┌──────────────────────────┐    ┌──────────────────┐       │
 │             │   BARRIER (envelope enc)  │◄──►│  Lease / expire  │       │
 │             │   keyring in RAM (unseal) │    │  manager (TTLs,  │       │
 │             │   encrypt down/decrypt up │    │  revoke hooks)   │       │
 │             └────────────┬─────────────┘    └──────────────────┘       │
 │  ┌────────────────┐      │ ciphertext only                             │
 │  │  Seal/Unseal   │      ▼                                             │
 │  │  (Shamir quorum│   ┌──────────────────────────────┐                 │
 │  │   OR KMS/HSM)  │   │  STORAGE BACKEND (Raft)       │  <-- assume    │
 │  └───────┬────────┘   │  encrypted blobs + metadata   │      STOLEN     │
 │          │ unwrap     └──────────────────────────────┘                 │
 └──────────┼─────────────────────────────────────────────────────────────┘
            ▼                                   │ external dynamic-secret targets
   ┌──────────────┐                             ▼
   │  HSM / Cloud │                   ┌──────────────┐  ┌──────────────┐
   │  KMS (root)  │                   │  Database    │  │  Cloud IAM   │
   └──────────────┘                   │ (create user)│  │ (issue creds)│
                                      └──────────────┘  └──────────────┘
   (audit log streamed off-box to append-only storage, not shown on hot path)

Read flow (the hot path, static secret):

  1. Client calls GET /v1/secret/data/payments/stripe with its vault token.
  2. Router authenticates the token (cached lookup), policy engine checks read on that path. Reject if not allowed.
  3. KV engine fetches the ciphertext blob from storage through the barrier. The barrier decrypts it with the in-memory keyring - a memory lookup plus an AES-GCM decrypt, sub-millisecond, no HSM call.
  4. If the secret is leased (e.g. a dynamic cred), the lease manager issues a lease ID and TTL and records a revocation hook. For static KV, a TTL is attached for cache guidance.
  5. Response returns plaintext secret + lease. Audit log records the access.

Write flow (create/update a secret):

  1. Authorized POST with the secret payload.
  2. Barrier encrypts the payload with the active data key (envelope), wrapping metadata (key version, IV, tag).
  3. The ciphertext is written to the Raft backend and must be committed by a quorum of nodes before the write returns (strong consistency - a committed secret is durable and visible to all).
  4. Audit log records the write (never the plaintext value).

Unseal flow (node startup):

  1. Node starts sealed. Storage holds the encrypted keyring but the node has no key to decrypt it.
  2. Operators (or an auto-unseal KMS) provide enough key shares to reconstruct the master key in memory (details in the deep dive).
  3. The master key decrypts the keyring; the node is now unsealed and can serve. The master key exists only in process memory, never written to the node’s disk.

Component Deep Dive

Four hard parts, each naive-first: (1) envelope encryption and the key hierarchy - the crux; (2) seal/unseal and keeping the master key off the ciphertext disk; (3) leases, dynamic secrets, and rotation; (4) sub-millisecond decryption at scale. I break each before fixing it.

1. Envelope encryption and the key hierarchy

This is the heart of the assignment: encrypt the vault so the master key never sits on the same disk as the ciphertext, while decryption stays fast.

Naive: encrypt every secret directly with one master key, key on disk

Keep one AES-256 master key. Encrypt each secret with it. Store the ciphertext in the backend, store the master key in a file next to it (or in an env var on the same box).

Where it breaks:

  • Key and ciphertext share a fate. Steal the disk (or dump the DB and read the adjacent key file) and you have both halves. The encryption bought nothing against the exact threat we care about - storage compromise. This is the whole thing the assignment forbids.
  • Rotating the master key means re-encrypting everything. If the one key that encrypts all 500,000 secrets must change (suspected leak, compliance), you must decrypt and re-encrypt all 500,000 entries in one risky, non-atomic migration. Rotation becomes so expensive you avoid it, which is the opposite of the goal.
  • One key, infinite exposure. Every secret ever encrypted with that key is compromised the instant it leaks. No blast-radius containment, no per-tenant isolation.

Better: a three-tier envelope hierarchy, master key never on the ciphertext disk

Split one key into a hierarchy where each level encrypts (wraps) the level below, so the thing on disk is always itself encrypted:

   ROOT / MASTER KEY   (the "unseal" key / KMS root)
        │  lives in: HSM/KMS, or reconstructed in RAM via Shamir.
        │  NEVER written in plaintext to the vault's storage disk.
        ▼ encrypts (wraps)
   KEYRING / KEY-ENCRYPTION KEY(s)  (KEK)
        │  the "encryption key" used by the barrier. Stored ON DISK but
        │  only in CIPHERTEXT (wrapped by the master key). Decrypted into
        │  RAM at unseal. This is what makes reads fast.
        ▼ encrypts
   DATA-ENCRYPTION KEYS  (DEK)  -- optionally per-secret or per-engine
        │  the key that actually encrypts a secret's bytes with AES-256-GCM.
        ▼ encrypts
   THE SECRET PLAINTEXT  ->  ciphertext + IV + auth tag  (stored on disk)

The envelope property, stated precisely: what sits on the ciphertext disk is (a) the encrypted secrets, and (b) the encrypted keyring. The key that decrypts the keyring - the master key - is never written to that disk in plaintext. It is either inside an HSM/KMS or reconstructed only in volatile memory at unseal. Steal the disk and you get two layers of ciphertext and no key to open either.

Why the tiers earn their keep:

  • The barrier (the KEK layer) is what every storage read/write passes through. Because the KEK is decrypted into RAM once at unseal, the barrier decrypts secrets with an in-memory key - no HSM round-trip per read. That is the entire reason sub-ms reads are possible (deep dive 4).
  • Master-key rotation is cheap because the master key only wraps the keyring, not the 500,000 secrets. To rotate the master key you re-wrap one small keyring, not the whole corpus. (Rotating a KEK is handled by keyring versioning, below.)
  • Keyring versioning for KEK rotation. The keyring holds multiple key versions: an active one for new writes and retired ones kept only to decrypt old data. Every ciphertext blob is tagged with the key version that encrypted it. Rotating the encryption key means adding a new active version; old data stays readable under its old version and gets lazily (or by a background rewrap job) re-encrypted to the new one. No stop-the-world re-encryption.
ciphertext blob on disk:
  { key_version: 7, iv: <96-bit>, ciphertext: <...>, auth_tag: <128-bit> }
            │
   barrier looks up keyring[7] in RAM  -> AES-256-GCM decrypt -> plaintext
   (auth_tag verified: tamper on disk is DETECTED, not silently served)

rotate encryption key:
  keyring gains version 8 (new active). New writes use 8.
  version-7 blobs still decrypt under keyring[7]. Background rewrap upgrades
  them to 8 over time. Then 7 can be retired. Zero downtime.

AES-256-GCM (authenticated encryption) is the deliberate choice: it gives confidentiality and integrity. The auth tag means a storage backend that silently flips bits in a blob gets caught at decrypt time rather than feeding a corrupted secret to a client. Against the “storage is compromised” threat, integrity matters as much as confidentiality.

2. Seal / unseal: keeping the master key off the disk

The hierarchy is only as good as the master key’s custody. If the master key is just sitting in a file, the hierarchy is theater.

Naive: store the master key in a config file or env var on the node

Put the master key on the node so it can auto-start and serve immediately after a reboot.

Where it breaks:

  • Co-location with ciphertext, again. The node also has (or can reach) the storage. Root the box, read the key file, dump the store - full compromise from one host breach. We have just moved the key from the storage disk to the node’s disk; same fate-sharing problem.
  • No separation of duty. One operator (or one attacker with one credential) can unlock everything. There is no “it takes several people/systems to open the vault.”
  • A stolen backup is a stolen vault. Back up the node and you have backed up the key next to the data.

Better: the vault starts sealed; the master key is reconstructed, never stored in plaintext

The node boots sealed: it has the encrypted keyring but no master key in memory, so it can read nothing. Unsealing reconstructs the master key in RAM only, two supported ways:

  • Shamir Secret Sharing (quorum unseal). The master key is split at initialization into N shares such that any K of them reconstruct it (e.g. 3-of-5), and no single share reveals anything. The shares are distributed to different operators / stored in different custody. To unseal, K operators each submit their share; the node reconstructs the master key in memory, decrypts the keyring, and becomes active. The reconstructed master key is held only in volatile memory - a reboot re-seals the node and requires a fresh quorum. This gives separation of duty (no one person can unseal) and keeps the master key off every disk.
  • Auto-unseal via KMS/HSM. For operability, delegate the outermost wrap to a cloud KMS or HSM. The keyring is wrapped by a key that lives inside the HSM and never leaves it. At startup the node asks the HSM to unwrap the keyring; the HSM performs the decrypt internally and returns the keyring, which lives only in the node’s RAM. The master key’s plaintext never exists outside the HSM silicon. This trades “humans hold shares” for “a hardware boundary holds the key,” and removes the operational pain of manual quorum unseal on every restart. Most production deployments use auto-unseal with KMS and keep Shamir shares as the recovery/break-glass path.
SEALED node:
  storage: [encrypted keyring][encrypted secrets]   <- all ciphertext
  memory:  (no master key)  -> cannot decrypt anything -> refuses to serve

UNSEAL (Shamir 3-of-5):
  op1 share ┐
  op2 share ├─ reconstruct master key IN RAM ─► decrypt keyring ─► UNSEALED
  op3 share ┘        (never written to disk)

UNSEAL (auto, KMS):
  node ──unwrap(encrypted keyring)──► [ HSM/KMS: decrypt internally ] ──► keyring in RAM
         master-key plaintext stays inside the HSM, ever.

Re-seal on: reboot, crash, or an explicit `seal` command (panic button).
A compromised node that is restarted comes up SEALED = inert.

The sealing property is the second half of the assignment’s constraint. Envelope encryption keeps the key off the storage disk; sealing keeps the reconstructed key out of any persistent store on the node, living only in RAM between unseal and reboot. Together: the plaintext master key exists only transiently in memory on a running, deliberately-unsealed node, and nowhere on any disk.

3. Leases, dynamic secrets, and rotation

Static encrypted storage is table stakes. The thing that makes this a rotation service is that secrets are time-bounded and the system actively expires and regenerates them.

Naive: hand out one shared static credential, forever

Store one DB password. Every service that needs the database reads that same password and uses it indefinitely. Rotate by hand when someone remembers.

Where it breaks:

  • Shared credentials cannot be attributed. Fifty services use the same DB user; when a query misbehaves or a credential leaks, you cannot tell which service. No per-consumer attribution, no per-consumer revocation.
  • Rotation is a coordinated outage. Change the one password and every one of the fifty services is instantly broken until each redeploys with the new value. So nobody rotates, and the credential lives for years - exactly the stale-long-lived-secret problem we set out to kill.
  • A leak has unbounded lifetime. A static password that leaks is valid until a human notices and rotates. That window is often months.

Better: dynamic, per-client credentials with leases, plus active rotation

  • Dynamic secrets. Instead of storing a usable DB password, store the root credential and let the database secret engine generate a fresh credential per request. A service asks for DB access; the engine runs CREATE USER svc_x_7f3a ... VALID UNTIL now()+1h against the database, returns those unique credentials, and records a lease with a revocation hook (DROP USER svc_x_7f3a). Now every consumer has its own short-lived credential: fully attributable, individually revocable, and automatically cleaned up.
  • Leases make every secret ephemeral. Each issued secret (dynamic creds, a PKI cert, even a token) carries a lease: a lease ID and a TTL. The lease/expiration manager tracks all live leases in a time-ordered structure and, on expiry, fires the revocation hook (drop the DB user, revoke the IAM key). A leaked credential dies on its own at TTL; the blast radius of any leak is bounded by the lease window, not by how fast a human reacts.
  • Renewal prompts services to refresh before expiry. A running service does not want its DB credential yanked mid-flight, so the client library renews the lease at ~1/2 to 2/3 of its TTL: a cheap renew(lease_id) call that extends the TTL (up to a max TTL ceiling, after which the credential is force-rotated and the client must obtain a new one). This is the “prompt running services to renew before they expire” behavior from the assignment: the lease is a countdown the client must keep resetting, and the system guarantees the credential is valid only while someone is actively renewing it.
  • Rotation of static roots and keys. Some secrets cannot be dynamic (a third-party API key, the DB root password, a signing key). For these: the vault can rotate the root itself (change the DB root password and keep the new one internal, so not even an operator knows it), rotate on a schedule or on demand, and version the secret so a brief overlap window lets clients that still hold version N finish while new reads get version N+1. Transit signing/encryption keys rotate by the same keyring-versioning mechanism as the barrier (new active version, old versions retained for verify/decrypt).
Dynamic DB credential lifecycle:

  client ──"give me db access"──► database engine
     engine: CREATE USER svc_x_7f3a PASSWORD <rand> VALID UNTIL +1h
     returns { user, password, lease_id: L42, ttl: 3600 }
     lease mgr records L42 -> revoke hook: DROP USER svc_x_7f3a

  t+30m  client renews L42 -> ttl reset to 3600 (bounded by max_ttl, say 24h)
  t+24h  max_ttl hit -> no more renewal -> lease expires ->
         lease mgr runs DROP USER svc_x_7f3a. Client must request a NEW cred.

  leak of svc_x_7f3a's password? valid at most until next expiry. Self-heals.

The lease manager is the engine of the whole rotation story. It must be durable (leases survive a vault restart - they are stored, encrypted, through the barrier) and precise (it cannot “forget” to revoke, or dead credentials pile up in the database). On the active node it keeps an in-memory timer heap of upcoming expirations backed by the persisted lease records, so recovery after a failover re-reads the leases and rebuilds the schedule.

4. Sub-millisecond decryption at scale

The assignment demands decryption under 1ms for high-throughput services (think transit decrypt on a per-request field). The crypto is cheap; the trap is accidentally putting a network hop on the hot path.

Naive: call the HSM/KMS to decrypt on every read

Since the master key lives in the HSM, ask the HSM to decrypt each secret as it is requested.

Where it breaks:

  • A network round-trip per read, ~5-50ms. The HSM is a remote (or at least out-of-process) device with a request queue. One decrypt is milliseconds to tens of ms - 10x to 50x over budget - before you even add contention.
  • The HSM is a throughput bottleneck. HSMs do a few thousand ops/sec at best. Our transit load is up to 100,000 ops/sec. Routing every decrypt through the HSM caps the whole system at the HSM’s rate and makes it a single hot point.
  • It defeats the point of the hierarchy. We built tiers precisely so the HSM is touched rarely; calling it per read throws that away.

Better: HSM only unwraps the keyring at unseal; all reads decrypt with the in-RAM keyring

  • The HSM/master key is on the control path, not the data path. It is used once at unseal to unwrap the keyring (and occasionally for root rotation). After that, the keyring (the working encryption keys) lives in process RAM. Every secret decrypt is: look up the key version in the in-memory keyring, run AES-256-GCM on CPU (AES-NI makes this a few hundred nanoseconds to low microseconds for KB-sized payloads). No network, no HSM, no lock on a remote device. That is how you get comfortably under 1ms - the operation is memory-bound and CPU-local.
  • Serve reads from any unsealed node; scale reads horizontally. Because decryption needs only the in-RAM keyring (replicated to every unsealed node via the Raft log), read/transit traffic can be served by standby/performance-replica nodes, not just the active node. Writes still go to the active (leader) node for strong consistency, but reads - the 99% - fan out across the cluster. This is the horizontal scaling lever for the hot path.
  • Token and policy lookups are cached in memory too. The per-request overhead that is not crypto - validating the token, resolving its policy - is served from an in-memory cache keyed by token, with short TTLs and invalidation on revoke. So the whole hot path (authn + authz + decrypt) stays in RAM.
  • transit keeps app plaintext-key-free at hot-path speed. With the keyring in RAM, the vault can offer encryption-as-a-service: the app sends ciphertext, the vault returns plaintext (or vice versa) in sub-ms, and the app never holds the key. This is the pattern for encrypting a DB column or a field per request without the app ever touching key material.
transit decrypt hot path (per request):
  app ──ciphertext──► vault node (already unsealed)
     authn: token in RAM cache            (~µs)
     authz: policy in RAM cache           (~µs)
     decrypt: keyring[v] in RAM + AES-GCM (~µs, AES-NI)
  ◄── plaintext ──    total: well under 1ms, zero network to HSM

HSM is touched ONLY at:  unseal (unwrap keyring), root-key rotation.  Never per read.

The design rule, stated plainly: the master/HSM key is on the slow control path (unseal, rotation); the working keyring is on the fast data path (RAM, per read). Isolation and speed stop being in tension because they live on different paths - the key stays maximally guarded in the HSM while decryption stays maximally fast in RAM.

API Design & Data Schema

APIs

# ---- Auth: exchange an external identity for a vault token ----
POST /v1/auth/kubernetes/login
  body: { role: "payments-svc", jwt: "<k8s service-account JWT>" }
  resp: { client_token: "hvs.CAES...", lease_duration: 3600,
          renewable: true, policies: ["payments-read"] }
  # vault verifies the JWT against the k8s API, maps role->policies, mints a
  # short-lived token. mTLS / cloud IAM / OIDC / AppRole are parallel methods.

# ---- Read a static secret (KV v2) ----
GET /v1/secret/data/payments/stripe        Header: X-Vault-Token: <token>
  resp: { data: { api_key: "sk_live_..." },
          metadata: { version: 4, created_time: "..." },
          lease_duration: 300, lease_id: "" }        # KV: TTL is cache guidance

# ---- Write / update a static secret ----
POST /v1/secret/data/payments/stripe       Header: X-Vault-Token: <token>
  body: { data: { api_key: "sk_live_..." } }
  resp: { metadata: { version: 5 } }         # versioned; prior versions retained

# ---- Dynamic database credential (generated on demand, leased) ----
GET /v1/database/creds/payments-role        Header: X-Vault-Token: <token>
  resp: { data: { username: "v-k8s-payments-7f3a", password: "A1b2..." },
          lease_id: "database/creds/payments-role/L42",
          lease_duration: 3600, renewable: true }
  # engine ran CREATE USER on the DB; lease mgr holds the DROP USER revoke hook.

# ---- Lease lifecycle ----
PUT  /v1/sys/leases/renew   body: { lease_id: "...L42", increment: 3600 }
     resp: { lease_id, lease_duration: 3600 }      # bounded by max_ttl
PUT  /v1/sys/leases/revoke  body: { lease_id: "...L42" }
     resp: 204                                      # runs revoke hook now

# ---- Transit: encryption as a service (app never holds the key) ----
POST /v1/transit/encrypt/orders  body: { plaintext: <base64> }
     resp: { ciphertext: "vault:v3:AbCd..." }       # v3 = key version used
POST /v1/transit/decrypt/orders  body: { ciphertext: "vault:v3:AbCd..." }
     resp: { plaintext: <base64> }                  # sub-ms, in-RAM keyring
POST /v1/transit/keys/orders/rotate                 # new active key version

# ---- PKI: issue a short-lived TLS cert (leased like any dynamic secret) ----
POST /v1/pki/issue/internal  body: { common_name: "svc.internal", ttl: "72h" }
     resp: { certificate, private_key, ca_chain, serial_number,
             lease_id, lease_duration: 259200 }

# ---- Seal / unseal / rotate (operator control plane) ----
POST /v1/sys/unseal  body: { key: "<shamir share>" }   # repeat until quorum
     resp: { sealed: true|false, t: 3, n: 5, progress: 2 }
POST /v1/sys/seal                                       # panic button -> inert
POST /v1/sys/rotate                                     # add new keyring version

Data / storage schema

The backend stores only ciphertext and metadata. Everything crosses the barrier. Choice of store is deliberate (below). Logical shapes:

# ---- Encrypted secret entry (as written through the barrier) ----
storage_key:   "logical/secret/payments/stripe/v5"      # path + version
value (on disk, CIPHERTEXT):
  { key_version: 7,              # which keyring version encrypted this
    iv:          <96-bit nonce>,
    ciphertext:  <AES-256-GCM of the plaintext secret>,
    auth_tag:    <128-bit GCM tag> }                     # integrity check
# The plaintext { api_key: "..." } exists ONLY after barrier decrypt, in RAM.

# ---- Keyring (itself stored encrypted, wrapped by the master key) ----
storage_key:   "core/keyring"
value (on disk, CIPHERTEXT, unwrapped only in RAM at unseal):
  { active_version: 8,
    versions: { 1..8: <32-byte AES key> },   # retired versions kept to decrypt old data
    rotation_time: "..." }

# ---- Lease record (durable, through the barrier) ----
lease {
  lease_id       string   PK      # "database/creds/payments-role/L42"
  secret_path    string           # what engine/path issued it
  issue_time     ts
  expire_time    ts       INDEX    # time-ordered -> drives the expiration heap
  max_ttl        int
  renewable      bool
  revoke_data    blob             # engine-specific hook payload (e.g. the DB username to DROP)
}
# Index on expire_time so the lease manager can pull "what expires next" cheaply.

# ---- Token / policy (through the barrier) ----
token  { accessor PK, policies[], ttl, max_ttl, parent, entity_id }
policy { name PK, rules: [ { path, capabilities: [read|create|update|delete|list] } ] }

# ---- Audit (append-only, streamed OFF-BOX) ----
audit_event { time, client_id, token_accessor, operation, path,
              result, request_id }    # secret VALUES are HMAC'd, never plaintext

Store choice: a strongly-consistent, replicated backend (integrated Raft, or Consul/etcd) - not a general SQL or eventually-consistent NoSQL store. Reasons:

  • Linearizability is mandatory for the control plane. A revoked lease, a rotated key, a changed policy must be immediately and globally effective. An eventually-consistent store could serve a revoked credential from a stale replica - a security hole. Raft gives a single committed order and a clear leader for writes. This is the one place we pay for strong consistency and it is non-negotiable.
  • The dataset is small and key-value shaped. ~1 GB of encrypted blobs, accessed by exact key/path. No relational joins, no analytical queries. A KV consensus store fits the access pattern exactly; a SQL engine’s query power is wasted and its weaker default consistency is a liability.
  • It is already encrypted. Because the barrier encrypts everything before it hits the store, the store needs no crypto features of its own - it just needs durable, linearizable, replicated KV. Integrated Raft keeps the data inside the vault cluster (no external dependency), which simplifies the trust boundary.
  • Audit does not belong here. Audit is high-volume append-only (10 TB/year) and must survive even a vault compromise, so it streams to a separate off-box append-only sink (object storage, a SIEM). Keeping it out of the consensus store keeps that store small and fast.

Bottlenecks & Scaling

Where it breaks first, in order, and the fix for each.

1. The HSM on the read path (breaks first if you let it). Decrypting via the HSM per read caps throughput at a few thousand ops/sec and adds milliseconds. Fix: HSM only unwraps the keyring at unseal; all reads decrypt with the in-RAM keyring (AES-NI, sub-µs). The master key stays on the control path, never the data path. This is the single most important performance decision in the design.

2. Single active node for writes and the read fan-out ceiling. Raft funnels all writes through one leader; a single node also caps read throughput. Fix: writes to the leader (for linearizability), reads fanned out to standby / performance-replica nodes. Since decrypt needs only the replicated in-RAM keyring, any unsealed node serves reads and transit. Reads (the 99%) scale horizontally; writes stay strongly consistent on the leader. Add performance replicas (even cross-region) for read-locality.

3. Lease manager overload and expiry storms. Millions of live leases, and a fleet-wide rollout can align expiry times so a flood of revocations fires at once (thundering herd against the target databases / IAM). Fix: a persisted, time-indexed expiration heap so “what expires next” is O(log n), plus TTL jitter so expiries spread out instead of synchronizing, plus batched revocation with rate-limiting against downstream targets. Renewal at 1/2-2/3 TTL naturally staggers refreshes.

4. Token/policy validation cost per request. Re-deriving policy from storage on every call would put a storage read on the hot path. Fix: in-memory token and policy caches with short TTLs and immediate invalidation on revoke/rotate. Hot-path authn+authz stays in RAM alongside the decrypt.

5. Hot secret / hot path (a single widely-read secret or transit key). One secret or one transit key read at 100k ops/sec concentrates load. Fix: it is already in the in-RAM keyring on every node, so spread the reads across all replicas (the key is replicated, not centralized). For a hot stored secret, the decrypted plaintext can be briefly cached in RAM behind a short TTL. There is no single node that must serve a given key, because the key material is everywhere unsealed.

6. Storage backend as a single point of failure. The consensus store holds everything; lose it and the vault is gone. Fix: Raft replication across an odd number of nodes (3 or 5) across failure domains, with snapshots and point-in-time backups - of ciphertext, which is safe to store more widely because the master key is not with it. A lost follower is re-synced from the leader; a lost leader triggers a Raft election. The vault survives minority node loss with no data loss.

7. Seal state after a crash (availability vs security tension). A crashed node restarts sealed and cannot serve until unsealed - correct for security, but manual Shamir unseal on every restart is an availability hazard. Fix: auto-unseal via KMS/HSM so a restarted node unwraps its keyring automatically and rejoins, while Shamir shares remain the break-glass recovery path. Run multiple nodes so one sealing/restarting does not take the cluster down - the others keep serving.

8. Running services caught by a vault outage. If the vault is down, services cannot renew leases. Fix: this is bounded by design. A live lease keeps the credential valid until its TTL, so a short outage is invisible to running services - they renew once the vault is back. Only an outage longer than the lease window bites, which is why TTLs are set with recovery time in mind (hours, not seconds, for critical paths) and clients cache the last-good secret until its lease truly expires. Availability degrades over the lease window rather than instantly.

9. Audit log volume and integrity. 10 TB/year, and it must survive even a vault compromise to be trustworthy. Fix: stream audit off-box to append-only, write-once storage (object storage with object-lock, or a SIEM), HMAC sensitive fields so values never appear in plaintext, and make audit-sink failure fail closed for high-security modes (if it cannot log, it does not serve) - a deliberate availability-vs-accountability trade-off the operator chooses per deployment.

Wrap-Up

The trade-offs that define this design:

  • Envelope encryption so the key and the ciphertext never share a fate. A three-tier hierarchy (master key -> keyring -> data keys) means the disk holds only ciphertext and an encrypted keyring; the master key lives in an HSM or is reconstructed in RAM, never written in plaintext to the ciphertext disk. That one property is the whole point of the system, and it also makes key rotation cheap (re-wrap a small keyring, not the whole corpus).
  • Isolation and speed live on different paths. The HSM/master key is on the slow control path - unseal and root rotation only - while the working keyring is on the fast data path, in RAM, so every decrypt is a CPU-local AES-GCM op well under 1ms. The two goals stop competing because they never touch the same request.
  • Sealing makes a compromised or restarted node inert. The master key exists only in volatile memory between a deliberate unseal and the next reboot; a quorum (Shamir) or a hardware boundary (KMS) is required to open the vault, giving separation of duty and bounding what a single host breach yields.
  • Leases make every secret ephemeral, so rotation is the steady state. Dynamic per-client credentials, time-bounded leases that clients must actively renew, and automatic revocation on expiry bound the blast radius of any leak to a short TTL and make a leaked credential self-healing - no human-in-the-loop rotation fire drill.
  • Strong consistency where it is a security property, horizontal scale where it is a throughput problem. Writes and control operations go through a Raft leader (a revoked credential must never be served stale); reads and transit fan out across unsealed replicas because the keyring is replicated to all of them.

One-line summary: a cluster of vault nodes that boot sealed and only serve once a quorum (or an HSM) reconstructs the master key in memory, storing every secret as AES-256-GCM ciphertext under a three-tier envelope hierarchy whose master key never touches the ciphertext disk, decrypting on the hot path with an in-RAM keyring in sub-millisecond time, and issuing short-lived, per-client, leased credentials that running services renew before expiry and that the vault auto-revokes - so secret rotation is continuous and automatic, blast radius is bounded by the lease, and a stolen disk yields nothing but two layers of ciphertext.