Security in System Design

The defenses every serious system needs — authentication, authorization, data protection, and the common attacks you must design against.

Security in 30 seconds

  • AuthN vs AuthZ: authentication is who are you; authorization is what are you allowed to do. Different problems, different tools.
  • Defense in depth: no single wall is enough — layer protections so one failure doesn't breach everything.
  • Least privilege: give every user, service, and token the minimum access it needs, and nothing more.
  • Protect data in transit (TLS) and at rest (encryption + key management).
  • Never trust input: validate and encode everything to stop injection and XSS; never build queries by string concatenation.
  • Secrets are not config: keep keys and passwords out of code and logs; store them in a secret manager and rotate them.
  • Assume breach: log, monitor, and design so a compromised component has a small blast radius.

Security is a property, not a feature

You can't bolt security on at the end like a coat of paint. It's a property that has to be designed into every layer — the connection, the identity, the permissions, the data, the inputs, the secrets. The useful mental model is defense in depth: assume any single protection will eventually fail, and layer defenses so that one failure doesn't hand an attacker the whole system. A castle doesn't rely only on its outer wall — it has a moat, walls, a gatehouse, and a keep. Your system should too.

Authentication vs authorization — don't conflate them

These two words sound alike and get mixed up constantly, but they answer completely different questions:

Authentication (AuthN)Authorization (AuthZ)
QuestionWho are you?What are you allowed to do?
ProvesIdentity (a valid login, token, or key).Permission (this identity may access this resource).
Typical toolsPasswords + MFA, OAuth/OIDC, session tokens, JWTs.Roles (RBAC), attributes (ABAC), access-control lists.
Failure looks likeAn impostor logs in as someone else.A real user reaches data they shouldn't (privilege escalation).

A system authenticates once (you log in) and authorizes on every request (can this identity do this action on this resource?). Conflating them is a classic source of bugs — a logged-in user is not the same as an allowed user.

Authenticate once, authorize on every request (python)
def handle(request):
    # 1. AuthN: who are you? Verify the token's signature and expiry.
    user = verify_token(request.headers.get("Authorization"))
    if user is None:
        return http_401()                    # not authenticated

    # 2. AuthZ: are YOU allowed to touch THIS resource? Check every time.
    doc = load(request.path_param("doc_id"))
    if doc.owner_id != user.id and "admin" not in user.roles:
        return http_403()                    # authenticated but not allowed

    return serve(doc)

# The bug to avoid: treating 'logged in' as 'allowed'. AuthN != AuthZ.

Tokens and sessions: how identity travels

