System Design Concepts

No fluff — visual, concise, interview-ready

🔒 3 · SECURITY

Authentication

Verifying identity — "Who are you?" — the gateway to every secure system

Authentication Methods — From Simple to Zero-Trust
Low Security High Security Basic Auth base64(user:pass) in Authorization header ⚠ only over HTTPS Use: internal/dev APIs API Key X-API-Key header scoped per service rotate regularly Use: S2S, third-party APIs JWT (Bearer) signed token (RS256/ES256) stateless verification short-lived (15min) Use: APIs, microservices OAuth 2.0 + OIDC delegated authorization "Sign in with Google" PKCE for public clients Use: SSO, social login mTLS + SPIFFE mutual certificates workload identity zero-trust, auto-rotate Use: service mesh JWT Structure: header.payload.signature Header: {"alg":"RS256","typ":"JWT"} · Payload: {"sub":"user123","exp":1700000000,"role":"admin","iss":"auth.example.com"} Signature: RSASHA256(base64url(header) + "." + base64url(payload), privateKey) HS256 = shared secret (single service) RS256/ES256 = asymmetric (microservices, public key verifies) ⚠ Never store JWT in localStorage (XSS vulnerable) — use httpOnly secure cookie
MethodMechanismStateless?Best ForSecurity Level
Basic Authbase64(user:pass) in headerYesInternal APIs, dev/testLow — credentials in every request
API KeyX-API-Key header or query paramYesService-to-service, third-partyMedium — no expiry by default
Session CookieServer-side session store + cookie IDNo (stateful)Traditional web appsMedium — CSRF risk, server state
JWT (Bearer)Signed token with claimsYesAPIs, microservices, mobileHigh — self-contained, verifiable
OAuth 2.0 + OIDCDelegated auth via authorization serverYes (token-based)SSO, social login, third-party accessHigh — industry standard
mTLSMutual X.509 certificatesYesService mesh, zero-trustHighest — cryptographic identity
Passkeys / WebAuthnFIDO2 public key credentialYesPasswordless user loginHighest — phishing-resistant
OAuth 2.0 Flows — Choosing the Right Grant Type
FlowClient TypeUse CaseSecurity
Authorization Code + PKCEPublic (SPA, mobile, CLI)User login, "Sign in with Google"Most secure — no client secret exposed
Client CredentialsConfidential (backend service)Machine-to-machine, no user contextHigh — client_id + client_secret
Device CodeInput-constrained (TV, IoT)User authorizes on separate deviceHigh — out-of-band verification
Refresh TokenAnyGet new access token without re-loginRotate on use, bind to device
ImplicitDEPRECATEDInsecure — token in URL fragment
Authentication Best Practices

Token Security

  • Access token: short-lived (15 min), in memory
  • Refresh token: longer (7d), httpOnly cookie, rotate on use
  • Storage: httpOnly + Secure + SameSite=Strict cookie
  • Never: localStorage (XSS), URL params (logs)
  • Revocation: token blocklist or short expiry

Multi-Factor Auth (MFA)

  • TOTP: Google Authenticator, Authy (6-digit code)
  • WebAuthn/Passkeys: biometric + device (phishing-proof)
  • SMS: weakest — SIM swap attacks
  • Push notification: Duo, Microsoft Authenticator
  • Hardware key: YubiKey (FIDO2) — strongest
Identity Providers: Auth0 — universal login, social + enterprise SSO. Keycloak — open-source, self-hosted. Firebase Auth — mobile-first. Okta — enterprise workforce identity. AWS Cognito — serverless user pools.
Microservices auth pattern: API Gateway validates JWT → extracts claims → passes user context in headers → downstream services trust gateway. Token exchange for service-to-service calls (audience-restricted tokens). Service accounts for machine identity.
Anti-patterns: Rolling your own auth — use battle-tested IdPs. Long-lived tokens without rotation — compromised token valid forever. Symmetric JWT (HS256) across services — shared secret = any service can forge tokens. No rate-limiting on login — credential stuffing.
Real-world: Google — OIDC tokens for all API access. Stripe — scoped API keys with restricted permissions. GitHub — fine-grained PATs replacing classic tokens. Cloudflare — Access replaces VPN with identity-aware proxy.

Authorization

Verifying permissions — "What can you do?" — enforce least privilege at every layer

