FullStack AI Hub
Studio
System Design · 07. Security
11 min
10 steps
Beginner

Encryption & TLS

Trace TLS 1.3 key exchange, zero-trust mTLS, KMS envelope encryption, and zero-downtime key rotation.

System Design07. SecurityLesson 3 of 3
11 minBeginner10 steps

Encryption & TLS

Trace TLS 1.3 key exchange, zero-trust mTLS, KMS envelope encryption, and zero-downtime key rotation.

Traffic Privacy
Plaintext!
Tamper Check
None
Server Identity
Unverified
Crypto Overhead
0 ms
Cleartext CookieTampered PayloadUser LaptopRogue Wi-Fi HopOriginServerMITM InterceptReads passwords & injects JS
Encrypted TLS Traffic
Key Exchange / KMS Wrap
Verified Ciphertext
Plaintext / MITM Sniffing
Expired Cert / Reject
In This LessonStep 1 of 10
What You Will Master
  • ✓Trace how TLS 1.3 pairs ECDHE key exchange with AES-GCM for 1-RTT Forward Secrecy
  • ✓Compare edge TLS termination against Zero-Trust service-to-service Mutual TLS (mTLS)
  • ✓Protect database PII with KMS Envelope Encryption (DEK + KEK) and local DEK caching
  • ✓Rotate encryption keys and X.509 certificates automatically with zero downtime

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
TLS 1.3 (ECDHE + AES-256-GCM)All public internet traffic between browsers/mobile apps and edge load balancersRequires automated ACME cert renewal to prevent sudden expiry outages
Zero-Trust mTLS (SPIFFE)Internal microservice-to-microservice traffic inside cloud VPCs and KubernetesRequires a service mesh or sidecar proxy to rotate short-lived client certs automatically
Disk Encryption at RestCompliance baseline protecting stolen physical drives or EBS volume snapshotsTransparent to the DB—does NOT stop SQL injection or compromised DBA accounts
KMS Envelope Encryption + CacheApplication-level encryption of SSNs, payment tokens, and tenant secretsEncrypted columns cannot use normal B-Tree range queries (need blind HMAC indexes)

Step-by-Step Architectural Breakdown (10 Steps)

Full architectural walkthrough transcript and state transitions for Encryption & TLS.

STEP 01 · PROBLEMJump to step →

Plaintext HTTP & Man-in-the-Middle Interception

Without **TLS (HTTPS)**, every HTTP request travels across coffee-shop Wi-Fi routers, ISPs, and BGP hops in readable **plaintext**. Any on-path attacker can silently read session cookies and passwords (**eavesdropping**) or inject malicious scripts into responses (**tampering**).

TLS solves three security properties at once: **Confidentiality** (encryption), **Integrity** (authenticated tags detect any bit flip), and **Authenticity** (certificates prove you are talking to `bank.com`, not an impostor).

watch:Always enable HSTS (`Strict-Transport-Security`) so browsers refuse to downgrade the very first request to plaintext `http://`.

MITM AttackConfidentialityIntegrityAuthenticity
STEP 02 · TECHNIQUEJump to step →

Hybrid Crypto: Asymmetric Handshake + Symmetric Bulk

**Symmetric encryption (AES-256-GCM / ChaCha20-Poly1305)** encrypts data at **5+ GB/sec** using hardware AES-NI instructions—but both sides must somehow agree on the exact same secret key over a hostile network.

**Asymmetric cryptography (ECDHE / RSA)** solves the key-distribution paradox using public/private key pairs, though it is ~1,000× slower. TLS uses **Hybrid Cryptography**: asymmetric math runs *once* during the handshake to agree on a shared session key, then fast symmetric AES-GCM encrypts every byte after that.

idea:AEAD ciphers like AES-256-GCM provide encryption AND an authentication tag in one pass—so flipping a single ciphertext bit causes instant decryption rejection.

AES-256-GCMAEAD IntegrityECDHE Key ExchangeHybrid Cryptography
STEP 03 · SOLUTIONJump to step →

TLS 1.3 1-RTT Handshake & Forward Secrecy

TLS 1.2 required **2 full round-trips (2-RTT)** before sending the first byte of HTTP and still allowed static RSA key exchange. **TLS 1.3** strips away legacy weak ciphers and sends the client’s ephemeral Diffie-Hellman key share right inside `ClientHello`—cutting setup to **1-RTT** (saving 40–150 ms on mobile networks!).

Even better, TLS 1.3 mandates **Ephemeral Diffie-Hellman (ECDHE)** for **Perfect Forward Secrecy (PFS)**: session keys are discarded immediately after the connection closes. Even if an attacker steals the server’s long-term private key next year, previously recorded traffic remains undecryptable.

good:TLS 1.3 + HTTP/3 (QUIC) merges TCP and TLS handshakes together, cutting cold connection setup from 3-RTT down to 1-RTT (and 0-RTT for repeat visitors).

TLS 1.3 1-RTTPerfect Forward SecrecyEphemeral Keys0-RTT Resumption
STEP 04 · TECHNIQUEJump to step →

PKI Certificate Chains & Automated ACME Renewal

Encryption alone is useless if you accidentally encrypt your password directly to an attacker! Your browser verifies the server’s **X.509 Certificate Chain**: the site’s **Leaf Cert** is cryptographically signed by an **Intermediate CA**, signed by a **Root CA** pre-installed in your OS trust store.

One of the most common self-inflicted production outages in software history is an **expired TLS certificate**. Automate 90-day (or 47-day) certificates with **ACME (`cert-manager` / Let’s Encrypt)** renewing seamlessly 30 days before expiry.

