← Building blocks

Protect data and secrets

Security & abusesenior

Credentials in config files; sensitive data readable by anyone with disk access.

Say it like this

Secrets never live in code or config, and data is encrypted in transit and at rest with keys I can rotate, so a leaked disk, log or repository exposes nothing usable.

Basic solution

Keep secrets in a vault with rotation; encrypt data in transit (TLS) and at rest (KMS-managed keys); hash passwords with a slow hash.

VaultAWS KMS / Secrets Managerbcrypt / Argon2TLS everywhere

Vault for secrets, KMS-wrapped keys for data

Services fetch secrets from the vault using their own identity; traffic is TLS end to end; the store encrypts rows with a data key that only the KMS can unwrap, so disks and backups are useless without it.

How it works

  1. Secrets (database passwords, provider API keys, signing keys) live in a vault, a service whose only job is to hold them. Each service authenticates to the vault with an identity of its own, such as an IAM role or a Kubernetes service account, and fetches its secrets at start-up or leases them with a time limit after which they must be renewed.
  2. Data in transit uses TLS on every hop: client to edge, edge to service, and service to service inside the network, using mutual TLS or a service mesh. Nothing travels in plaintext even on a private network.
  3. Data at rest uses envelope encryption. Each record or file is encrypted with its own data key; that data key is itself encrypted with a master key held in a key management service (KMS) and stored next to the data. The database or object store does this transparently for everything, or the application does it for specific fields that need extra protection.
  4. Passwords are never encrypted, because nothing should ever need to decrypt them. They are hashed with a slow, salted algorithm (Argon2id, bcrypt), so a stolen table cannot be turned back into passwords at any useful speed.
  5. Rotation runs on two tracks. Master keys rotate on a schedule by re-wrapping the data keys, which touches a few bytes per record rather than the data itself. Secrets rotate by issuing a new credential, moving the consumers to it, and then revoking the old one.

What each layer protects against

  • Vault: secrets ending up in repositories, config files, environment dumps and chat logs.
  • TLS: anyone on the network path reading or altering traffic.
  • Encryption at rest: lost disks, backups and snapshots being read outside the database.
  • Slow hashing: a leaked user table being turned into working passwords.

Worked example

Notification system

  • Secrets: Twilio, SES and APNs credentials, the database password, the webhook signing secret. Six secrets, each fetched once at service start by 200 worker instances: 1,200 vault reads per deploy, a few per hour after that with lease renewal. The vault is nowhere near the request path.
  • Device tokens: 100M rows of 200 bytes = 20 GB. Encrypted at rest by the database with an AES-256 data key wrapped by a KMS master key. AES-GCM on modern CPUs runs at over 1 GB/s per core, so the overhead on 50M writes/day is unmeasurable.
  • Field-level encryption for the few sensitive template variables (a one-time code, an account balance): the app encrypts with a per-tenant data key before insert. Encrypt plus decrypt costs about 20 microseconds; at 2,900 sends/s that is 0.06 CPU-seconds per second.
  • Password hashing for the preferences portal: Argon2id tuned to ~100 ms per hash. Login at 50/s needs 5 CPU-seconds per second, so a dedicated small pool of login workers rather than the API fleet.
  • Rotation: provider API keys every 90 days with a 7-day overlap; KMS master key yearly, which re-wraps data keys in minutes without re-encrypting 20 GB.

Variants and when each wins

Secrets in environment variables from a deploy pipeline

  • The pipeline injects values into the process environment at deploy time. It wins for small systems with few secrets because it is simple; the values still sit in the orchestrator's config and in process environments that crash dumps and debug endpoints can expose.

Vault with dynamic, short-lived credentials

  • The vault mints a database user per service instance with a one-hour lease and revokes it when the lease ends. It wins because a leaked credential dies on its own; it adds moving parts and makes the vault's availability matter at start-up.

Transparent (database or disk) encryption only

  • The storage layer encrypts everything with no application change. It wins against lost disks and copied backups; it does nothing against an application bug or a compromised database account, which read everything decrypted.

Application-level field encryption

  • The application encrypts specific fields before they reach the store, with keys per tenant or per user. It wins when a database-level compromise must not expose those fields, and it enables crypto-shredding (delete the key and the data is gone); it breaks indexing and search on the encrypted fields.

Recommendation: vault with dynamic credentials, TLS everywhere, transparent encryption for the whole store, field-level only for the handful of fields where a database compromise must not expose them.

Failure modes

Secret committed to a repository

  • A provider key shows up in git history, where it stays even after the file is deleted. It happens because a config file held real values. Scan for secrets in CI, use keys with recognisable prefixes so scanners find them, rotate the leaked key immediately, and remove secrets from config entirely by fetching them from the vault.

Encryption at rest without key separation

  • The backup is encrypted, but the key sits in the same bucket next to it. It happens because the key was stored on the same host or in the same storage as the data. Hold master keys in a KMS, use envelope encryption, and give the data and the keys separate access policies.

Secrets in logs

  • Authorization headers or passwords appear in the log store. It happens because the code logs whole requests. Add a redaction list to the logging library, deny-list header names, and log the hash of a key rather than the key.

Vault outage takes down deploys

  • New instances fail to start while running ones are fine. It happens because secrets are fetched only at boot and there is no cached copy. Cache secrets encrypted on the node, retry with backoff, and run the vault as a highly available service in its own right.

Fast hash for passwords

  • A leaked user table yields millions of passwords within hours. It happens because MD5 or SHA-256 was used for password hashing, and those are designed to be fast. Use Argon2id or bcrypt with a per-user salt and a cost that takes tens of milliseconds, and rehash each user on their next login after a parameter change.

Interviewer follow-ups

Answer out loud before you open each one.

What is envelope encryption and why not use the master key directly?

Data is encrypted with a data key; the data key is encrypted with the master key in the KMS. The master key never leaves the KMS and is used only to wrap and unwrap small keys, so bulk encryption stays fast and local, and rotating the master key means re-wrapping data keys, not re-encrypting terabytes.

How do you rotate a database password with no downtime?

Create a second user with the same grants, update the vault, have services pick it up on lease renewal or restart over a few minutes, confirm from connection logs that the old user is idle, then drop it. Dynamic credentials from a vault make this automatic: every instance already has its own short-lived user.

Does encryption at rest protect against a SQL injection bug?

No. The database decrypts transparently for any query it runs, so an injected query reads plaintext. Encryption at rest defends against lost disks and copied backups. Against application bugs you need input validation, least-privilege database accounts, and field-level encryption for the most sensitive columns.

Why hash passwords slowly when everything else should be fast?

The cost is paid once per login by you and millions of times per guess by an attacker with a stolen table. A 100 ms hash makes brute-forcing a strong password infeasible while costing a user nothing noticeable. Keep it off the general API fleet so an attacker cannot use login as a CPU denial-of-service vector.

Connections

Built on
Merkle tree
Pairs with
Terminate TLS at the edge · Authenticate, then authorise · Identify API clients · Recover from bad data, not just dead disks · Log so you can query

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingNotification workerCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
AWS KMSVault, KMSCloud KMSKey VaultHashiCorp Vault, OpenBao
Amazon DynamoDBDevice token storeFirestore, BigtableCosmos DBScyllaDB, Apache Cassandra
Amazon S3Backups + snapshotsCloud StorageBlob StorageCloudflare R2, MinIO, Ceph