Authorization Models — RBAC → ABAC → ReBAC
RBAC (Role-Based) Users → Roles → Permissions User Role:admin read,write,delete ✓ Simple, auditable ✗ Role explosion at scale Use: GitHub, AWS IAM, K8s RBAC ABAC (Attribute-Based) Rules on attributes (who, what, where, when) IF role=doctor AND dept=cardiology AND time=business_hours → ALLOW read:patient ✓ Fine-grained, context-aware ✗ Complex policies, hard to audit ReBAC (Relationship-Based) Relationships define access (graph-based) user:alice IS owner OF doc:report → owner CAN edit, share, delete ✓ Natural for sharing, hierarchies ✗ Graph traversal complexity Policy-Based Authorization (OPA / Cedar / Rego) Externalized policies — decouple authorization logic from application code allow { input.method == "GET" input.user.role == "viewer" } Decision: ALLOW / DENY + audit log of every decision Tools: OPA/Rego, AWS Cedar, Casbin, Cerbos, Permit.io
ModelHow It WorksScalabilityUse CaseExample Systems
RBACUsers → Roles → PermissionsSimple, limited flexibilityMost apps, admin panelsGitHub, AWS IAM, K8s, PostgreSQL
ABACRules on attributes (role, time, IP, resource tags)Very flexible, complex policiesHealthcare, finance, complianceAWS IAM Conditions, XACML
ReBACGraph of relationships (user→resource)Handles sharing/hierarchy naturallyFile sharing, social, multi-tenantGoogle Zanzibar, AuthZed, Ory Keto
Policy-BasedExternalized rules (Rego/Cedar DSL)Decoupled, testable, versionableMicroservices, multi-tenant SaaSOPA, AWS Cedar, Cerbos
ACLPer-resource access control listSimple but doesn't scaleFile systems, small appsLinux permissions, S3 ACLs (legacy)
Authorization Patterns in Microservices

Where to Enforce

  • API Gateway: coarse-grained (valid token? correct scope?)
  • Service layer: business rules (can this user edit THIS resource?)
  • Database: row-level security (Postgres RLS, Citus)
  • Sidecar/mesh: OPA sidecar for policy decisions
  • Frontend: UI-only (never trust — always verify server-side)

Google Zanzibar (ReBAC)

  • Powers Google Drive, YouTube, Cloud IAM
  • Relationship tuples: (user, relation, object)
  • Check: "does user:alice have edit on doc:123?"
  • Handles billions of relationships, <10ms checks
  • Open-source: SpiceDB, Ory Keto, OpenFGA
Principles: Least privilege — minimal permissions needed. Deny by default — explicit grants only. Separation of duties — no single role can do everything. Auditability — log every access decision (who, what, when, allowed/denied).
Multi-tenant authorization: Every query must include tenant_id filter. Use row-level security (Postgres RLS) as defense-in-depth. Tenant isolation at every layer: API → service → DB. Test with cross-tenant access attempts.
Anti-patterns: Checking permissions only in UI — API must enforce independently. God role — one role with all permissions (audit nightmare). Hardcoded permissions in code — can't change without deploy. No tenant isolation — one customer sees another's data.
Real-world: Google — Zanzibar for all products (Drive, YouTube, Cloud). GitHub — RBAC (owner/admin/write/read) + fine-grained permissions. AWS — IAM policies (ABAC with conditions). Notion — workspace → team → page hierarchy (ReBAC).

Encryption

Protecting data at rest and in transit — the foundation of confidentiality and integrity

Encryption Types — Symmetric, Asymmetric & Hashing
Symmetric (AES-256-GCM) same key encrypts + decrypts plaintext 🔑 key ciphertext ✓ Fast (hardware AES-NI) Use: disk encryption, DB encryption, S3 SSE Asymmetric (RSA / ECDSA) public key encrypts, private key decrypts plaintext 🔑 pub ciphertext ✗ Slow (1000× slower than AES) Use: TLS handshake, JWT signing, SSH, PGP Hashing (One-Way) irreversible transformation, no key needed input hash (fixed) ✗ no reverse ✓ Verify without storing secret Use: passwords (bcrypt), integrity (SHA-256) Envelope Encryption (KMS Pattern) Data key encrypts data; master key (in HSM) encrypts data key — never expose master key Your Data Data Key (DEK) AES-256, per-object encrypts Encrypted Data Master Key (KEK) in HSM, never leaves wraps DEK Encrypted DEK stored alongside data AWS KMS / GCP Cloud KMS / Azure Key Vault / HashiCorp Vault
TypeAlgorithmKey SizeUse CaseNotes
SymmetricAES-256-GCM256-bitData at rest, disk, DB column encryptionStandard choice. GCM provides authentication.
SymmetricChaCha20-Poly1305256-bitTLS on mobile (no AES-NI)Software-fast, used by WireGuard
AsymmetricRSA-2048+2048-4096 bitTLS certs, JWT RS256 signingSlow, being replaced by ECDSA
AsymmetricECDSA (P-256)256-bitTLS 1.3, JWT ES256, SSH keysPreferred. Smaller keys, faster.
AsymmetricEd25519256-bitSSH keys, signingFastest, simplest, no config pitfalls
Key ExchangeX25519 (ECDH)256-bitTLS 1.3 key exchangeForward secrecy (new key per session)
Hashingbcrypt / Argon2idN/APassword storageSlow by design. Salt + work factor.
HashingSHA-256 / SHA-3N/AIntegrity checks, HMAC, content addressingFast. Never for passwords.
EnvelopeDEK + KEKVariesCloud KMS pattern (AWS, GCP, Azure)Master key never leaves HSM
TLS 1.3 — Encryption in Transit
Client Server ClientHello: supported ciphers + key_share (X25519) ServerHello: chosen cipher + key_share + cert + Finished Client Finished → encrypted app data begins TLS 1.3: 1-RTT handshake (vs 2-RTT in TLS 1.2) | 0-RTT resumption possible Cipher: TLS_AES_256_GCM_SHA384 + X25519 key exchange + Ed25519 cert 1 RTT

