Cheat SheetsComputer NetworksInfrastructure

Infrastructure — Cheat Sheet

Computer Networks · 5 topics. Download the PDF or the Instagram carousel and share it.

Cheat Sheet · AiCanCode.org
Infrastructure
Computer Networks5 topicsQuick revision reference
1

Load Balancers

A load balancer distributes incoming traffic across multiple backend servers to prevent any single server from becoming a bottleneck, while providing health checking, SSL termination, and high availability.

  • L4 load balancers route by IP/port (fast, protocol-agnostic); L7 route by HTTP content (smarter, enables path-based routing).
  • Least-connections is better than round-robin when request processing times vary significantly.
  • IP hash provides session affinity without shared state — but better practice is to externalise session to Redis.
  • Connection draining (deregistration delay) allows in-flight requests to complete before removing an instance — enables zero-downtime deployments.
  • AWS ALB is the default choice for HTTP microservices; NLB for non-HTTP protocols or ultra-low latency TCP.
L4 vs L7 load balancer comparison
// Layer 4 (TCP/UDP) — AWS Network Load Balancer (NLB)
// Routes based on: destination IP + port + protocol
// Does NOT read HTTP headers, paths, or cookies
// Use cases: non-HTTP protocols (gRPC, WebSocket raw, gaming, IoT),
//            ultra-low latency, millions of concurrent connections
// Connection: client ↔ NLB ↔ backend (TCP passthrough)

// Layer 7 (HTTP/HTTPS) — AWS Application Load Balancer (ALB)
// Reads: URL path, Host header, HTTP method, cookies, query params
// Use cases: microservices routing, A/B testing, auth offload, WebSocket
// Routing rules example:

// Nginx L7 load balancer config:
upstream api_servers {
  least_conn;                     // least-connections algorithm
  server 10.0.1.1:8080 weight=3; // gets 3x more traffic
  server 10.0.1.2:8080 weight=1;
  server 10.0.1.3:8080 backup;   // only used if others are down
}

