SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
  • SSL/TLS
  • Encryption at Rest
  • Secrets Management
  • Password Management
  • RBAC
  • SAML
  • OWASP Top 10 and Common Attacks
  • DDoS Attacks and Defenses
  • Web Application Firewall (WAF)
  • Certificates and PKI
  • Multi-Factor Authentication (MFA)
  • Zero Trust
  • Key Management (KMS)
  • Data Privacy and GDPR Basics
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Operations and Security/Advanced Security

Key Management (KMS)

Create, store, use, rotate and retire encryption keys safely, with a service that never shows the key.

⏱ 13 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A Key Management Service (KMS) creates, stores, uses, rotates and retires encryption keys. Its big promise: the master key never leaves it. You send data (or a small data key) to the KMS, and it sends back the encrypted or decrypted result.

  • Key lifecycle: generate, store, use, rotate, revoke, destroy. Every step needs a safe process.
  • Key hierarchy: a master key wraps key-encryption keys, which wrap the data keys that encrypt your data (envelope encryption).
  • Control and proof: access policies say who may use a key, and an audit log records every use.

02Concept: What is it?

Encryption is only as strong as the protection of its key. If a key sits in a config file next to the data, an attacker who gets one gets both. A KMS solves this by being a small, hardened service whose only job is to hold keys and do cryptographic work with them. Many are backed by HSMs (hardware security modules), special devices built so that keys cannot be copied out.

You already know envelope encryption from the Encryption at Rest topic: each piece of data gets its own data encryption key (DEK), and a master key inside the KMS wraps (encrypts) that DEK. This topic is about running that safely day to day: who may use a key, how often to rotate it, what happens when it is lost, and how to delete data by deleting a key.

A key hierarchy
πŸ›οΈRoot / master keyinside HSM, never exported
→↓wraps
πŸ”‘Key-encryption key (KEK)per service or tenant
→↓wraps
πŸ—οΈData key (DEK)per file, row or customer
→↓encrypts
πŸ“¦Your data
Each level protects the one below. Only the top level stays inside the KMS or HSM.
🧠You send the data to the key, not the key to the data
Applications ask the KMS to wrap or unwrap a data key. The master key is never handed over. That is why a stolen database dump is useless without access to the KMS.

03Real-Life Example

🍡The Bank Vault and the Key Ledger
A bank keeps the master key to its vault in a guarded room. Staff never take it out. They ask the vault keeper to open one box, show their ID, and the keeper writes the request in a ledger. Each customer has their own small box key, kept inside a sealed envelope that only the vault keeper can open. If a customer leaves, the bank shreds their box key, so even a photocopy of the box contents cannot be opened. Changing the vault lock does not mean emptying every box: you only reseal the envelopes.
Bank
KMS
The vault master key
The master key in an HSM
The vault keeper
The KMS API
Sealed envelope with a box key
A wrapped data key
The ledger
The KMS audit log
ID check before opening
Access policy and authentication
Changing the vault lock
Rotating the master key (re-wrap, not re-encrypt data)
Shredding one customer's key
Crypto-shredding

04Why Do We Need It?

πŸ”’Keys stay safe
Keys live in hardened hardware and are never shown to apps or people.
πŸ“œEvery use is logged
You can see who used which key and when, for audits and investigations.
🚦Fine access control
A service can be allowed to encrypt but not decrypt, or to use one key only.
πŸ”Easy rotation
Change the master key on a schedule without re-encrypting all your data.
πŸ—‘οΈDelete by destroying a key
Deleting a key makes all data under it unreadable, including copies in backups.
βœ…Compliance
Standards and laws often ask for managed keys, rotation and separation of duties.
Without key management, encryption just moves the secret somewhere else. A KMS makes the key the best-protected thing in your system.

05Where Do We Use It?

πŸ’ΎDisk and database encryption
Cloud storage, databases and volumes ask the KMS to wrap their data keys.
πŸͺ£Object storage
Each object or bucket gets a data key. A bucket policy can require a particular KMS key.
🏒Multi-tenant SaaS
A key per customer allows per-tenant deletion and customer-controlled keys.
πŸ”Signing
Code signing, JWT signing and certificate authorities use keys that must never leak.
🧾Sensitive fields
Card numbers and personal data are encrypted by the app with keys from a KMS.
πŸ”Secrets stores
A secrets manager encrypts the secrets it holds with a KMS key.

06Types / Parts / How It Works

The key lifecycle