HTTP is stateless, so after you log in the system needs a way to recognize you on the next request without re-checking your password. Two common approaches:

  • Session cookie: the server stores session state and hands the browser an opaque session ID in a cookie. Simple, easy to revoke (delete the server-side session), but requires shared session storage across servers.
  • JWT (JSON Web Token): a signed token carrying the user's claims (id, roles, expiry). Stateless — any server can verify the signature without a lookup — but harder to revoke before it expires. Keep lifetimes short and pair with a refresh token.
  • OAuth 2.0 / OIDC: the standard for 'log in with Google/GitHub' and for delegating access — you authorize a third party without handing over your password.
  • Cookie flags matter: mark auth cookies HttpOnly (JS can't read them, blunting XSS theft), Secure (HTTPS only), and SameSite (blunts CSRF).

Least privilege, everywhere

Give every actor — a user, a service account, a token, a database login — the minimum access it needs to do its job, and nothing more. When (not if) something is compromised, least privilege is what keeps the blast radius small:

  • A read-only reporting service gets a read-only database credential — a leak can't delete data.
  • A token scoped to one bucket can't touch the rest of your storage.
  • An admin action requires an admin role checked server-side, never a hidden button the client simply doesn't render.
  • Service-to-service calls use narrowly scoped credentials, so a breached microservice can't impersonate the whole system.

The attacks you must design against

A handful of attack classes account for a huge share of real breaches. You don't need to memorize an encyclopedia, but you must recognize these and know the standard defense for each:

AttackWhat it isThe standard defense
SQL / command injectionHostile input treated as code (a query, a shell command).Parameterized queries / prepared statements; never concatenate input into commands.
XSS (cross-site scripting)Attacker's script runs in another user's browser.Encode/escape all output; a Content-Security-Policy; HttpOnly cookies.
CSRF (cross-site request forgery)A victim's browser is tricked into making an authenticated request.CSRF tokens; SameSite cookies; check the Origin header.
Broken access controlA user reaches data/actions they shouldn't (e.g. changing an id in the URL).Authorize every request server-side against the real owner/role.
Credential stuffing / brute forceReusing leaked passwords or guessing at scale.MFA, rate limiting, lockouts, password hashing (bcrypt/argon2).
DDoSOverwhelming the system with traffic.Rate limiting, CDN absorption, autoscaling, upstream scrubbing.

Never trust input

The single most important habit: treat every input as hostile until proven safe — request bodies, query params, headers, file uploads, and even data coming back from other services. Two defenses carry most of the weight:

  • Validate on the way in: reject anything that doesn't match the expected shape, type, length, and range. Allow-list what's valid rather than trying to block-list what's bad.
  • Parameterize, never concatenate: let the database (or shell, or template engine) treat input as data, never as code. This single rule eliminates the entire injection class.
Injection: the vulnerable pattern vs the parameterized fix (python)
# VULNERABLE: input is concatenated straight into the query as code.
# A value of  '  OR 1=1 --  turns this into 'return every row'.
query = "SELECT * FROM users WHERE email = '" + user_input + "'"   # NEVER
db.execute(query)

# SAFE: the input is bound as a parameter — the DB treats it as pure data,
# never as part of the SQL. Injection becomes impossible here.
db.execute("SELECT * FROM users WHERE email = ?", [user_input])    # ALWAYS
XSS: escape output so data can't become script (javascript)
// VULNERABLE: untrusted text injected as HTML runs any <script> in it.
el.innerHTML = `Hello, ${userName}`;        // NEVER with untrusted input

// SAFE: assign as text, so the browser renders it as characters, not markup.
el.textContent = `Hello, ${userName}`;      // ALWAYS, or escape explicitly

// Plus a Content-Security-Policy header as a second layer of defense:
//   Content-Security-Policy: default-src 'self'; script-src 'self'
// so even an injected inline script is refused by the browser.

Protecting data: in transit and at rest

Data needs protection in two states, and they use different tools:

  • In transit: encrypt everything on the wire with TLS/HTTPS (see HTTPS, TLS & TCP) — not just the public edge, but internal service-to-service calls in a zero-trust design.
  • At rest: encrypt stored data (disk/database/backup encryption) so a stolen drive or leaked backup is useless without the keys. Manage those keys in a KMS, separate from the data they protect.
  • Hash, don't encrypt, passwords: store passwords with a slow, salted hash (bcrypt, scrypt, argon2) so a database leak doesn't reveal them. You never need to decrypt a password — only to compare hashes.
  • Minimize and classify: the safest data is the data you never collect. Know what sensitive data you hold (PII, payment, health) and treat it with extra care.
Passwords: salted slow hash, compared in constant time (python)
# Store a salted, slow hash — never the password, never a plain hash.
def set_password(user, plain):
    user.pw_hash = bcrypt.hashpw(plain.encode(), bcrypt.gensalt())  # salted + slow

def check_password(user, plain):
    # bcrypt compares in constant time, so timing can't leak the answer.
    return bcrypt.checkpw(plain.encode(), user.pw_hash)

# Why slow on purpose: a fast hash lets an attacker try billions of guesses
# against a stolen database. bcrypt/argon2 make each guess deliberately costly.

The reverse proxy / gateway as a security chokepoint

A huge amount of security is best applied at a single chokepoint rather than scattered across every service. The API gateway or reverse proxy at your edge (see API gateway) is the natural place to terminate TLS, authenticate requests, enforce rate limits, block known-bad traffic (a WAF), and add security headers — so every downstream service inherits the protection by default instead of re-implementing it.

Defense in depth — each layer catches what the one before it missed.

Security is the discipline of assuming things will go wrong and designing so that when they do, the damage is contained. It's woven through every layer — connection, identity, permission, data, input, secrets — and it's judged by its weakest link, not its strongest.

Why it matters

  • A single breach can end user trust, trigger legal and financial fallout, and undo years of work overnight.
  • The cheapest, most effective security is designed in early — retrofitting it after an incident is painful and incomplete.
  • Most real breaches come from a handful of well-understood mistakes (leaked secrets, injection, broken access control) — which means they're largely preventable.

If ignored

  • Leaked credentials or an injection flaw hands an attacker the keys to your data.
  • Broken access control lets ordinary users read or change other people's data by editing an id.
  • Plaintext secrets, unencrypted data, or missing TLS turn a minor slip into a full breach.

Where it fits

  • Spans every layer: TLS at the transport, auth at the edge, authorization in each service, encryption at the data store.
  • Concentrates many controls at the gateway/reverse-proxy chokepoint for consistency.
  • Is a continuous practice — monitoring, rotation, and patching — not a one-time setup.

Related topics

  • HTTPS, TLS & TCP: the 'data in transit' foundation of security
  • Rate limiting: the first line against brute force and DDoS
  • API gateway: the chokepoint where auth, TLS, and WAF rules concentrate
  • Idempotency: safe retries are part of resilient, tamper-resistant APIs

Interview lens

Questions it unlocks

  • What's the difference between authentication and authorization?
  • How do you store user passwords safely?
  • How would you prevent SQL injection and XSS?
  • How do you keep secrets like API keys out of harm's way?

60-second answer

I design security in layers — defense in depth — assuming any single control can fail. Authentication proves who you are (passwords plus MFA, OAuth/OIDC, signed tokens); authorization, checked on every request server-side, decides what that identity may do, and I never treat 'logged in' as 'allowed'. I protect data in transit with TLS and at rest with encryption and a KMS, and I store passwords as salted slow hashes like bcrypt, never reversibly. I treat all input as hostile: parameterized queries kill SQL injection, output encoding plus a CSP blunt XSS, and SameSite/CSRF tokens handle forgery. Secrets live in a secret manager, scoped to least privilege and rotated, never in code or logs. I concentrate controls at the gateway — TLS termination, auth, rate limiting, a WAF — so every service inherits them, and I assume breach: log, monitor, and keep each component's blast radius small.

Common traps

  • Confusing authentication with authorization, or authorizing only on login instead of every request.
  • Building queries by string concatenation, opening the door to injection.
  • Encrypting passwords (reversible) instead of hashing them with a slow, salted algorithm.
  • Committing API keys or secrets to source control or printing them in logs.
  • Relying on the client to hide an action (not rendering a button) instead of enforcing access server-side.

Search topics

↑↓ to move · Enter to open · Esc to close