Skip to content

Repository files navigation

🌐 Distributed Systems Simulator

A browser-native, high-scale distributed systems architecture, queuing models, failure injection, and FAANG system design interview evaluation sandbox.

Vite React TypeScript TailwindCSS Vitest Status Tests License: MIT


📑 Table of Contents


💡 Overview

The Distributed Systems Simulator provides a visual, hands-on environment for modeling, testing, and debugging high-throughput distributed architectures. Rather than reading abstract documentation, engineers can interactively observe:

  • Traffic distribution and consistent hashing on load balancers.
  • Primary-replica database replication lag and failover split-brain scenarios.
  • Multi-tier cache stampedes, XFetch early recomputation, and LRU/LFU evictions.
  • Circuit breaker tripping, token-bucket rate limiting, and exponential retry backoff with jitter.
  • Multi-region geo-routing across trans-oceanic subsea fiber backbones.
  • Chaos engineering experiments (node crashes, packet drops, Byzantine traitors).
  • End-to-end System Design Interviews with napkin-math calculators, automated SLA scoring, and real-world outage post-mortems.

⚡ Key Features

1. Ingress & Load Balancing

  • Load Balancing Algorithms: Round Robin, Least Connections, Weighted Round Robin, and Deterministic IP Hash.
  • Consistent Hashing Ring: 360-degree interactive SVG visualizer with virtual node tokens and minimal key redistribution upon node failure.
  • Token Bucket Rate Limiting: Ingress traffic throttling with configurable burst capacity and continuous token refill.
  • Health Checks & Outlier Ejection: Automated outlier detection with consecutive error threshold tripping.

2. Compute Nodes & Bulkheads

  • Server Cluster Grid: Horizontal scaling from 1 to 6 nodes with dynamic CPU, memory, and active connection tracking.
  • Failure State Machine: Simulates healthy, degraded, flapping, and out-of-memory (OOM) node states.
  • Bulkhead Isolation: Independent thread and connection pools for critical vs. non-critical subsystems.
  • Automated Watchdog Supervisor: Process health supervision with automatic node restart and recovery.

3. Distributed Database & Storage

  • Primary-Replica Replication: Synchronous and asynchronous write-ahead log (WAL) streaming.
  • Replication Lag & LSN Tracking: Simulates replication lag in milliseconds and Log Sequence Numbers (LSN).
  • Automated Quorum Failover: Automatic promotion of the freshest replica during leader outages.
  • Split-Brain Mitigation: STONITH (Shoot The Other Node In The Head) fencing and dual-leader detection.

4. Tiered Caching & Invalidation

  • Redis Cluster Simulation: In-memory key-value cache with real-time hit/miss ratio tracking.
  • Eviction Policies: Least Recently Used (LRU), Least Frequently Used (LFU), and First-In-First-Out (FIFO).
  • Cache Stampede Defense: Mutex single-flight request coalescing and XFetch probabilistic early recomputation.
  • Key Inspector: Detailed inspection of cache keys, TTL countdowns, and manual purge triggers.

5. Resilience & Fault Tolerance

  • Envoy/Hystrix Circuit Breakers: Closed, Open, and Half-Open tri-state machines with automatic health probing.
  • Advanced Retry Jitter: AWS Full Jitter and Decorrelated Jitter algorithms with idempotency safeguards.
  • Graceful Degradation Fallbacks: Stale cache fallback, mock default responses, and read-only mode.

6. Chaos Engineering & Byzantine Faults

  • Network Partition Matrix: Simulates full network cuts, asymmetric rings, and cross-AZ partitions.
  • Byzantine Fault Injection: Simulates Lamport's Byzantine Generals problem with message bit-flips and vote tampering.
  • Chaos Monkey Experiment Runner: Automated automated drills (Rolling AZ Outage, Database Blackhole, Cascading Meltdown).

7. Global Multi-Region & Geo-DNS

  • Geo-DNS Routing Policies: Geo-Proximity (Haversine distance), Latency-Based, Weighted, Active-Passive, and BGP Anycast.
  • Subsea Fiber WAN Backbone: Physical simulation of major undersea cables with propagation delay and cut drills.
  • 1-Click Region Evacuation: Instantaneous traffic draining and automated leader re-election.

🎓 System Design Interview Sandbox (Phase 12)

Phase 12 turns the simulator into an interactive interview preparation and architecture sandbox for senior and staff engineer candidates.

Canonical FAANG Scenarios

