Guide / System design Fundamentals
10. Real-time, observability, deployment, security, LLD
Rate limiting now has its own page: Rate limiting.
10.2 Real-time and push systems#
- Fan-out on write (push): precompute each follower’s feed when someone posts; fast reads, expensive for users with millions of followers. Fan-out on read (pull): build feed at read time; cheap writes, slow reads. Hybrid: push for normal users, pull for celebrities.
- WebSocket at scale: stateful gateway servers (one holds ~50–100K+ connections), a presence/connection registry in Redis (
user → gateway), pub/sub (Redis, Kafka, NATS) between backend and gateways, sticky routing at the LB for upgrades, heartbeat every ~30 s. - Notifications: a notification service with per-channel workers (push via APNs/FCM, SMS, email), user preferences, templates, dedupe, rate limits, retries + DLQ.
10.3 Observability#
- Logs (structured JSON, correlation/trace ID in every line), metrics (counters, gauges, histograms; RED = Rate, Errors, Duration for services; USE = Utilization, Saturation, Errors for resources), traces (OpenTelemetry spans across services).
- SLI = measured signal (p99 latency, success rate); SLO = target (99.9% of requests < 300 ms over 30 days); SLA = contractual promise with penalties; error budget = 1 − SLO (0.1% ≈ 43 min/month) — spend it on releases, freeze when exhausted.
- Alert on symptoms users feel (error rate, latency) not on every cause; page only for actionable alerts.
- Percentiles matter more than averages: p99 latency is what your heaviest users see, and fan-out multiplies tail latency.
10.4 Deployment and release#
Rolling (replace instances gradually), blue-green (two environments, switch traffic, instant rollback, double capacity cost), canary (1% → 10% → 100% with automated metric checks), feature flags (decouple deploy from release, kill switches, A/B tests), shadow traffic (mirror production requests to the new version without returning its responses). Database migrations must be backward compatible with both versions during rollout.
10.5 Security fundamentals#
- AuthN vs AuthZ: who you are vs what you can do. OAuth 2.0 (delegated authorization; authorization code + PKCE for apps), OIDC (identity on top of OAuth), SAML (enterprise SSO).
- Sessions vs JWT: server sessions are revocable instantly; JWTs are stateless but hard to revoke → short-lived access token (5–15 min) + refresh token with rotation and a revocation list.
- RBAC vs ABAC: roles vs attribute-based policies (tenant, department, resource owner).
- Multi-tenancy isolation: tenant ID in every query (row-level security in Postgres), per-tenant encryption keys for sensitive data, noisy-neighbour limits.
- Data protection: TLS in transit, encryption at rest (KMS), secrets in a vault (not env files in Git), PII minimisation, masking in logs, audit logs.
- Common attacks: SQL injection (parameterized queries), XSS (escape output, CSP), CSRF (SameSite cookies, tokens), SSRF (allowlist outbound hosts), IDOR (check ownership on every resource ID), DDoS (CDN/WAF, rate limits).
10.6 Low-level design (machine coding rounds)#
- SOLID: Single responsibility, Open/closed (extend without modifying), Liskov substitution (subtypes usable as their base), Interface segregation (small focused interfaces), Dependency inversion (depend on abstractions, inject dependencies).
- Other principles: DRY, KISS, YAGNI, composition over inheritance, law of Demeter.
- Patterns to know cold: Strategy (pricing/discount rules), Factory (create payment providers), Observer (notifications), State (order lifecycle, elevator), Decorator (adding toppings, middleware), Singleton (sparingly), Builder, Adapter (wrapping third-party gateways), Chain of Responsibility (validation pipelines), Command (undo).
- Concurrency: race conditions, mutexes, read-write locks, deadlock (and the four conditions), producer-consumer with bounded queues, thread pools; in Go: goroutines, channels,
select,sync.WaitGroup, context cancellation. - Classic LLD problems: parking lot, elevator, Splitwise, BookMyShow seat booking (concurrent seat locking), LRU cache (hash map + doubly linked list), rate limiter, vending machine, snake & ladder, chess, in-memory KV store with TTL, logger, pub/sub.
- How LLD is judged: clean entities and relationships, extensibility (add a new vehicle type without rewriting), working code, tests, handling concurrency where relevant.
10.7 Specialised topics — geospatial and collaborative editing#
Geospatial indexing (“find nearby drivers / restaurants”)#
A plain index on latitude and longitude can’t answer “within 2 km” efficiently, because a B-tree orders one dimension at a time. Spatial indexes map 2D space into cells.
| Approach | How | Pros | Cons |
|---|---|---|---|
| Geohash | Encode lat/lng into a base-32 string; shared prefix = nearby; precision by length (6 chars ≈ 1.2 km × 0.6 km cell) | Works with any KV/B-tree via prefix queries; Redis GEO uses it | Edge problem: nearby points across a cell border have different prefixes, so always search the cell + its 8 neighbours |
| Quadtree | Recursively split a square into 4 until each cell has ≤ N points | Adapts to density (dense cities get small cells) | In-memory structure to maintain; rebalancing on moves |
| Google S2 / Uber H3 | Hierarchical cells on a sphere (H3 uses hexagons) | Uniform neighbours (hexagons have equal-distance neighbours), good for aggregation (surge pricing per hex) | Library-specific |
| R-tree / PostGIS (GiST) | Bounding-box tree in the database | Rich spatial queries (polygons, delivery zones) in SQL | Write-heavy moving objects strain it |
Static places (restaurants): PostGIS or Elasticsearch geo queries; read-heavy, cached. Moving objects (drivers, every ~4 s): keep latest locations in memory (Redis GEO or an in-memory grid sharded by cell), don’t write every ping to the main DB; stream pings to Kafka for history/analytics. Query: compute the rider’s cell, fetch drivers in it and neighbours, filter by exact distance (haversine), rank by ETA. Shard the location service by region/city.
Collaborative editing (Google Docs, Figma)#
Many users edit the same document at once; everyone must converge to the same state without locking.
- Operational Transformation (OT): edits are operations (insert “x” at position 5). When two concurrent operations arrive, the server transforms one against the other (if A inserted before position 5, B’s position shifts to 6). Needs a central server to order operations. Used by Google Docs. Mature but complex to get right.
- CRDTs (Conflict-free Replicated Data Types): each character/element has a unique, ordered ID, so concurrent inserts merge deterministically on any replica, in any order, without a central coordinator. Works offline and peer-to-peer. Libraries: Yjs, Automerge. Costs: metadata overhead (tombstones for deletes), and need for garbage collection.
- Architecture: clients connect via WebSocket to a document session server (all editors of one doc routed to the same server via consistent hashing on
doc_id); server orders/merges ops, broadcasts to other clients, appends ops to a log, and periodically snapshots the document (load = latest snapshot + ops after it). Presence (cursors, selections) is ephemeral and sent separately, not persisted. - Offline: client queues local ops and syncs on reconnect; CRDTs merge naturally, OT rebases ops against what changed on the server.
- Follow-ups: “What if the session server dies?” (clients reconnect to a new server, which loads snapshot + op log; unacked client ops are resent with IDs for dedupe). “How do you do version history?” (named snapshots over the op log). “Permissions?” (checked on connect and on each op for comment-only/view-only users).