watch:Never manage production TLS certificates with calendar reminders! Automated ACME renewal + synthetic expiry monitoring (`cert_days_remaining < 14`) eliminates cert outages forever.

X.509 ChainCertificate AuthorityACME AutomationCertificate Transparency
STEP 05 · TRADE-OFFJump to step →

Edge TLS Termination vs Zero-Trust mTLS

Traditional "castle-and-moat" networks terminate TLS at the Edge Load Balancer and forward **plaintext HTTP** inside the private VPC. If a single container is compromised via an RCE bug, the attacker can sniff east-west traffic or impersonate internal microservices freely.

**Zero-Trust Mutual TLS (mTLS)** encrypts every internal hop and requires **both client AND server** to present short-lived cryptographic workload identities (**SPIFFE / SVID certs** rotated every few hours by a service mesh like Istio or Envoy).

idea:With mTLS, the Payments service doesn’t trust an IP address—it cryptographically verifies that the caller’s client certificate says `spiffe://prod/ns/checkout/sa/orders`.

Mutual TLS (mTLS)Zero-Trust NetworkSPIFFE IdentityService Mesh Sidecar
STEP 06 · TECHNIQUEJump to step →

Encryption at Rest vs Column-Level PII Encryption

Cloud **Disk Encryption at Rest** (EBS / RDS KMS) encrypts bytes on physical SSDs so someone stealing a decommissioned hard drive sees gibberish. However, while the database is running, it decrypts pages **transparently**—meaning a SQL injection bug or compromised DBA still reads every SSN and tax ID in plaintext!

For crown-jewel PII (SSNs, OAuth tokens, health records), add **Application / Column-Level Encryption**: the app encrypts sensitive fields *before* sending SQL `INSERT`, so the database itself only ever stores opaque ciphertext.

watch:Disk encryption checks a compliance box for stolen drives, but only application-level encryption protects sensitive fields if your database snapshot or read-replica credentials leak.

Encryption at RestColumn-Level EncryptionCiphertext DBBlind Index (HMAC)
STEP 07 · SOLUTIONJump to step →

KMS Envelope Encryption (DEK + KEK)

Where do you store the encryption key? Never hardcode it in Git or `.env` files! Yet sending 10 MB files over the network to **Cloud KMS (AWS KMS / GCP KMS)** for every encrypt call is slow and hits 4 KB payload limits.

**Envelope Encryption** uses a two-tier key hierarchy: a fast local **Data Encryption Key (DEK)** encrypts your actual record in RAM, and a hardware-backed **Key Encryption Key (KEK)** inside KMS—which *never leaves the HSM*—encrypts ("wraps") the tiny 32-byte DEK. You store `(ciphertext + wrapped_dek)` right alongside each other in your database.

good:Envelope Encryption gives you hardware HSM security (the master KEK never leaves KMS) AND arbitrary payload size with local AES-GCM speed.

Envelope EncryptionDEK vs KEKHardware HSMCloud KMS
STEP 08 · TECHNIQUEJump to step →

Local DEK Caching to Escape KMS Rate Limits

Calling Cloud KMS on every single read costs both latency (~15 ms) and thousands of dollars in KMS API charges. The fix is **Bounded Local DEK Caching** (e.g., AWS Encryption SDK Data Key Caching).

Each app instance caches the unwrapped DEK in volatile RAM with **strict security caps**: max age **5 minutes** AND max **10,000 messages encrypted** (with a fresh random 96-bit AES-GCM IV/nonce per record). KMS traffic drops by **99.5%** while preserving tight key-exposure bounds.

watch:CRITICAL AES-GCM rule: NEVER reuse the same `(DEK, IV/nonce)` pair twice—reusing a GCM nonce completely breaks confidentiality and authentication!

DEK CachingKMS Quota SavingsUnique 96-bit IVBounded Cache TTL
STEP 09 · TECHNIQUEJump to step →

Zero-Downtime Key Rotation (Dual-Read & Re-Wrap)

Rotating a master encryption key **never** means taking your database offline to decrypt and re-encrypt 500 million rows! Instead, every encrypted envelope stores a cleartext **`key_version` header** (`kek_v1`, `kek_v2`).

Rotation happens in 3 zero-downtime phases: (1) activate `kek_v2` for all **new writes** while still allowing **reads** from both `v1` and `v2`, (2) run a throttled background worker that simply **re-wraps the 32-byte DEKs** from `v1 → v2` (no bulk data re-encryption needed!), and (3) retire `kek_v1` once zero rows reference it.

good:Envelope re-wrapping rotates keys across 100 TB of user files in minutes because you only re-encrypt tiny 32-byte DEKs—never the gigabytes of ciphertext!

Key VersioningDual-Read RotationEnvelope Re-WrapZero-Downtime Crypto
STEP 10 · RECAPJump to step →

Full-Stack Encryption & TLS Architecture

Complete data protection covers every boundary: **TLS 1.3 + automated ACME** at the public edge, **Zero-Trust mTLS** with short-lived SPIFFE certificates between internal services, and **Disk + KMS Envelope Encryption with local DEK caching** for stored PII.

Treat key and certificate rotation as continuous automated background processes—never emergency fire drills.

good:Encrypt in transit (TLS 1.3 + mTLS), encrypt at rest (Disk + Envelope PII), keep master keys inside HSMs, and automate every rotation.

TLS 1.3Zero-Trust mTLSKMS Envelope + DEK CacheAutomated Rotation

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.