Scenario Tier Target SLA Core Architectural Challenge & Solution
Twitter / X Newsfeed Hard 99.99% (P99 < 95ms) Celebrity Fan-out: Hybrid push/pull fan-out. Normal users write to Redis; celebrities pull on read.
Uber Ride Matching Staff 99.95% (P99 < 80ms) Spatial Contention: Uber H3 hexagonal spatial indexing, discrete 5-second match windows with Hungarian algorithm.
Black Friday Flash Sale Hard 99.99% (P99 < 60ms) Inventory Overselling: Atomic Redis Lua script reservations, virtual waiting room, asynchronous Kafka checkout.
Netflix Video Streaming Medium 99.99% (P99 < 45ms) Origin I/O Bottlenecks: Multi-CDN edge appliances (Open Connect) caching 98% of 4s ABR chunks; multi-region active-active.
Bitly URL Shortener Easy 99.99% (P99 < 15ms) Hash Collisions: Deterministic Base62 counter IDs (3.5T unique links), Bloom filters, HTTP 301 edge caching.
WhatsApp Chat Platform Staff 99.99% (P99 < 70ms) C10M Connections: Erlang/BEAM lightweight processes (2M conns/server), ephemeral gateways, dual-ACK state machine.

Interactive Capabilities

  • 🧮 Napkin-Math Capacity Estimator: Back-of-the-envelope calculations for read/write QPS, 5-year storage, bandwidth, and 80/20 RAM cache sizing across 4 scale profiles (MVP Startup, Series B, FAANG Scale, Viral Flash Spikes).
  • 🏆 Automated Architecture Evaluator: Grades candidate architectures from A+ to F based on measured availability, P99 latency budgets, cloud costs, and Single Points of Failure (SPOFs).
  • 🧭 6-Step Interview State Machine: Guides candidates through Clarification, Estimation, High-Level Design, Deep Dive, Failure Scenarios, and Final Review.
  • 💡 3-Tier Progressive Hints Engine: Gentle nudges, architectural recommendations, and canonical blueprints with score penalties.
  • 🗺️ Topology Blueprints: ASCII flowcharts and data flow pipelines contrasting naive baselines with production designs.
  • 💥 Historical Post-Mortems (FailureModeMatrix): Real-world outage analyses (Twitter Fail Whale, Uber NYE Surge, Netflix AWS US-East-1 outage, WhatsApp connection tsunami).
  • 📝 Staff Engineer Technical Quizzes: 18 deep-dive questions with detailed explanations.
  • ⚡ Automated Load Benchmarks: Simulated traffic bursts up to 10,000 QPS with statistical percentile verification.
  • 📄 Executive Markdown Dossier Exporter: Generates complete technical evaluation reports with scorecards and recommendations.

🛠️ Architecture & Tech Stack


📂 Project Directory Structure