Data in Transit

  • TLS 1.3: all external traffic (HTTPS, gRPC-TLS)
  • mTLS: service-to-service (Istio, Linkerd)
  • VPN/WireGuard: site-to-site, remote access
  • SSH: admin access (Ed25519 keys preferred)
  • Enforce: HSTS header, cert pinning for mobile

Data at Rest

  • Disk: LUKS, BitLocker, AWS EBS encryption
  • Database: TDE (Transparent Data Encryption)
  • Object storage: S3 SSE-KMS, GCS CMEK
  • Column-level: encrypt PII fields individually
  • Backup: encrypt before upload (client-side)
Secrets Management — Never Hardcode Secrets
ToolTypeKey FeatureUse Case
HashiCorp VaultSecrets engineDynamic secrets, auto-rotation, audit logDB creds, API keys, PKI certs
AWS Secrets ManagerManagedAuto-rotation for RDS, RedshiftAWS-native apps, Lambda
AWS SSM Parameter StoreConfig + secretsFree tier, hierarchical pathsConfig values, non-rotating secrets
GCP Secret ManagerManagedIAM-based access, versioningGCP workloads
Azure Key VaultManagedHSM-backed, cert managementAzure workloads, .NET integration
SOPSFile encryptionEncrypt values in YAML/JSON, git-friendlyGitOps, IaC secrets in repo
K8s External SecretsOperatorSync from Vault/AWS/GCP → K8s SecretsK8s workloads needing external secrets
Encryption Best Practices & Common Mistakes

Do

  • Use AES-256-GCM (authenticated encryption)
  • Use bcrypt/Argon2id for passwords (cost factor ≥ 12)
  • Use envelope encryption (KMS) for data at rest
  • Rotate keys regularly (90 days for data keys)
  • Enable TLS 1.3 everywhere, disable TLS 1.0/1.1
  • Use forward secrecy (ephemeral key exchange)
  • Store secrets in Vault/KMS, never in code/env vars

Never Do

  • MD5/SHA1 for passwords — rainbow table attacks
  • ECB mode — reveals patterns in ciphertext
  • Hardcoded keys in source code or Docker images
  • Reuse IVs/nonces — breaks AES-GCM completely
  • Roll your own crypto — use vetted libraries
  • Encrypt without authenticating — use AEAD modes
  • Log sensitive data — PII, tokens, keys in logs
Key rotation: Envelope encryption makes rotation easy — rotate the master key (KEK), re-wrap data keys. Data itself doesn't need re-encryption. Automatic rotation via KMS (AWS: every 365 days, configurable). Old key versions kept for decryption of existing data.
Compliance: PCI-DSS — encrypt cardholder data, rotate keys annually. HIPAA — encrypt PHI at rest and in transit. GDPR — encryption as a technical safeguard. SOC 2 — demonstrate encryption controls in audit.
Anti-patterns: Secrets in .env committed to git — scan with truffleHog/gitleaks. Same key for all environments — dev key compromise = prod compromise. No key rotation — compromised key valid forever. Client-side encryption without key escrow — data lost if key lost.
Real-world: AWS — KMS + envelope encryption for S3, EBS, RDS (default). Google — default encryption at rest with Google-managed keys + CMEK option. Stripe — PGP for API key delivery, AES-256 for card data. Signal — Double Ratchet protocol (forward secrecy per message).