All posts
System Design Mastermind · F15
  • System design
  • Interview prep
  • Security
  • Auth

Security essentials for system design

Foundations F15. What to say when the interviewer asks "how do you secure this?": authentication and password storage, sessions vs signed tokens and how to revoke them, OAuth 2.0 and OpenID Connect, authorization and least privilege (BOLA is still #1), TLS 1.3, mTLS and zero trust, envelope encryption, keys and secrets, injection, XSS, CSRF and SSRF, and edge defence against DDoS and abuse. Each idea is told as a story you'll remember, with a lab that shows how long a stolen token keeps working and what checking it costs.

23 Oct 2026 · 26 min read · interactive

Share

Start here

Security comes up in every design round, usually as one question near the end: "how do you secure this?" A weak answer lists words: "OAuth, HTTPS, encryption, a firewall". A Senior answer walks one request: how the user proves who they are, what the request carries afterwards and how long that stays valid, how the server decides this user may touch this object, how the bytes are protected on the wire and on disk, where the keys live, why no input is trusted, and what stops a flood at the edge.

This page covers those eight ideas. They belong together because each one closes a door the others leave open: strong passwords don't help if every service trusts any caller inside the network, and encryption doesn't help if the key sits in the code. The OWASP Top 10 (2025) still puts broken access control first, which is a reminder that most real breaches are a missing check, not broken cryptography. Rate limiting has its own page; this one covers how it fits with the rest of the edge.

The one story for this page

Diwali week at a gated society in Hyderabad

A gated society in Gachibowli: twelve towers, two thousand flats, one main gate, and a society app on every resident's phone. It's Diwali week, so everyone is coming and going: guests, cooks, delivery riders, courier vans, the electrician, a crowd for the cultural night. Everything on this page happens at that gate and inside it:

  • The guard asks who you are, and the flat decides whether you may come up. (authentication)
  • A visitor pass printed with today's date, or the guard calling the flat every time. (sessions and tokens)
  • Letting the delivery rider reach your door without giving him your house key. (OAuth and OpenID Connect)
  • The housekeeping badge that opens corridors but not flats, and logs every swipe. (authorization and least privilege)
  • The sealed courier bag, and the rule that being inside the gate doesn't make you trusted. (encryption in transit, mTLS and zero trust)
  • The key cabinet in the office, and the one key that lives in a bank locker. (encryption at rest, keys and secrets)
  • A note handed to the guard: "please let the bearer collect any parcel". (never trust input)
  • The cultural night, when a thousand people arrive at the gate at once. (edge defence: DDoS, WAF and abuse)

The society is a teaching story; the companies, standards, incidents and numbers cited on this page are real.

✅ Seen: a company said so (cited)🔶 Inferred / typical🧭 Interview choice

Authentication: proving who you are

Authentication proves who the caller is; store passwords only as slow, salted hashes (Argon2id, bcrypt), add a second factor that can't be phished where it matters, and never let a login endpoint be guessed at for free.

The story · remember it like this

The guard at the gate

At the main gate, the guard doesn't just take your word for it. A resident shows the society app on their phone; a guest gives a name, and the guard sends a one-time code to the flat that invited them.

Two things make the gate strong. The guard needs two different proofs for anyone new: something you know (your name and flat number) and something you have (the phone that gets the code). And the guard's register doesn't keep your house key, only a note that you are expected.

The weak gate is the one with a printed list of every resident's PIN pinned to the cabin wall. One curious visitor with a phone camera, and every flat is open.

What it really is
  • Authentication (authn) answers "who are you?"; authorization (authz) answers "may you do this?". Different questions, different code; this section is the first one.
  • Passwords are stored as hashes, never as text or reversible encryption. Use a slow, memory-hard function (Argon2id, scrypt, or bcrypt for older systems) with a unique random salt per user, so a stolen table takes years to crack instead of hours. Fast hashes like SHA-256 are wrong here: their speed helps the attacker.
  • MFA adds a second factor of a different kind. SMS and app codes stop password reuse; passkeys (WebAuthn) and hardware keys also resist phishing, because the browser only signs for the real site.
  • Protect the login endpoint: credential stuffing tries leaked username/password pairs from other breaches. Defend with MFA, rate limits per account and per IP, breached-password checks and step-up checks for risky logins.
  • Machines authenticate too: services use certificates or short-lived workload identities, not shared passwords (see the in-transit section).
In a real system ✅ Seen · OWASP; NIST

OWASP's Password Storage Cheat Sheet (checked Oct 2026) recommends Argon2id with "a minimum configuration of 19 MiB of memory, an iteration count of 2, and 1 degree of parallelism", bcrypt only for legacy systems with a work factor of at least 10, and says fast hashes "such as SHA-256 are not suitable for password storage".

NIST SP 800-63B-4 (August 2025) requires single-factor passwords of at least 15 characters (8 when part of MFA), says verifiers "SHALL NOT impose other composition rules" or force periodic changes, requires checking new passwords against a blocklist of common and breached ones, and requires a phishing-resistant option to be offered at AAL2.

In India, the RBI's directions on authentication for digital payments (25 September 2025) set a minimum of two-factor authentication for digital payment transactions, to be complied with by 1 April 2026, and let issuers add risk-based checks on top. OWASP's credential stuffing cheat sheet cites Microsoft's analysis that MFA "would have stopped 99.9% of account compromises".

Trade-offs
  • A slower hash makes stolen hashes far harder to crack but costs CPU and memory on every login; tune it to about the time your login servers can afford (tens to hundreds of milliseconds), and rate-limit logins so attackers can't use it to overload you.
  • Stronger factors (passkeys, hardware keys) resist phishing but need recovery flows for lost devices; recovery is often the weakest link, so give it the same care as login.
Say it in the interview

Passwords are stored with Argon2id at OWASP's minimum settings and a per-user salt. Login is rate-limited per account and per IP and checks breached passwords. We offer passkeys, require a second factor for payments and new devices, and services authenticate with short-lived workload certificates, not shared secrets.

Trap

"We encrypt the passwords." Encryption can be reversed by whoever has the key; passwords must be hashed with a slow, salted function. Saying SHA-256 or MD5 here loses the point.

Sessions and tokens: what the request carries

After login, each request carries either a random session ID the server looks up, or a signed token (often a JWT) the services verify on their own; lookups make logout instant but put a store on every request, signed tokens scale but can't be taken back before they expire, so keep them short and pair them with a revocable refresh token.

The story · remember it like this

A printed pass, or a phone call every time

The society tried two ways of letting guests back in after the first check.

The first year, the guard called the flat every single time a guest walked in or out. Safe: if the resident said "not any more", the guest was stopped at once. But on Diwali evening the phone line was jammed, guests queued for twenty minutes, and when the intercom died, nobody could get in at all.

So they printed passes: "Guest of 1204, valid until 10 pm today", stamped with the society's seal that the guard can check at a glance. No calls, no queue. The catch came when a resident fell out with a guest at 6 pm. The pass in the guest's pocket still said 10 pm, and the guard had no way to know.

Now passes are valid for one hour and renewed at the gate, and the guard has a small board of cancelled passes that the office updates every few minutes.

What it really is

Two shapes of "logged in":

  • Session ID: a random value (at least 64 bits of entropy) in a cookie; the server keeps the session in a store (Redis, a database) and looks it up on each request. Logout deletes it, instantly. The cost is a lookup on every request and a store that every request depends on.
  • Signed token (JWT, RFC 7519): claims like user ID, expiry and audience, signed by the auth service. Any service can verify it with the public key, with no network call. The cost: it stays valid until it expires, whatever happens.

The usual combination:

  • A short-lived access token (5–15 minutes) that services verify locally.
  • A long-lived refresh token, stored by the auth service and revocable, swapped for a new access token when it expires. Rotate refresh tokens on use.
  • For "must stop now" cases (a stolen phone, a blocked account), a deny list of revoked token IDs pushed to services. It stays small because entries can drop off when the token would expire anyway.

Verifying a JWT properly: pin the algorithm (never accept "none" or a switched algorithm), check the signature, expiry, issuer and audience. A JWT is signed, not encrypted: anyone holding it can read the claims.

In the browser: keep session IDs and tokens in cookies marked Secure, HttpOnly and SameSite, and renew the session ID at login.

In a real system ✅ Seen · OWASP; RFC 8725

OWASP's Session Management Cheat Sheet (checked Oct 2026) says session IDs "must have at least 64 bits of entropy", must be regenerated after any privilege change such as login, and gives common idle timeouts of "2-5 minutes for high-value applications and 15-30 minutes for low risk applications". It says session cookies "must explicitly set SameSite=Strict (preferred) or SameSite=Lax" as defence in depth, alongside Secure and HttpOnly.

RFC 8725, JSON Web Token Best Current Practices (February 2020), requires libraries to let callers pin the allowed algorithms, says "each key MUST be used with exactly one algorithm", and that a relying party "MUST validate the audience value" and reject a JWT whose audience doesn't match. RFC 9700 (OAuth 2.0 Security BCP, January 2025) says refresh tokens for public clients "MUST be sender-constrained or use refresh token rotation" and access tokens "SHOULD be audience-restricted".

Trade-offs
  • Server-side sessions: instant logout and small cookies, but a lookup per request and a store on the critical path. Signed tokens: no lookup and easy across services, but revocation waits for expiry unless you add a deny list.
  • Shorter access tokens make revocation faster but multiply refresh traffic and make an auth outage bite sooner; 5–15 minutes is the common middle.
Say it in the interview

Login returns a 15-minute JWT access token with user, scopes and audience, and a rotating refresh token kept server-side. Every service verifies the JWT locally with the auth service's public keys, pinned to one algorithm. Logout revokes the refresh token, and for stolen devices we push the token ID to a deny list that every service checks, so it dies within seconds, not 15 minutes.

Trap

"JWTs are stateless, so there's no session store to scale" with a 24-hour expiry. Then logout, password reset and "block my account" don't work for a day. Say how you revoke.

Try it: How long does a stolen token work, and what does checking cost?

Services must answer "who is this?" on every request. Pick how: signed tokens each service verifies locally, the same plus a deny list of revoked tokens, or a lookup in a session store. See the load on the auth service, how long a logged-out or stolen token keeps working, what an auth outage does, and the time added to each request. The verdict flips across the presets: a 24-hour JWT can't be revoked, a lookup on every request overloads the store, a cached lookup makes a short auth outage take everything down, one-minute tokens cause a refresh storm, and a 15-minute token with a deny list meets a bank's one-minute rule.

Start from

A shopping app with a million active users. Access tokens are JWTs that live for a day, so nobody has to refresh. Security wants a stolen or logged-out token dead within 15 minutes.

How services check identity
What we're sizingNumberHow we got itSo we decide
1 · The traffic
Identity checks per secondEvery request has to answer "who is this?" somewhere. The question is whether the answer is in the request (a signed token) or in a store someone must ask.400K
1.0M users × 6 requests/min ÷ 60 = 100K requests/s
× 4 services that each verify the token = 400K checks/s
Where the check happens decides what it costs: local checks scale with the services; lookups land on one store.
2 · Load on the auth service
Refreshes per secondSigned tokens move the work into the services; the auth service only sees each user once per token lifetime.12 (0%)
1.0M users ÷ (24 h × 60 s) = 12 refreshes/s; signature checks need no call
÷ capacity 20K/s = 0%
Comfortable.
3 · Revocation
A revoked token keeps working forLogout, a password change or "block my card" only helps once every service stops accepting the old token.up to 24 h
nothing checks a central list, so it lives until it expires: 24 h
requirement: 15 min
Too slow: shorten the token or add a deny list.
4 · When auth is down
Signed-in requests failing after 5 minThe more often services must ask the auth service, the sooner its outage becomes everyone's outage.0%
identity survives 24 h without the auth service (token lifetime)
at the end: min(1, 5 min ÷ 24 h) = 0%; averaged over the outage 0%; new logins fail throughout
A short auth outage blocks logins and some refreshes, not the whole app.
5 · Latency
Time added per requestVerifying a signature is a little CPU; a lookup is a network round trip, and its tail latency becomes every request's tail.200 µs
4 services × ≈0.05 ms to verify a signature = 200 µs
Small enough to ignore.
6 · Verdict for this setup
What you getA stolen token keeps working for up to 24 hServices check the signature and the expiry, and nothing else, so logging out or blocking the account doesn't stop a copied token: it works until it expires, 24 h later, against a requirement of 15 min. Shorten the token (15 minutes is common) and keep the long-lived part in a refresh token the auth service can revoke, or add a deny list of revoked token IDs.

Try: on 24-hour JWT, set the lifetime to 15 minutes. On Look up every request, cache for 60 seconds, then set the outage to 0. On 1-minute JWTs, set 15. On Bank, switch to plain JWT, then set the outage to 30 minutes. Model: rounded teaching values; token ages are spread evenly, refresh happens exactly at expiry, the gateway caches per token, and a real auth service also handles logins, MFA and key rotation.

OAuth 2.0 and OpenID Connect: delegation and sign-in

OAuth 2.0 lets a user give an app limited access to their data elsewhere without sharing their password (authorization code flow, with PKCE); OpenID Connect adds an ID token on top so the app also learns who the user is, which is what "Sign in with Google" uses.

The story · remember it like this

The rider who never gets your key

You order sweets for the Diwali party. The rider reaches the gate, and you don't go down and hand him your house key, and you don't tell the guard your own PIN so he can pretend to be you.

Instead you tap "approve" in the society app. The guard gets a pass from the society office that says: "rider for 1204, up to the door only, for the next 30 minutes". The rider never learns your PIN. The pass can't open your door, and it expires by itself. If you see something odd, you cancel it from the app.

And when your cousin visits, the gate doesn't make her register from scratch. Her own society's app vouches for who she is, and your gate decides what she may do here.

What it really is

OAuth 2.0 is about delegated authorization: a user lets a client app act on a resource server, within limited scopes, without the app ever seeing the password.

  • Roles: the user (resource owner), the client app, the authorization server that issues tokens, the resource server (API) that accepts them.
  • Authorization code flow: the app sends the user to the authorization server, the user logs in and approves scopes, the server redirects back with a short-lived code, and the app swaps the code for tokens over a back channel.
  • PKCE: the app first sends a hash of a random secret and later proves it knows the secret, so a stolen code is useless. Required for mobile and browser apps.
  • Client credentials for service-to-service calls with no user.
  • Avoid: the implicit flow (tokens in the URL) and the password grant (the app collects the user's password).

OpenID Connect adds authentication on top: an ID token (a JWT) that tells the app who the user is and how they logged in. OAuth alone says "this token may read photos"; OIDC says "this is Priya, signed in five minutes ago with MFA".

Inside a company, the same pattern gives single sign-on: one identity provider, many apps, and every API trusts tokens from it.

In a real system ✅ Seen · RFC 9700; OIDC

RFC 9700, the OAuth 2.0 Security Best Current Practice (January 2025), states that the resource owner password credentials grant "MUST NOT be used", that clients "SHOULD NOT use the implicit grant", and that "public clients MUST use PKCE" (RFC 7636, September 2015), with PKCE also recommended for confidential clients.

OpenID Connect Core 1.0 (OpenID Foundation; errata set 2, December 2023) defines the ID token, a signed JWT with the issuer, subject, audience, expiry and authentication time, which is what "Sign in with Google" and most enterprise single sign-on return to the app.

Trade-offs
  • Using an external identity provider removes password storage and gives MFA for free, but makes login depend on that provider; cache keys and keep sessions working through a short provider outage.
  • Fine-grained scopes limit what a leaked token can do but make consent screens and token handling more complex; start with a few coarse scopes that match real user actions.
Say it in the interview

Third-party apps use the authorization code flow with PKCE and get scoped, short-lived tokens; they never see the password. Our own web and mobile apps sign in through our identity provider with OpenID Connect, and every API checks the token's audience and scopes. Internal jobs use client credentials.

Trap

Calling OAuth an authentication protocol, or using an OAuth access token as proof of who the user is. An access token is for the API it was issued to; identity comes from the OIDC ID token, checked for issuer and audience.

Authorization and least privilege

Check, on the server, for every request, that this caller may do this action on this specific object; give every user, service and machine only the permissions its job needs; and log who did what, so a mistake or a stolen credential can only do limited, visible damage.

The story · remember it like this

The housekeeping badge

The housekeeping staff carry swipe badges. A badge opens the service lift, the corridors and the garbage room of the towers that staff member covers. It does not open any flat, the society office, or the other towers.

One morning a badge goes missing. It's annoying, but not a disaster: whoever finds it can reach a corridor in Tower C, not a single home. And every swipe is logged, so the office can see exactly where it was used.

The mistake the society once made: the plumber was given the master key "just for today" because it was easier than finding the right one. It stayed on his keyring for a month.

What it really is

Check every object, on the server. Authenticating the caller is not enough: GET /orders/9812 must check that order 9812 belongs to this user (or that this user's role allows it). Missing this check is BOLA / IDOR, the most common API flaw; changing the ID in the URL is all an attacker needs.

Models:

  • RBAC: permissions grouped into roles (customer, support agent, admin).
  • ABAC / policies: rules over attributes ("agents may read orders in their own region, during a ticket"). Often run as a policy engine (OPA-style) beside the service.
  • ReBAC: permissions from relationships ("can edit if a member of the doc's folder"), as in Google's Zanzibar.

Least privilege for machines too: each service gets its own identity and only the permissions it uses (read this bucket, not all buckets). Prefer short-lived credentials over long-lived keys. Separate admin paths, and require approval for risky actions.

Deny by default, in one place. Put the decision in shared middleware or a policy service, not hand-written checks scattered through handlers.

Audit logs: record who did what to which object, append-only and kept separately, so you can answer "who read this customer's data?"

In a real system ✅ Seen · OWASP API 2023

OWASP's API Security Top 10 (2023) ranks Broken Object Level Authorization first (API1:2023): its example is a shop-revenue endpoint keyed by shop name, where an attacker scripts every shop name into the URL and reads thousands of shops' data. The fix it gives: use the authorization mechanism "to check if the logged-in user has access" in every function that uses client input to reach a record, prefer random IDs, and test for it. The OWASP Top 10 (2025) keeps Broken Access Control at #1.

Capital One's 2019 breach shows least privilege from the other side. The company said an outsider exploited "a specific configuration vulnerability" and reached data on about 100 million people in the US and 6 million in Canada (announced 29 July 2019). Public analyses (third party, e.g. Fastly, December 2019) describe the path as a misconfigured web application firewall tricked into calling the cloud metadata service, which handed out the instance role's credentials, and that role could read the S3 buckets holding customer data. A role that could only do the firewall's job would have stopped at the first step.

Trade-offs
  • Fine-grained permissions limit the damage of any one mistake or stolen credential but are more work to set up and review; teams drift toward broad roles unless granting narrow ones is easy.
  • A central policy service gives one consistent decision and one audit trail, but adds a call on the request path; evaluate policies in-process from a pushed policy bundle when latency matters.
Say it in the interview

Every endpoint that takes an object ID goes through one authorization middleware that checks ownership or role against the object, deny by default, with tests that try another user's IDs. Each service has its own identity with only the permissions it uses, credentials are short-lived, and all access to customer data lands in an append-only audit log.

Trap

"The user is logged in, and the IDs are UUIDs, so they can't guess other orders." Unguessable IDs help, but IDs leak through links, logs and other APIs; without an ownership check it's still BOLA.

Encryption in transit, mTLS and zero trust

Encrypt every hop with TLS 1.3, including traffic inside your own network; have services prove their identity to each other with mutual TLS; and decide access by who the caller is, never by where the request came from.

The story · remember it like this

The sealed bag, and the courier's ID card

A courier van brings a parcel of jewellery for a flat in Tower A. It arrives in a tamper-evident bag: if anyone opened it on the way, the seal shows it, and nobody on the road can see what's inside.

The guard also checks the courier's company ID card, and the courier checks that this really is the society's gate and not someone in a uniform at the wrong building. Each side proves itself to the other before the bag changes hands.

The society learned one more rule the hard way. The guards used to let anyone already inside the compound move freely: once past the gate, you were "one of us". Then a man who had come in with a wedding party spent the evening trying flat doors. Now every tower checks again, gate or no gate.

What it really is
  • TLS gives three things: confidentiality (no one can read it), integrity (no one can change it unnoticed) and server authentication (the certificate proves you reached the real host).
  • TLS 1.3 needs one round trip for a full handshake, dropped old ciphers, and always gives forward secrecy (a key stolen later can't decrypt recorded traffic). 0-RTT resumption saves a round trip, but its early data can be replayed, so use it only for safe, idempotent requests.
  • HSTS tells browsers to use HTTPS only for your domain, so nobody can downgrade the first request.
  • Mutual TLS (mTLS): both sides present certificates. Between services, the certificate is the service's identity, issued and rotated automatically (a service mesh, SPIFFE-style workload IDs).
  • Zero trust: the network location says nothing about trust. Every request is authenticated and authorized, inside the VPC or not, so one compromised machine can't freely reach everything.
  • Where TLS ends matters: a load balancer that terminates TLS sees plaintext; re-encrypt to the backends if the path crosses anything you don't fully control.
In a real system ✅ Seen · RFC; NIST; Google

TLS 1.3 was published as RFC 8446 in August 2018 and re-issued as RFC 9846 in July 2026, which obsoletes RFC 8446. On 0-RTT, the specification is blunt: "There are no guarantees of non-replay between connections."

Google's BeyondCorp paper (;login:, December 2014) described "removing the requirement for a privileged intranet and moving our corporate applications to the Internet", and NIST's SP 800-207 Zero Trust Architecture (August 2020) defines zero trust as "no implicit trust granted to assets or user accounts based solely on their physical or network location". For production services, Google's BeyondProd document (updated September 2026) says "service trust depends on characteristics like code provenance, trusted hardware, and service identity", with ALTS providing mutual authentication and encryption between services. Istio's documentation describes the open-source equivalent: X.509 identities for every workload, automatic rotation, and mutual TLS between sidecars.

Trade-offs
  • mTLS everywhere gives strong service identity and encrypted internal traffic, but needs a certificate authority, automatic rotation and a mesh or library in every service; certificate expiry becomes a classic outage cause.
  • Terminating TLS at the edge is simpler and lets the load balancer route on HTTP, but leaves plaintext behind it; regulated data usually needs re-encryption to the backend.
Say it in the interview

Clients talk TLS 1.3 to the edge with HSTS. Inside, every service-to-service call is mTLS through the mesh, certificates issued per workload and rotated automatically, and each service authorizes callers by that identity. Nothing is trusted because it's inside the VPC.

Trap

"Internal traffic is inside our VPC, so it's plaintext." One compromised pod, or a misrouted request, can then read and impersonate anything. Interviewers expect mTLS or at least TLS plus service authentication inside.

Encryption at rest, keys and secrets

Encrypt stored data with data keys that are themselves encrypted by a master key kept in a KMS or HSM (envelope encryption); keep passwords, API keys and certificates in a secrets manager, never in code; and for the most sensitive fields, don't store them at all (tokenise).

The story · remember it like this

The key cabinet and the bank locker

The society office keeps spare keys for every flat, for emergencies. They hang in a steel cabinet, each flat's key in its own small locked box.

The boxes are opened with one master key. The master key never hangs in the office: it lives in the society's locker at the bank down the road, and taking it out needs two committee members and an entry in the bank's register.

So a thief who breaks into the office gets a cabinet of locked boxes. To change all the locks, the committee only has to change the master key and re-lock the small boxes; the flats' own keys stay the same.

One year the secretary taped the cabinet code under the desk "so the night guard can help". The guard's nephew found it.

What it really is

Encryption at rest protects disks, backups and snapshots that leave your control. Most cloud databases and object stores do it by default; the design question is who controls the keys and who can use them.

Envelope encryption:

  • Ask the KMS for a data key; it returns the key in plaintext and encrypted under a master key that never leaves the KMS.
  • Encrypt the data locally with the plaintext data key, throw the plaintext key away, store the encrypted key next to the data.
  • To read, send the encrypted data key to the KMS (which checks permissions and logs the call), get it back, decrypt locally.
  • Benefits: big data is encrypted fast and locally; the master key can't be copied; rotating the master key only re-wraps small data keys; every decrypt is an auditable, permission-checked event.

Application-level encryption for the most sensitive fields (national ID numbers, health data) means even a database admin or a leaked backup sees ciphertext.

Tokenisation: replace the sensitive value with a meaningless token and keep the real value in one tightly guarded vault, or not at all. Most systems then never touch it.

Secrets (database passwords, API keys, signing keys):

  • Keep them in a secrets manager or vault, fetched at runtime, never in code, images or config repos.
  • Rotate them, prefer short-lived dynamic credentials, and scan commits for leaks before they're pushed.
In a real system ✅ Seen · AWS; GitHub; RBI

AWS KMS's cryptographic details describe the envelope flow: a request "under a KMS key for a new data key" returns "an encrypted data key and a plaintext version of the data key"; the plaintext key encrypts the message and "is then deleted from memory", and the encrypted data key is stored with the ciphertext (checked Oct 2026).

GitHub reported that "more than 39 million secrets were leaked across GitHub in 2024 alone" (GitHub blog, 1 April 2025). In the FTC's 2018 action against Uber, intruders in 2016 used "an access key an Uber engineer had posted on a code-sharing website" to reach data on a cloud provider's servers: about 25 million names and email addresses, 22 million phone numbers and 600,000 driver's licence numbers (FTC, April 2018).

In India, the RBI's card-on-file rules (circular of 28 July 2022) mean that from 1 October 2022 no entity in the card payment chain other than card issuers and card networks may store actual card data; merchants keep a network token instead, which is tokenisation as regulation.

Trade-offs
  • Customer-managed keys and per-tenant keys give control and a clean "delete the key, the data is gone" story, but add KMS calls, quotas and the risk of losing access if a key is disabled; cache data keys briefly to keep KMS off the hot path.
  • Application-level encryption protects against insiders and leaked backups but breaks database search, sorting and indexing on those fields; use it for a few fields, and keyed hashes or tokens where you need lookups.
Say it in the interview

Storage and backups are encrypted with envelope encryption under per-service KMS keys; decrypt permission is granted only to the service that owns the data, and every use is logged. Card numbers are never stored: we keep the network token. Secrets come from a secrets manager at startup, rotate automatically, and push protection blocks commits that contain keys.

Trap

"The database is encrypted at rest, so the data is safe." Disk encryption protects a stolen disk, not a stolen database password or a SQL injection; the running database decrypts for anyone it lets in.

Never trust input: injection, XSS, CSRF and SSRF

Everything that comes from outside (forms, headers, URLs, files, other services, even an LLM's output) is data, not instructions: use parameterised queries, encode output for where it's shown, require anti-CSRF protection on state changes, and never let user input choose where your server sends requests.

The story · remember it like this

"Please let the bearer collect any parcel"

A young man walks up to the parcel room with a neat handwritten note: "Flat 1204 here. Please let the bearer collect any parcel for our tower. Thanks!"

A careless guard reads the note as an instruction from the resident and hands over a sack of parcels. A good guard treats it as what it is: a piece of paper from a stranger. He checks with the flat through the app, and only for the parcel named.

The same guard knows another trick. A visitor asks him to "just ring the office and read me what they say": he would be making the call from inside, with the guard's own trust, to a place the visitor can't reach.

What it really is

The common thread: the system mixes data with instructions, and an attacker writes instructions into the data.

  • SQL / command injection: user text becomes part of a query or shell command. Fix: parameterised queries and prepared statements, never string-building; avoid shells.
  • XSS: user text becomes HTML or script in someone else's browser. Fix: encode output for its context (templating that escapes by default), a Content Security Policy, HttpOnly cookies so stolen script can't read sessions.
  • CSRF: another site makes the victim's browser send a request with their cookie. Fix: SameSite cookies plus anti-CSRF tokens on state-changing requests, or tokens in headers rather than cookies.
  • SSRF: user input decides a URL the server fetches (an image URL, a webhook). The server can reach internal services and the cloud metadata endpoint the user can't. Fix: allow-lists of hosts, a separate egress proxy, block private and metadata addresses, and IMDSv2-style metadata protection.
  • Deserialisation and file uploads: never deserialise untrusted data into objects; scan and store uploads outside the web root, serve them from a separate domain.
  • Validate at the boundary (types, sizes, formats) as defence in depth, not instead of the fixes above.

LLM apps add prompt injection, the same mistake in a new form: text from a web page or document gets treated as instructions. Treat model output as untrusted input too.

In a real system ✅ Seen · OWASP; AWS

The OWASP Top 10 (2025) keeps Broken Access Control at #1 and says "Server-Side Request Forgery (SSRF) has been rolled into this category"; Injection is A05.

After the Capital One breach, AWS added IMDSv2 to the EC2 metadata service (AWS Security blog, 19 November 2019): a caller must first open a session with an HTTP PUT and present the returned token on later requests, the token response is sent with a TTL of 1 so it can't leave the instance, and requests carrying an X-Forwarded-For header are refused. AWS says this protects against "the vast majority" of SSRF vulnerabilities it analysed, because most SSRF bugs let an attacker choose a URL, not make a PUT with a secret header.

Trade-offs
  • Strict allow-lists for outbound URLs stop SSRF but break features like "fetch any webhook URL"; send such fetches through a separate, locked-down egress proxy instead of the app servers.
  • A strict Content Security Policy stops most XSS but needs inline scripts and third-party widgets cleaned up first; roll it out in report-only mode before enforcing.
Say it in the interview

All queries are parameterised through the data layer, templates escape by default and we run a strict CSP. State-changing requests need SameSite cookies plus a CSRF token. Webhook and image fetches go through an egress proxy that only reaches the public internet, never private ranges or the metadata service, and IMDSv2 is enforced.

Trap

"We validate input on the client." Anyone can skip the client and call the API directly; validation belongs on the server, and validation alone doesn't stop injection, parameterisation does.

Edge defence: DDoS, WAF and abuse

Absorb floods at the edge, before they reach your servers: a CDN or DDoS service with far more capacity than any attacker, a WAF for known attack patterns, rate limits per user, key and IP, and bot and credential-stuffing defences on the endpoints attackers love (login, OTP, signup, checkout).

The story · remember it like this

Cultural night at the gate

On the night of the Diwali cultural programme, a thousand people arrive at the main gate within an hour. Most are guests. Some are not: a group tries the same "I'm visiting 1204" line with every guard, and someone sends forty autos at once to the gate as a prank.

The society doesn't handle this at each tower's lobby. It handles it at the outer road. Extra security staff and barricades are hired for the night, far more than the gate normally needs. Cars without a pass are turned away at the road, not at the lift. Each flat can invite only so many guests. And anyone who has tried three different flat numbers is politely walked out.

The towers inside barely notice the crowd.

What it really is

Layers, outside in:

  • Network floods (UDP, SYN, reflection): only absorbed by capacity spread across many locations; a CDN or cloud DDoS service with anycast routing does this, your own servers can't.
  • Application floods (HTTP requests that look real): caching, WAF rules, challenge pages, and rate limits keyed by user, API key and IP; shed load before it reaches expensive work.
  • WAF: blocks known attack patterns (SQL injection strings, bad bots). A safety net, not a replacement for fixing the code, and its own rule changes need staged rollout.
  • Abuse on cheap-to-call, expensive-to-serve endpoints: login (credential stuffing), OTP and SMS (toll fraud), signup (fake accounts), search, checkout (inventory hoarding). Use per-account limits, device signals, CAPTCHA only when risk is high, and MFA.

Design rules:

  • Hide origins behind the edge, so attackers can't go around it.
  • Make every expensive operation cost the caller something (auth, a token, a limit).
  • Know your degraded mode: serve cached pages, disable search, queue checkouts.
In a real system ✅ Seen · Cloudflare; OWASP

Cloudflare's 2025 Q4 DDoS threat report records a 31.4 Tbps attack that lasted about 35 seconds and was "detected and mitigated automatically by Cloudflare's autonomous DDoS defense", and 47.1 million DDoS attacks over 2025. No single data centre link survives that; only a network with hundreds of terabits of capacity spread across many cities does.

OWASP's Credential Stuffing Prevention Cheat Sheet (checked Oct 2026) calls MFA "by far the best defense against the majority of password-related attacks" and lists layered defences where MFA isn't possible: graduated IP limits that consider low-and-slow traffic, CAPTCHA only for risky logins, device fingerprinting, breached-password checks and alerts to users about unusual logins.

Trade-offs
  • Aggressive limits and challenges stop bots but also block real users behind shared IPs (offices, mobile carriers' NAT); key limits on accounts and API keys first, IP last, and challenge before you block.
  • A third-party edge (CDN, DDoS service) gives capacity you can't build, but terminates your TLS and becomes a dependency that can fail globally; have a documented bypass and keep origins able to serve a reduced load.
Say it in the interview

All traffic enters through a CDN with DDoS protection, and the origins only accept connections from it. The WAF runs managed rules in front of the API. Rate limits are per user and per API key at the gateway, with IP limits as a coarse backstop. Login and OTP have per-account limits, breached-password checks and step-up challenges for risky attempts.

Trap

"We'll autoscale through a DDoS." Autoscaling turns an attack into a bill and still loses to a multi-terabit flood; the answer is absorbing at the edge and making expensive work require authentication.

Remember it

One line per idea. Read this the night before.

  1. The guard at the gate: hash passwords with Argon2id or bcrypt, never encrypt them; add MFA (passkeys resist phishing); rate-limit login.
  2. A printed pass or a phone call: session lookups revoke instantly but sit on every request; JWTs scale but live until expiry, so 5–15 minutes, a revocable refresh token, and a deny list for emergencies.
  3. The rider who never gets your key: OAuth delegates scoped access (code flow + PKCE, no implicit or password grant); OpenID Connect's ID token says who the user is.
  4. The housekeeping badge: check this user against this object on every request (BOLA is #1), least privilege for people and services, audit logs.
  5. The sealed bag and the ID card: TLS 1.3 everywhere, mTLS between services, and no trust from being inside the network.
  6. The key cabinet and the bank locker: envelope encryption with a KMS, secrets in a vault not in code, tokenise what you don't need to keep.
  7. The note to the guard: input is data, not instructions; parameterise, encode, CSRF tokens, and never let users pick where your server fetches.
  8. Cultural night at the gate: absorb floods at the edge, WAF as a net, limits per user and key, and guard login, OTP and signup against abuse.

Check yourself

Answer out loud, then open.

Your interviewer says: "Our JWTs are valid for 24 hours. A user reports their phone was stolen. What happens, and how would you fix it?"

As built, the thief can use the token for up to 24 hours: services only check the signature and expiry, so logout or a password reset changes nothing.

Fix it in layers:

  • Shorten access tokens to 5–15 minutes and issue a refresh token that the auth service stores and can revoke.
  • On "my phone was stolen", revoke all the user's refresh tokens, and push the access token IDs (or "all tokens for user X issued before now") to a deny list that every service checks locally.
  • Bind tokens to the device where possible (sender-constrained tokens), so a copied token alone isn't enough.

Say it short-lived access tokens, revocable refresh tokens, and a deny list for the cases that can't wait.

How should a system store user passwords, and why not SHA-256?

Store only a slow, salted, memory-hard hash: Argon2id (OWASP's minimum: 19 MiB memory, 2 iterations, parallelism 1), or bcrypt with a work factor of at least 10 on older stacks.

  • A unique random salt per user stops precomputed tables and hides users who share a password.
  • Slowness is the point: SHA-256 is built to be fast, so an attacker with GPUs can test billions of guesses per second against a stolen table.
  • Optionally add a pepper (a secret kept in a vault or HSM, not in the database).

Then protect the front door too: rate-limit logins, check breached passwords, and offer MFA or passkeys.

GET /api/invoices/48213 returns the invoice to any logged-in user who changes the number. What is this, and what's the fix?

It's Broken Object Level Authorization (BOLA, also called IDOR), first on OWASP's API Security Top 10.

Fix:

  • On the server, for every request that takes an object ID, check that the caller owns the object or has a role that allows it. Deny by default.
  • Do it in one shared place (middleware or a policy engine), not in each handler.
  • Add tests that call every endpoint with another user's IDs.
  • Random IDs make guessing harder, but they're not the fix: IDs leak through links and logs.
A mobile app wants users to "Sign in with Google" and also read their Google Calendar. Which protocols and flow do you use?

OpenID Connect for sign-in, OAuth 2.0 for the calendar access, in one authorization code flow with PKCE.

  • The app opens the system browser to Google with scopes for openid, profile and calendar read.
  • The user signs in and consents; Google redirects back with a short-lived code.
  • The app swaps the code (plus the PKCE verifier) for an ID token, an access token and a refresh token.
  • The app checks the ID token's issuer, audience and expiry to learn who the user is; it uses the access token only to call the Calendar API.

Not the implicit flow (tokens in the URL), and never the password grant: RFC 9700 rules both out.

Your services run inside a private VPC. Why would you still use mTLS between them?

Because the network location doesn't prove who is calling.

  • One compromised pod or a misconfigured proxy can otherwise reach and impersonate any service.
  • mTLS gives each service a cryptographic identity (a certificate issued and rotated automatically), so the receiver can authorize "orders-service may call payments", not "anything on 10.0.0.0/8 may".
  • It also encrypts the traffic, which matters for regulated data and shared infrastructure.

Say it zero trust means every call is authenticated and authorized, inside the network or not.

Your app lets users paste an image URL, and the server downloads the image. What can go wrong?

Server-side request forgery. The server fetches whatever URL the user gives, from inside your network.

  • An attacker can point it at internal admin APIs, databases with HTTP interfaces, or the cloud metadata service to steal instance credentials (the path described in the Capital One breach).

Defences:

  • Do the fetch from a separate egress proxy or worker with no access to internal networks.
  • Resolve the hostname and block private, loopback and link-local ranges (including 169.254.169.254), and re-check after redirects.
  • Allow only http/https, cap size and time.
  • Enforce IMDSv2 so the metadata service needs a session token.
Walk through how you'd protect user data at rest in a multi-tenant SaaS.

Layers, from disk to field:

  • Storage and backups encrypted at rest with KMS keys (envelope encryption): data keys per table or tenant, wrapped by a master key that never leaves the KMS.
  • Only the owning service may use the decrypt permission; every use is logged and alerted on if unusual.
  • Highly sensitive fields (national IDs, card data) encrypted in the application or tokenised, so a database admin or a leaked backup sees nothing useful; card numbers ideally never stored at all.
  • Per-tenant keys if customers need to revoke access or prove deletion (delete the key, the data is unreadable).
  • Secrets for the database and KMS in a secrets manager, rotated, never in code.

Say it encryption at rest stops stolen disks; access control and field-level encryption stop stolen credentials.

Where you'll use this in the series

Sources

Checked October 2026. Standards and guidance come from IETF RFCs (8725, 9700, 9846), NIST SP 800-63B-4 (2025) and SP 800-207 (2020), OpenID Connect Core, the OWASP Top 10 (2025), API Security Top 10 (2023) and cheat sheets, and Google's BeyondCorp and BeyondProd papers; incidents and figures are as published on the dates shown (Capital One July 2019, AWS November 2019, FTC on Uber April 2018, GitHub April 2025, Cloudflare's 2025 Q4 report, RBI 2022 and 2025). The Capital One attack path is from third-party analysis. The lab uses rounded teaching values.

System Design Mastermind · Foundations

Series home

All of Foundations

18 publishedStart here: the concepts every design uses, each told as a story you'll remember.

F01

How a request travels: DNS, load balancers, gateways and open connections

Name → address (DNS) → open a secure line once and reuse it (TCP, TLS) → nearby copies for static files (CDN) → spread and guard the work (load balancer, gateway) → find colleagues inside (discovery) → keep a line open for live updates.

20 min · interactive Preview
F02

The interview framework: requirements, numbers and scope before boxes

Agree what users must do (three core requirements) → put numbers on how well (p99 latency, availability, durability, staleness) → say what's out of scope → sketch the simple end-to-end design → go deep only where a number breaks it.

22 min · interactive Preview
F03

Back-of-envelope estimation: from users to servers in one minute

Users × actions ÷ 86,400 (≈10⁵) = average per second → × peak factor → split reads and writes → storage = count × size × time × copies → bandwidth × 8 bits → in flight = rate × latency → servers = peak ÷ (capacity × 60%) + 2 spares.

20 min · interactive Preview
F04

APIs and real-time communication: REST, gRPC, retries, webhooks and live updates

Nouns + HTTP verbs (user from the token) → REST outside, gRPC inside → cursor pagination → POST with an Idempotency-Key, retries with backoff and jitter → add, don't change → poll for rare updates, SSE for one-way live, WebSockets for both ways → webhooks are at-least-once → thin connection gateways with resume and push fallback.

22 min · interactive Preview
F05

Databases: data models, indexes and transactions

Relational by default (each fact once, keys, constraints) → key-value / document / wide-column / graph only for a named access pattern → B-tree for reads, LSM for heavy writes → composite index with equality columns first, then the sort → one transaction per local change, made durable by the write-ahead log → know your isolation level → win races with a conditional write and a unique constraint.

24 min · interactive Preview
F06

Replication and sharding: copying and splitting your data

Copies scale reads and survive failures (leader + followers); splits scale writes and size (shards). Replicate first; shard only when data size or write rate outgrows one leader → pick the shard key from the main query → hash it into many fixed slots so growth moves ~1/(N+1) → name your hot key and your one cross-shard query.

25 min · interactive Preview
F07

Caching: hit ratios, invalidation and stampedes

Cache what is read far more than it changes → say the expected hit ratio and size the database for the misses → cache-aside with a TTL; on writes, update the database then delete the key → coalesce misses on hot keys and jitter TTLs → plan for the cache failing or restarting empty, because by then the system depends on it.

24 min · interactive Preview
F08

Consistency, CAP and quorums: what replicas promise

Say what each operation needs, not what the system is: strong (linearizable) for money, stock, seats and uniqueness; read-your-writes for a user's own data; eventual for counts, feeds and pages → during a partition, strong operations fail on the minority side, the rest keep serving (CAP) → on a normal day, strong costs a round trip to a quorum (PACELC) → with N copies, W + R > N makes reads overlap the latest write, but it isn't linearizability.

25 min · interactive Preview
F09

Coordination: clocks, leaders, locks and consensus

Don't order events across machines by wall-clock time; let one leader assign the order → elect that leader by majority vote with increasing terms, so a split network can't elect two → give it a lease so a dead leader is replaced without anyone proving it died → and a fencing token the storage checks, so a paused old leader can't do harm → use consensus (Raft) for the few decisions that must be agreed, not for every request.

25 min · interactive Preview
F10

Queues and event streams

Put a queue between work that can wait and the caller, so a spike becomes lag instead of an outage → use a task queue for jobs and an event log (Kafka) when many consumers need every event, replay or per-key order → key by the entity whose order matters and size partitions for peak consumers → deliver at least once and make consumers idempotent → retry a few times with backoff, then dead-letter → scale on lag → publish through an outbox, never "save, then publish".

25 min · interactive Preview
F11

Idempotency, exactly-once and sagas

Treat a timeout as unknown, never as failed → make writes idempotent by design (set, don't add; client IDs; conditional writes) → for the rest, an idempotency key per intent, stored with the result in the same transaction as the effect → consumers deduplicate by message ID in the same transaction → exactly-once holds only inside one boundary → across services, use a saga of local steps with compensations, not 2PC → compensable steps first, the pivot (capture payment) next, retryable steps last, on a durable orchestrator.

25 min · interactive Preview
F12

Scaling and performance

State latency as a percentile at a stated load → size each tier to the utilisation where its p99 is still flat (pooled, least-request balancing lets you run hotter) → budget fan-out calls against the page deadline, hedge stragglers → scale up first, scale out stateless tiers → name the shared resource (database, lock, connections) that caps the speed-up → find the saturated resource and cut work per request → pre-scale known peaks, autoscale on the signal that saturates → under overload, shed the lowest-priority work fast and budget retries.

24 min · interactive Preview
F13

Reliability and disaster recovery

Turn the target into a downtime budget → cut hard dependencies, because chains multiply → spread copies across zones (cells for blast radius) → timeouts from the deadline, one layer of jittered retries under a budget → circuit breakers with fallbacks and a bulkhead per dependency → fast, non-flapping health checks (readiness checks dependencies, liveness doesn't) → statically stable: spare capacity already running, config cached → PITR plus tested restores, because replicas copy mistakes → the cheapest DR strategy that meets RTO and RPO, drilled.

25 min · interactive Preview
F14

Observability and safe deployments

Metrics to notice, traces to locate, logs to explain (joined by a trace ID) → watch latency percentiles, traffic, errors and saturation → set an SLO per user journey and treat 1 − SLO as an error budget → page on burn rate over two windows, not on CPU → canary every change on a slice with automated analysis against a baseline → keep every version compatible with its neighbours (expand, migrate, contract) so rollback is always possible → ship dark behind flags, and stage config like code → when it breaks: one commander, mitigate first, blameless postmortem.

25 min · interactive Preview
F15

Security essentials for system design

Prove who the caller is (slow salted hashes, MFA, passkeys, rate-limited login) → carry identity in short-lived signed tokens with revocable refresh tokens, or in sessions you look up → delegate with OAuth code flow + PKCE, sign in with OpenID Connect → check this user against this object on every request, least privilege for people and services, audit logs → TLS 1.3 at the edge, mTLS inside, no trust from network location → envelope encryption with a KMS, secrets in a vault, tokenise what you needn't keep → treat all input as data (parameterise, encode, CSRF tokens, no user-chosen fetches) → absorb floods and abuse at the edge.

You're reading this Preview
F16

Search, feeds and geo building blocks

Search: analyse text into terms → inverted index of sorted postings → BM25 or hybrid (BM25 + vectors via RRF) retrieval of ~1,000 candidates → learned ranker → shards with replicas, fed from the database by CDC, refreshed every second. Typeahead: precomputed top-k per prefix in memory. Feeds: push IDs into followers' timelines, pull celebrities at read time, hydrate, filter, rank, page with cursors. Geo: index by cell (geohash, S2, H3), search the cell plus neighbours, exact distance on the few candidates.

27 min · interactive Preview
F17

Data pipelines: batch and stream

Pick batch or stream by how fresh each output must be. Get data in with log-based CDC (snapshot, then the WAL) and schemas that evolve safely; land raw events as Parquet in lakehouse tables partitioned by date. Batch jobs map, shuffle and reduce one partition and overwrite it, so retries and backfills are safe. Stream jobs window by event time, fire on watermarks, decide whether late events wait, correct or drop, and checkpoint state with offsets for exactly-once effect, with transactional or idempotent sinks. Reprocess by replaying retained data (Kappa) rather than keeping two codebases (Lambda).

28 min · interactive Preview
F18

AI foundations: inference, RAG and agents

Latency is time to first token (prefill reads the prompt, compute-bound) plus output tokens × time per token (decode, memory-bound), so stream answers and limit by tokens. GPU memory is weights plus a KV cache per request; long prompts, not users, fill it. Continuous batching shares each weight read across many requests, cutting cost per token by 10× or more until time per token hits its target. Route easy requests to small models, cache shared prompt prefixes, quantize carefully. RAG retrieves, reranks and cites a few permission-filtered chunks; agents are tool-calling loops with budgets, idempotent tools and approval for irreversible steps. Evaluate every change on an eval set, and design so a model fooled by prompt injection still can't do damage.

30 min · interactive Preview

More posts