StageWhat happensGood practice
GenerateA strong random key is made inside the KMS or HSMNever make keys in app code or on a laptop
StoreThe key is kept in hardware or an encrypted storeNo plain copy outside the KMS
UseApps call encrypt, decrypt, wrap, unwrap or signLeast privilege, one purpose per key
RotateA new key version is created and used for new workAutomatic on a schedule, and after any suspected leak
Revoke / disableThe key is turned off so it cannot be usedUsed in an incident, can be undone
DestroyThe key is deleted for goodUse a waiting period, and be sure nothing still needs it

Who holds the master key?

ModelWho controls the keyTrade-off
Provider-managedThe cloud provider, by defaultEasiest. You trust the provider fully.
Customer-managed (CMK)You control policy, rotation and deletion in the provider's KMSA good middle ground and the usual choice
BYOK (bring your own key)You make the key and import itMore control, more work. A copy exists outside the KMS.
HYOK / external key storeThe key stays in your own HSM and the cloud calls out to itMost control, but if your HSM is down, the cloud data is unreadable

Rotation without re-encrypting everything

Rotate the master key, re-wrap the DEKs
Before
πŸ›οΈMaster v1
πŸ—οΈDEKs wrapped by v1
πŸ“¦Data (encrypted by DEKs)
After
πŸ›οΈMaster v2 (v1 kept for old wraps)
πŸ—οΈDEKs re-wrapped by v2
πŸ“¦Data unchanged
Only the small wrapped keys change. The large data stays as it is.
Master key Data keys Data
VisualizerRotate, revoke and shred, and see what stays readableRotate the master key and note that no data blob is re-encrypted. Then delete one customer's key (crypto-shredding), and finally disable the master key. Switch to β€œone key for everything” to see why rotation becomes painful.
πŸ”
KMS master key Β· version 1
never leaves the KMS, only wraps and unwraps
🏒Customer A
orders-A.db
DEK: wrapped by master v1
βœ“ readable
🏬Customer B
orders-B.db
DEK: wrapped by master v1
βœ“ readable
🏭Customer C
orders-C.db
DEK: wrapped by master v1
βœ“ readable
Readable
3 / 3
customers
DEKs re-wrapped
0
last rotation
Data blobs re-encrypted
0
last rotation
Press a button. Each customer has its own DEK, and a master key wraps every DEK. Try rotate, then shred one customer, then revoke the master key.
  • Created master key v1. Each customer got its own data key (DEK), wrapped by v1.

A simulation with no real cryptography. Real KMS services also keep older key versions so data wrapped by them can still be unwrapped.

07How to Use It / Steps / Implementation

Using a KMS well

  1. 1
    Choose the key scope
    One key per purpose, environment and often per tenant. Do not share one key across unrelated systems.
  2. 2
    Write a tight access policy
    Separate who administers a key from who uses it. A service that only encrypts should not be able to decrypt.
  3. 3
    Use envelope encryption
    Ask the KMS for a data key, encrypt locally, and store only the wrapped key next to the data.
  4. 4
    Cache data keys carefully
    A KMS call on every request is slow and may be rate-limited. Cache unwrapped DEKs in memory for a short time, never on disk.
  5. 5
    Turn on rotation
    Automatic rotation with versions. Old versions stay available to unwrap old keys.
  6. 6
    Log and alert
    Send key-use logs to your audit system. Alert on odd patterns, such as a burst of decrypt calls.
  7. 7
    Protect deletion
    Use a waiting period before a key is destroyed, and require approval. Back up what you need.
  8. 8
    Plan for loss and regions
    Decide what happens if the KMS or a region is down. Use multi-region keys if you fail over.
Envelope encryption, in outline
dek_plain, dek_wrapped = kms.generate_data_key(key_id)
ciphertext = aes_gcm_encrypt(dek_plain, data)
store(ciphertext, dek_wrapped)      # never store dek_plain
forget(dek_plain)

# to read:
dek_plain = kms.decrypt(dek_wrapped)  # KMS checks policy and logs it
data = aes_gcm_decrypt(dek_plain, ciphertext)
⚠️Deleting a key is forever
If you destroy a key that still protects data, that data is gone, backups included. Use waiting periods, test restores, and know exactly what each key protects.

08Key Terms to Know

TermMeaning in easy words
KMSKey Management Service: a service that makes, stores and uses keys safely
HSMHardware security module: a device that holds keys and does crypto without letting keys out
DEKData encryption key: encrypts the actual data
KEKKey encryption key: wraps and unwraps other keys
Master / root keyThe top key, kept inside the KMS or HSM
Wrap / unwrapEncrypt or decrypt a key with another key
Envelope encryptionData encrypted by a DEK, and the DEK wrapped by a master key
Key rotationReplacing a key with a new version on a schedule
Key versionOne generation of a key, kept so old data can still be read
Crypto-shreddingDeleting data by destroying the key that encrypts it
BYOK / HYOKBring your own key / hold your own key, for more customer control
Separation of dutiesThe people who manage keys are not the ones who use them
Key escrowA secure backup of a key, to recover from loss