server {
  listen 443 ssl;
  location /api/     { proxy_pass http://api_servers; }
  location /static/  { proxy_pass http://cdn_servers; }  // content-aware routing
}
2

Reverse Proxy

A reverse proxy sits in front of backend servers and forwards client requests to them — providing SSL termination, caching, compression, rate limiting, and shielding internal server topology from external clients.

  • A reverse proxy decouples client-facing endpoints from internal backend topology — backends can change without affecting clients.
  • Nginx handles tens of thousands of concurrent connections with minimal memory using an event-driven, non-blocking architecture.
  • Always pass X-Forwarded-For and X-Real-IP headers so backends know the actual client IP, not the proxy's IP.
  • Proxy-level caching reduces backend load for read-heavy endpoints — combine with immutable Cache-Control headers for static assets.
  • Kubernetes Ingress Controllers (nginx-ingress, Traefik) are reverse proxies that route cluster-external traffic to services.
Forward proxy vs reverse proxy
// Forward Proxy (client-side):
// Client ──▶ [Forward Proxy] ──▶ Internet
// Use cases:
//   - Corporate internet filtering (block social media, log traffic)
//   - Anonymisation (hide client IP from servers)
//   - VPN/tunnelling (bypass geo-restrictions)
// Server sees: proxy's IP, not client's IP

// Reverse Proxy (server-side):
// Client ──▶ [Reverse Proxy] ──▶ Backend Server(s)
// Use cases:
//   - SSL termination
//   - Load balancing (Nginx upstream)
//   - Caching static content
//   - Rate limiting and security
//   - Serve multiple apps on one IP (virtual hosts)
// Client sees: proxy's domain (aicancode.org), not backend's internal IP (10.0.1.5)

// Virtual hosting (multiple apps, one IP/port):
// nginx:
server { server_name api.aicancode.org;  proxy_pass http://api_backend; }
server { server_name www.aicancode.org;  proxy_pass http://nextjs_backend; }
3

CDN (Content Delivery Network)

A CDN is a globally distributed network of edge servers that cache and serve content from locations close to users — reducing latency, decreasing origin load, and improving availability.

  • A CDN cache hit serves from a PoP milliseconds away; a miss fetches from origin and populates the edge cache for subsequent requests.
  • Use content-hash filenames for static assets with max-age=31536000 immutable — no invalidation ever needed.
  • Use s-maxage (CDN TTL) separate from max-age (browser TTL) for HTML pages served via CDN.
  • Explicit purge is needed for HTML pages and API responses; versioned URLs are self-invalidating for static assets.
  • Edge compute (Cloudflare Workers, Lambda@Edge) enables A/B testing, auth, and geo-redirects without origin round-trips.
CDN routing and CloudFront configuration
// CDN request flow:
// 1. User in Mumbai requests: https://aicancode.org/logo.png
// 2. DNS query for aicancode.org → CDN GeoDNS returns Mumbai PoP IP (e.g. 104.18.x.x)
// 3. Browser connects to Mumbai PoP
// 4. PoP checks cache: HIT → serve immediately (~5ms)
//                      MISS → fetch from origin (e.g. Vercel/AWS), cache, serve
//
// Cache key: typically scheme + host + path + (optionally) query string
// X-Cache: HIT / MISS / REFRESH_HIT in response headers

// CloudFront distribution (Terraform):
resource "aws_cloudfront_distribution" "cdn" {
  origin {
    domain_name = "api.aicancode.org"
    origin_id   = "api-origin"
  }
  default_cache_behavior {
    allowed_methods        = ["GET", "HEAD"]
    cached_methods         = ["GET", "HEAD"]
    viewer_protocol_policy = "redirect-to-https"
    cache_policy_id        = aws_cloudfront_cache_policy.default.id
  }
  price_class = "PriceClass_200"  // all PoPs except South America
  enabled     = true
}
4

API Gateway

An API Gateway is a single entry point for all client requests that handles cross-cutting concerns — authentication, rate limiting, routing, protocol translation, and observability — before forwarding to backend microservices.

  • An API Gateway centralises cross-cutting concerns (auth, rate limiting, routing, logging) so backend services focus on business logic.
  • JWT validation at the gateway means backend services receive authenticated requests and decoded identity as trusted headers.
  • Rate limiting is enforced at the gateway using shared Redis state — limits can be per-IP, per-user, or per-subscription tier.
  • API Gateway handles north-south traffic (client↔service); service mesh handles east-west traffic (service↔service) — they are complementary.
  • AWS API Gateway authorizer caches auth results (configurable TTL) to avoid hitting the Lambda authorizer on every request.
API Gateway responsibility matrix
// API Gateway cross-cutting concerns:
//
// Client Request ──▶ API Gateway ──▶ Backend Service
//
// What the gateway handles:
// ┌──────────────────────────────────────────────────────────┐
// │ 1. SSL Termination     — decrypt HTTPS, forward HTTP     │
// │ 2. Authentication      — validate JWT / API key / OAuth  │
// │ 3. Authorisation       — check scopes / roles            │
// │ 4. Rate Limiting       — 100 req/min per API key         │
// │ 5. Request Routing     — /api/courses → course-service   │
// │                          /api/users   → user-service     │
// │ 6. Protocol Translation— REST → gRPC (grpc-gateway)      │
// │ 7. Request Transform   — add headers, rewrite paths      │
// │ 8. Response Aggregation— fan out to N services, merge    │
// │ 9. Caching             — cache GET responses at edge     │
// │ 10. Observability      — unified access logs, metrics    │
// └──────────────────────────────────────────────────────────┘
5

Service Mesh

A service mesh is an infrastructure layer that manages service-to-service communication inside a cluster — providing automatic mTLS, traffic management, retries, circuit breaking, and distributed tracing via a sidecar proxy deployed alongside every service.

  • A service mesh injects a sidecar proxy (Envoy) into every pod — all network traffic flows through it transparently, enabling mesh-wide policies.
  • Istio issues SPIFFE X.509 certificates to every workload automatically — mTLS between all services with zero application code changes.
  • Traffic management (retries, timeouts, circuit breakers, canary splits) is configured via Kubernetes CRDs — no code changes in services.
  • Outlier detection ejects repeatedly-failing instances from the load-balancing pool, acting as a distributed circuit breaker.
  • Service mesh is not a replacement for an API Gateway — the gateway handles north-south (external) traffic; the mesh handles east-west (internal) traffic.
Sidecar proxy pattern and traffic interception
// Kubernetes pod with Istio sidecar injection:
// (injection is automatic when namespace is labelled)
kubectl label namespace production istio-injection=enabled

// Resulting pod has 2 containers:
// ┌─────────────────────────────────────────────────────┐
// │ Pod: course-service-7f9b4d5-xk2p8                  │
// │  ┌──────────────────┐  ┌──────────────────────────┐ │
// │  │  course-service  │  │  istio-proxy (Envoy)     │ │
// │  │  :8080           │  │  :15001 (outbound)       │ │
// │  │  (app code)      │  │  :15006 (inbound)        │ │
// │  └──────────────────┘  └──────────────────────────┘ │
// └─────────────────────────────────────────────────────┘
// iptables rules redirect all traffic through Envoy transparently:
// Outbound: app → Envoy :15001 → (encrypt mTLS) → destination Envoy
// Inbound:  source Envoy → (decrypt mTLS) → Envoy :15006 → app :8080
Learn this free with Aria, your AI tutor → AiCanCode.org/learn/computer-networks