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

Secrets Management

Keep passwords, API keys and certificates out of code, and hand them out safely.

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

01Quick Summary

A secret is any value that gives access if someone else learns it: a database password, an API key, a private key, a token, a certificate. Secrets management is how you store, hand out, rotate and watch those values safely.

  • Secrets must never live in source code, in git history, in container images or in logs.
  • A secret manager (a vault) keeps them in one place, gives each service only what it needs, and logs every read.
  • The best secrets are short-lived and created on demand, so a leak expires by itself. Rotate the rest on a schedule.

02Concept: What is it?

Your app needs secrets to do its job: to log in to the database, call a payment service, sign tokens or open a TLS connection. The easy way is to type the value into the code or a config file. That is also the dangerous way, because code is copied everywhere: to every developer laptop, to the build server, to the container image and to the git history, where it stays even after you delete the line.

A secret manager (for example HashiCorp Vault, or the managed services of the big clouds) solves this. The secret lives in one protected store. When a service starts, it proves who it is (using an identity such as a cloud role or a Kubernetes service account) and asks for the secrets it is allowed to have. The vault checks the rules, hands the secret over and writes a line in the audit log.

Better still are dynamic secrets. Instead of one shared password that lives for a year, the vault creates a new database user for each app instance, with a lease that expires in hours. If that credential leaks, it is unique, narrow and short-lived, and the vault can revoke it at once.

Hard-coded versus fetched from a vault
Secret in the code
πŸ“Repohas the password
→↓copied to
πŸ’»Laptops, CI, imagesall hold it
Secret in a vault
πŸ–₯️Serviceproves its identity
→↓asks
πŸ”Vaultchecks, logs, hands over
With a vault the secret is not in the code or the image. It is delivered at run time to an identified service.
🧠Deleting a leaked secret is not enough
Once a secret reached git, a log or an image, assume it is public. Removing it from the latest commit does not remove it from the history or from the copies. The fix is to rotate it: make a new one and cancel the old one.

03Real-Life Example

🍡The Hotel Key Cards
A small hotel used one metal key for every room and gave a copy to every cleaner. When a cleaner left, nobody knew who still had a copy, and changing the lock meant changing every door. A better hotel uses key cards. The front desk (the vault) makes a card for one guest, for one room, for one night. It records who asked. The card stops working on its own at checkout, and a lost card is cancelled in one click.
Hotel
Secrets management
One metal key copied for everyone
A shared password hard-coded in the code
The front desk that makes cards
The vault or secret manager
Showing ID to get a card
A service proving its identity to the vault
A card for one room only
Least privilege: only the secrets that service needs
A card that expires at checkout
A short-lived dynamic secret with a lease
Cancelling a lost card
Revoking a credential at once
The desk's log of who got a card
The audit log of secret reads
Changing all the locks
Rotating a long-lived shared secret
How a service gets a database credential
πŸͺͺIdentifycloud role or service account
→↓
πŸ”Vault checksis it allowed?
→↓
πŸ—οΈNew credentialshort lease
→↓
πŸ—„οΈUse itthen it expires

04Why Do We Need It?

πŸ”“Leaks are common
Secrets end up in public repos, chat messages, screenshots and logs far more often than they are broken by clever attacks.
🎯Small blast radius
Each service gets only its own secrets, so one leak does not open everything.
⏳Leaks expire
Short-lived credentials stop working by themselves, even if nobody notices the leak.
πŸ”Easy rotation
Change a secret in one place and the services pick it up, with no code change or redeploy.
πŸ”Know who read what
An audit log answers who used which secret, and when.
πŸ“œRules and audits
Standards for payment, health and security teams expect controlled and logged access to secrets.
Treat secrets like keys to the building: hand them out one at a time, to known people, for a short time, and write it down.

05Where Do We Use It?

πŸ—„οΈDatabase logins
Fetch a password at start-up, or get a fresh dynamic user for each instance.
πŸ”ŒThird-party API keys
Payment, email and map services all hand out keys that must stay private.
πŸͺͺSigning and TLS keys
Private keys for tokens and certificates are among the most sensitive secrets you have.
πŸ—οΈCI/CD pipelines
Build and deploy jobs need credentials. Give them short-lived ones, scoped to one job.
☸️Containers and Kubernetes
Mount secrets at run time. Never bake them into an image.
πŸ‘©β€πŸ’»Developers
Developers use their own limited, logged access, not the production passwords.

06Types / Parts / How It Works