09Pros, Cons and Trade-offs

βœ… Pros
  • Keys are protected in hardened hardware
  • Every use is logged and can be audited
  • Rotation is cheap with envelope encryption
  • Per-tenant keys allow easy deletion
  • Fine control over who may use which key
⚠️ Cons
  • The KMS is a critical dependency: if it is down, data is unreadable
  • Extra latency and per-call cost
  • Request rate limits on busy systems
  • Losing or deleting a key loses data
  • More design work for access policies and rotation

Trade-offs

ChoiceWe gainWe lose
Provider-managed keysZero effortLess control and proof
Customer-managed keysControl over policy and deletionYou own the mistakes
Key per tenantEasy per-tenant erase, isolationMany keys to manage and pay for
Cache DEKsFaster, fewer KMS callsKeys sit in memory for a while
External key store (HYOK)Keys never in the cloudCloud data depends on your HSM being up

10Common Problems and Mistakes

Common mistakes

  1. Keys in code or config. Even an encrypted file is weak if the key is next to it.
  2. One key for everything. Rotation, deletion and access control all become all-or-nothing.
  3. Everyone can decrypt. A broad policy lets a hacked service read every secret.
  4. No rotation. A key that never changes gives an attacker unlimited time.
  5. Deleting too fast. A mistaken deletion destroys data. Use a waiting period.
  6. Forgetting backups and regions. The key must be available wherever the data can be restored or failed over.
  7. Calling the KMS on every request. You hit latency or rate limits. Cache short-lived DEKs.

Things to watch

🧱Single point of failure
A KMS outage can take down every service that decrypts at start-up. Cache and plan for it.
🌍Regions
Keys are often regional. Use multi-region keys, or re-wrap data when you replicate.
πŸ•΅οΈInsiders
Admins of the key should not be able to read data without being logged. Separate the duties.
πŸ“‰Cost and limits
Calls are priced and rate-limited. Measure before a launch.

11Real-World Examples

☁️AWS KMS
Customer-managed keys with policies, automatic rotation, grants and CloudTrail logs. Used by S3, EBS, RDS and many more.
🌐Google Cloud KMS
Key rings, versions and rotation, with Cloud HSM and external key options.
πŸͺŸAzure Key Vault
Stores keys, secrets and certificates, with managed HSM options and access policies.
πŸ—οΈHashiCorp Vault (Transit)
Encryption as a service: apps send data and get ciphertext back, and keys never leave Vault.
πŸ›οΈHardware HSMs
Used by banks, card networks and certificate authorities for their root keys.
🏒SaaS customer-managed keys
Some SaaS products let customers hold the key and cut off the vendor's access by disabling it.
Mini case: erase one tenant
🏒Tenant X leaves
→↓destroy their key
πŸ—οΈKey X goneafter waiting period
→↓all copies unreadable
πŸ’ΎData, replicas, backupsnoise without the key
One key per tenant turns 'delete everything for tenant X' into one safe operation.

12Related Topics to Read Next

Encryption at Rest→

The base idea: envelope encryption, DEKs and master keys.

Secrets Management→

Where passwords and API keys live, protected by a KMS.

SSL/TLS→

Uses keys and certificates that a KMS or HSM can protect.

Certificates and PKI→

A chain of trust built on keys that must be kept safe.

Audit Logs→

The record of every key use.

Data Privacy and GDPR Basics→

Crypto-shredding is one way to meet erasure requests.

Multi-Tenancy→

Per-tenant keys give isolation and easy deletion.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”KMS: a hardened service that holds keys and does crypto for you.
  • βœ”Hierarchy: master key β†’ KEK β†’ DEK β†’ data.
  • βœ”Rotate: new master version, re-wrap DEKs. No data re-encryption.
  • βœ”Control: tight policy, separate admin from use, log every call.
  • βœ”Delete data: destroy the key (crypto-shredding), with a waiting period.
  • βœ”Performance: cache DEKs briefly in memory, watch rate limits.
  • βœ”Risks: KMS outage, lost key, regional keys, key in code.
  • βœ”One line: β€œSend the data to the key, never the key to the data.”
← Previous
Zero Trust
Next β†’
Data Privacy and GDPR Basics