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
Implicitβ€”DEPRECATEDInsecure β€” 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).