Where a secret can live

PlaceHow it is usedMain risk
In the source codeTyped into a file in the repoCopied everywhere and kept forever in git history. Never do this.
In a config or .env file in the repoLoaded at startSame as code if it is committed. Local files must stay out of git.
In the container imageBaked in at build timeAnyone who can pull the image can read it, and old layers keep it.
Environment variables set by the platformInjected at deployBetter, but often long-lived, shared, and visible in dumps and crash reports.
Secret manager, fetched by the appFetched with the service identityCentral, controlled and logged. The app still holds it in memory.
Dynamic, short-lived credentialsCreated per instance with a leaseBest. A leak expires soon and is narrow. Needs a vault that can create them.

The secret lifecycle

From creation to retirement
πŸ†•Createrandom, strong
→↓
πŸ—ƒοΈStorein the vault
→↓
πŸ”‘Distributeto identified services
→↓
πŸ”„Rotateon a schedule
→↓
πŸ—‘οΈRevokewhen no longer needed
A secret that is never rotated or retired is a leak waiting to happen.
VisualizerWhere is the secret kept? Leak it four waysStart with the secret in code and leak the repo. Then try an environment variable, a vault and dynamic credentials. Change the rotation and notice times and watch how long the attacker can use it.
Where does the app keep its database credential?

Copied to every clone, build and laptop.

What goes wrong?
How the secret is kept
const DB_PASSWORD = "..." (in the repository)
Access it gives: Full database access, shared by every service
Audit log of who read it: no
Event
The repository leaks (a public fork, a stolen laptop, a former contractor).
The attacker can read the secret
The repository leaks (a public fork, a stolen laptop, a former contractor). The secret is right there. It gives full database access, shared by every service, and stays valid until someone notices and rotates it everywhere it was copied.
Secret readable
Yes
in this event
Attacker can use it for
30 days
until noticed or expired
Blast radius
Wide
Full database access, shared by every service

A teaching model with illustrative numbers (a vault secret rotated every 90 days, a dynamic credential living about 1 day). Real risk depends on your setup. The pattern holds: keep secrets out of code and images, give each service only what it needs, make them short-lived, and watch who reads them.

07How to Use It / Steps / Implementation

Handling secrets well

  1. 1
    Keep secrets out of code, git and images
    Add secret files to .gitignore, and run a secret scanner on commits and in CI to catch mistakes before they spread.
  2. 2
    Use a secret manager
    Store secrets in a vault or your cloud's secret service. Let services fetch them at run time using their own identity, not a shared key.
  3. 3
    Give least privilege
    Each service may read only its own secrets. Each secret should open only what it must, for example one schema, not the whole database.
  4. 4
    Prefer short-lived and dynamic secrets
    Use leases, tokens that expire and per-instance credentials, so a leak runs out fast.
  5. 5
    Rotate on a schedule and after any leak
    Make rotation a normal, automated job. If rotation is scary, it is not practised enough.
  6. 6
    Never print secrets
    Mask them in logs, error messages, crash dumps and CI output. Do not pass them on the command line, where other users can see them.
  7. 7
    Audit and alert
    Log each read, and alert on odd patterns such as a service reading secrets it never used, or a burst of reads at night.
  8. 8
    Plan the leak response
    Know how to revoke and replace each secret quickly, and who does it. Practise it before you need it.
πŸ’‘Solve the first secret
A vault needs some way to know who is asking. Use the platform identity (a cloud role, a Kubernetes service account) so that no long-lived password has to be handed to the app to unlock the vault.
⚠️Config files are not a vault
A .env file or a plain environment variable is fine for local development with fake values. In production, it has no access control, no audit log and no rotation.

08Key Terms to Know

TermMeaning in easy words
SecretA value that gives access if someone learns it: passwords, API keys, tokens, private keys
Secret manager / vaultA service that stores secrets, controls access to them and logs every read
Least privilegeGive each service and secret only the access it needs, and no more
Dynamic secretA credential the vault creates on demand for one client, with a short life
Lease / TTLThe time a secret or token stays valid before it expires
RotationReplacing a secret with a new one and retiring the old one
RevocationCancelling a secret right now, before it would expire
Service identityHow a workload proves who it is, such as a cloud role or service account
Secret scanningA tool that searches code and history for accidentally committed secrets
Audit logA record of who read or changed which secret, and when
Secret sprawlSecrets scattered across code, tickets, chats and machines with no owner

09Pros, Cons and Trade-offs

βœ… Pros
  • Secrets stay out of code, images and repos
  • Central control and a full audit trail
  • Easy and safe rotation
  • Short-lived credentials limit the damage of a leak
  • Each service gets only what it needs
⚠️ Cons
  • The vault becomes a critical dependency that must be highly available
  • Extra set-up and a learning curve
  • Apps must fetch secrets at start-up and handle rotation
  • The vault itself must be protected very well
  • A secret in a running app's memory can still be read by a host takeover

Trade-offs

ChoiceWe gainWe lose
Environment variablesSimple, works everywhereLong-lived, shared, little control or audit
Secret managerCentral control, audit and rotationA new dependency and some set-up
Dynamic credentialsSmall blast radius, auto-expiryMore moving parts, and the target system must support it
Short leaseA leak dies soonMore renewals, and failures if the vault is unreachable
Long leaseFewer calls to the vaultA leak stays useful for longer
Cache secrets in memoryFast, survives short vault outagesStale values after a rotation, and exposure in memory

10Common Problems and Mistakes

Common mistakes

  1. Committing a secret. It lives in git history even after you delete it. Rotate it, do not just remove it.
  2. Baking secrets into images. Every layer and every registry copy holds it.
  3. One shared secret for everything. One leak opens every door, and nobody can tell who used it.
  4. Logging secrets. Debug output, error pages and CI logs are read by many people and tools.
  5. Never rotating. An old secret that many people once saw is a long-term risk.
  6. Over-broad access. If every engineer or service can read every secret, the vault gives little protection.
  7. No plan for a leak. When it happens, nobody knows which secrets to revoke or how.

Things to watch

πŸ’₯Vault outage
If services cannot fetch secrets at start, they cannot start. Run the vault in a highly available way and cache carefully.
πŸ”„Rotation breaks apps
Apps that read a secret once at start will fail after a rotation. Support refresh or overlap old and new for a while.
🧭Secret sprawl
Secrets copied into tickets, chats and wikis. Scan and clean up.
πŸ§ͺTest and staging
Real production secrets in a test environment widen the risk. Use separate, lower-power secrets.

11Real-World Examples

🏒Vault-style tools
Teams run a secret manager such as HashiCorp Vault, or use the managed secret services of their cloud, to keep secrets in one place.
☸️Kubernetes
Secrets are mounted into pods at run time, often from an external secret manager, and tied to a service account.
πŸ—„οΈDynamic database users
A vault can create a database user with a lease for each app instance, then remove it when the lease ends.
πŸ”Secret scanning
Code hosts and CI tools scan for accidentally committed keys and can alert or block the push.
πŸ—οΈPipelines
Modern CI systems can exchange a trusted identity for short-lived cloud credentials, with no stored long-lived keys.
🚨Leak response
After a leak, teams rotate the secret first and investigate second, because the old value must stop working.
πŸ“Note
Product names and features change. Check the documentation of your secret manager and platform for what it supports, such as dynamic secrets and identity-based access.
Mini case: a key committed by mistake
Long-lived shared key
πŸ“Key in repovalid for a year
→↓scraped
😈Attackerfull access for weeks
Short-lived scoped credential
πŸ“Credential in logexpires in a day
→↓scraped
😈Attackerexpired or narrow
Wide and long Narrow and short
Two ways the same mistake plays out.

12Related Topics to Read Next

Encryption at Rest→

Keys are secrets too, and a KMS protects them.

Password Management→

User passwords need a different, one-way approach.

SSL/TLS→

Private keys and certificates are secrets to protect.

RBAC→

Controls which people and services may read which secret.

CI/CD Pipelines→

Pipelines need short-lived credentials, not stored keys.

OAuth / OAuth2β†’

Tokens are short-lived secrets with scopes.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”Secret: any value that gives access if learned. Passwords, keys, tokens, certificates.
  • βœ”Never in: code, git history, container images, logs, tickets and chats.
  • βœ”Use: a vault or cloud secret manager. Services prove identity with a role or service account.
  • βœ”Best: dynamic, short-lived, per-instance credentials with a lease.
  • βœ”Least privilege: each service gets only its own secrets with only the access it needs.
  • βœ”Rotate: on a schedule and after any leak. Support overlap so nothing breaks.
  • βœ”Leak plan: rotate first, investigate with the audit log, then add scanning.
  • βœ”One line: β€œHand out keys to known people, one at a time, for a short time, and write it down.”
← Previous
Encryption at Rest
Next β†’
Password Management