Distributed_Systems_Simulator/
├── src/
│   ├── components/                 # React UI components
│   │   ├── bulkhead/              # Bulkhead thread & connection pool UI
│   │   ├── chaos/                 # Chaos monkey, partitions & Byzantine UI
│   │   ├── interview/             # System Design Interview Sandbox UI
│   │   │   ├── ArchitectureBlueprintModal.tsx
│   │   │   ├── ArchitecturePresetLoader.tsx
│   │   │   ├── ArchitectureScorecardModal.tsx
│   │   │   ├── CapacityEstimatorCalculator.tsx
│   │   │   ├── FailureModeCaseStudyModal.tsx
│   │   │   ├── InterviewHintWidget.tsx
│   │   │   ├── ScenarioBenchmarkModal.tsx
│   │   │   ├── ScenarioSimulationWidget.tsx
│   │   │   ├── SystemDesignObjectivePanel.tsx
│   │   │   ├── SystemDesignQuizModal.tsx
│   │   │   ├── SystemDesignSandboxView.tsx
│   │   │   └── TradeoffMatrixView.tsx
│   │   ├── layout/                # Header, navigation, status bar
│   │   ├── modals/                # Consistent hash ring, circuit breaker modals
│   │   ├── multiregion/           # Multi-region world map & Geo-DNS UI
│   │   ├── nodes/                 # Server cards, DB cards, cluster grid
│   │   ├── telemetry/             # Metrics charts, latency histograms
│   │   └── ui/                    # Base primitives (Button, Badge, Card, Slider)
│   ├── engine/                    # Core simulation engines
│   │   ├── scenarios/             # System design scenario specifications & engines
│   │   │   ├── simulators/        # Domain simulators (Twitter, Uber, Netflix, etc.)
│   │   │   ├── ArchitectureBlueprintViewer.ts
│   │   │   ├── ArchitectureEvaluator.ts
│   │   │   ├── ArchitecturePresets.ts
│   │   │   ├── CapacityEstimator.ts
│   │   │   ├── CapacityPresetProfiles.ts
│   │   │   ├── FailureModeMatrix.ts
│   │   │   ├── InterviewHintsEngine.ts
│   │   │   ├── ScenarioBenchmarkRunner.ts
│   │   │   ├── ScenarioCatalog.ts
│   │   │   ├── ScenarioChallengeRunner.ts
│   │   │   └── SystemDesignQuizQuestions.ts
│   │   ├── ByzantineFaultInjector.ts
│   │   ├── CacheEvictionEngine.ts
│   │   ├── CircuitBreakerManager.ts
│   │   ├── ConsistentHashRing.ts
│   │   ├── DatabaseReplicationEngine.ts
│   │   ├── GeoDnsRouter.ts
│   │   ├── LoadBalancerEngine.ts
│   │   ├── MultiRegionLatencyEngine.ts
│   │   ├── NetworkPartitionMatrix.ts
│   │   ├── SimulationEngine.ts
│   │   └── types.ts
│   ├── hooks/                     # Custom React hooks (useSimulation)
│   ├── test/                      # Vitest test suites (22 suites, 81 tests)
│   │   └── interview/             # Comprehensive scenario & engine tests
│   ├── utils/                     # Alert helpers & formatting
│   ├── App.tsx                    # Main multi-tab application container
│   ├── index.css                  # Global Tailwind styles & dark scrollbars
│   └── main.tsx                   # Application entry point
├── dist/                          # Production build output
├── LICENSE                        # MIT License
├── package.json                   # Dependencies & scripts
├── tsconfig.json                  # TypeScript compiler options
├── vite.config.ts                 # Vite bundler configuration
└── README.md                      # Project documentation

🚀 Getting Started & Setup

Prerequisites

  • Node.js: v18.0.0 or higher
  • npm: v9.0.0 or higher (or pnpm / yarn)
  • Git

Installation

  1. Clone the repository:

    git clone https://github.com/Humaam-04-06/distributed-systems-simulator.git
    cd distributed-systems-simulator
  2. Install project dependencies:

    npm install

Running Locally

Start the Vite development server:

npm run dev

Open your browser and navigate to:

http://localhost:5173

You can now interact with all 10 simulation tabs:

  1. Topology Canvas: Drag, drop, and link nodes.
  2. Load Balancer: Consistent hashing ring and routing algorithms.
  3. Server Cluster: Horizontal scaling and node failures.
  4. Database Storage: Primary-replica replication and failover elections.
  5. Caching Tier: LRU/LFU eviction and cache stampede simulations.
  6. Resilience & Breakers: Circuit breaker state transitions and retry jitter.
  7. Bulkhead Isolation: Thread and connection pool boundaries.
  8. Chaos Lab: Network partitions and Byzantine fault injection.
  9. Multi-Region & Geo-DNS: Global subsea cable map and disaster drills.
  10. System Design Interview Sandbox: FAANG scenario challenges, napkin math, and architecture grading.

🧪 Testing

The project uses Vitest for unit and integration testing.

Run the test suite:

npm test

Run tests in watch mode (interactive development):

npm run test:watch

Test Suite Status

Test Files  22 passed (22)
     Tests  81 passed (81)
  Duration  ~1.7s

All 22 test suites pass with 100% success rate, including the end-to-end integration test (FullInterviewLifecycle.test.ts).


📦 Production Build

To verify TypeScript types and generate the optimized production bundle:

# Type check without emitting files
npx tsc --noEmit

# Build for production
npm run build

The optimized assets will be generated in the dist/ directory, ready to be served by any static web server or CDN.

To preview the production build locally:

npm run preview

👤 Author & License

  • Author: Humaam Ahmed (@Humaam-04-06)
  • License: Released under the MIT License. Free to use, modify, and distribute for educational, commercial, and interview preparation purposes.

About

⚡ High-scale distributed systems architecture, queuing models, chaos engineering & FAANG system design interview sandbox. Features interactive napkin-math calculators, real-time traffic engines, automated SLA evaluators, and production outage post-mortems.

Topics

Resources

Stars

6 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages