- Components: HTTP server + Database on same machine
- Issue: Single point of failure
- Use: Only for very small applications
- Approach: Move database to separate server
- Benefit: Reduces single point of failure slightly
- Limitation: Still limited scalability
- Definition: Adding more resources to a single server (CPU, RAM, storage)
- Limitations:
- Servers have physical limits
- Still creates single points of failure
- Eventually reaches cost/performance ceiling
- Definition: Adding more servers to distribute load
- Key Requirement: Stateless web servers
- Benefits:
- Can scale indefinitely
- Better fault tolerance
- More cost-effective at scale
- Consideration: Choose simplest architecture that meets projected traffic requirements
- On-Premises: Company-owned data centers
- Cloud Services:
- Amazon EC2
- Google Compute Engine
- Azure VMs
- Serverless: Lambda, Kinesis, Athena
- Method: Periodic backups to standby server
- Recovery Time: Slowest
- Data Loss: Possible (up to last backup)
- Cost: Lowest
- Method: Continuous replication to standby
- Recovery Time: Moderate
- Data Loss: Minimal
- Cost: Moderate
- Method: Real-time active standby server
- Recovery Time: Fast (near instant)
- Data Loss: None
- Cost: Higher
- Method: Multiple active primary servers
- Recovery Time: Immediate (no failover needed)
- Benefit: Load distribution + high availability
- Complexity: Highest
- Definition: Splitting database across multiple servers
- Components:
- Client & request router
- Multiple shards (Shard 1, 2, 3...N)
- Challenges:
- Difficult to do joins across shards
- Resharding complexity
- Hotspot problems (uneven distribution)
- Structure: Replica Sets (RS) with Primary + Secondaries
- Components:
- mongos process (query router)
- Config servers
- Multiple replica sets per shard range
- Example Sharding:
- RS1: users min → 1000
- RS2: users 1000 → 5000
- RS3: users 5000 → max
- Architecture: No single master
- Consistency: Eventually consistent
- Benefit: High availability, partition tolerance
- Challenges:
- Tough to do joins across shards
- Resharding difficulties
- Hotspot issues
- Best For:
- Simple key/value lookups
- Applications where formal schema not needed
- SQL Support: Most NoSQL databases actually support SQL operations
- Examples: MongoDB, DynamoDB, Cassandra, HBase
- Pros: Less storage space, updates in one place
- Cons: More lookups required
- Pros: Single lookup, faster reads
- Cons: More storage, updates are hard, data redundancy
- Storage: Amazon S3 (or equivalent)
- Format: CSV, JSON files in distributed storage
- Schema Creation: Amazon Glue
- Querying:
- Amazon Athena (serverless)
- Amazon Redshift (distributed data warehouse)
- Performance: Requires careful data partitioning
- Atomicity: Transaction succeeds completely or fails completely
- Consistency: All database rules enforced, or transaction rolled back
- Isolation: Transactions don't affect each other
- Durability: Committed transactions persist even after crashes
- Consistency: All nodes see same data
- Availability: System remains operational
- Partition Tolerance: System works despite network failures
- CP (Consistency + Partition Tolerance):
- HBase
- MongoDB (in strongly consistent mode)
- Amazon DynamoDB
- AP (Availability + Partition Tolerance):
- Cassandra
- CA (Consistency + Availability):
- MySQL (when not distributed)
- Client-side caching: Browser cache
- CDN caching: Geographic distribution
- Application server cache: In-memory cache
- Database cache: Query result caching
- Horizontally scaled cache servers
- Client hashing: Requests distributed to specific servers
- In-memory storage: Fast access
- Applications with more reads than writes
- Expiration Policy:
- Too long: Data goes stale
- Too short: Cache ineffective
- Hotspot Problem: Celebrity problem (uneven distribution)
- Cold Start: How to warm up cache initially
- LRU (Least Recently Used): Evict items not accessed recently
- LFU (Least Frequently Used): Evict items accessed least often
- FIFO (First In First Out): Evict oldest items first
- Uses Doubly Linked List + Hash Table
- O(1) operations for get and put
- Type: In-memory key/value store
- Features:
- Snapshots, replication, transactions, pub/sub
- Advanced data structures
- Open source
- Complexity: More complex than Memcached
- Type: Simple distributed caching
- Benefit: Easy to use
- Languages: .NET, Java, Node.js
- Type: Distributed Map
- Languages: Java
- Type: Fully-managed Redis or Memcached
- Benefit: AWS-managed solution
- Geographic Distribution: Edge locations worldwide
- Content Types:
- JavaScript files
- Images
- Static web pages
- Limited computation
- Cloudflare
- Google Cloud CDN
- Microsoft Azure CDN
- Single server
- Entire rack
- Entire data center (availability zone)
- Entire region
- Beyond regional (catastrophic)
- Geographic Distribution: NA, EU, India, etc.
- Load Balancing: Route traffic to nearest/healthiest region
- Failover: Automatic routing to healthy regions
- Spread secondaries across:
- Multiple racks
- Multiple availability zones
- Multiple regions
- Overprovisioning: Ensure capacity to survive failures
- Budget vs. Availability: Balance cost and reliability
- Alternative: Offsite backups with slower provisioning
- Scalable object storage
- High availability
- Security
- Fast access
- Data lakes
- Websites
- Backups
- Big data analytics
- Durability: 99.999999999% (11 nines)
- Meaning: 0.000000001% chance of data loss
- 99% availability: 3.65 days downtime/year
- 99.9999% (6 nines): ~30 seconds downtime/year
- Example: "3 nines latency" = 100ms
- Meaning: 99.9% of requests complete within 100ms
- Access: Frequent
- Cost: Higher
- Speed: Fastest
- Access: Infrequent
- Cost: Moderate
- Speed: Moderate
- Access: Archival
- Cost: Lowest
- Speed: Slowest (hours to retrieve)
- Amazon S3 (+ Glacier)
- Google Cloud Storage
- Microsoft Azure
- Hadoop HDFS (self-hosted)
- Consumer: Dropbox, Box, Google Drive (not for system design)
- Name Node: Coordinates operations, stores metadata
- Data Nodes: Store actual data blocks
- Rack Awareness: Replication across racks
- Files broken into blocks
- Blocks replicated across cluster
- Clients read from nearest replica
- Writes replicated across different racks
- High availability with 3+ name nodes
- Access: O(n)
- Insert at head: O(1)
- Insert at end: O(n)
- Best for: Sequential access, stacks (LIFO), queues (FIFO)
- Memory: Low (one pointer per node)
- Structure: Next + Previous pointers
- Insert front/back: O(1)
- Access: O(n)
- Use cases: Deques, MRU (Most Recently Used)
- Structure: Each node has left and right child
- Access: O(log n) average, O(n) worst case
- Insert/Delete: O(log n)
- Best for: In-order traversals, sorted data
- Components: Hash function, Buckets, Collision handling
- Operations: O(1) average, O(n) worst case
- Use: Fast lookups needed
- Challenge: Hash collisions
- Components: Nodes (vertices) and Edges
- Traversal: BFS (Breadth-First Search), DFS (Depth-First Search)
- Access: O(V+E) where V=vertices, E=edges
- Use cases: Social networks, routing, networks
- Method: Iterate from beginning to end
- Complexity: O(n)
- Requirement: No special structure needed
- Method: Divide array in half repeatedly
- Complexity: O(log n)
- Requirement: Sorted array
- Insertion Sort: O(n) best, O(n²) worst - good for small/mostly-sorted
- Merge Sort: O(n log n) - scales well to large lists
- Quick Sort: O(n log n) average, O(n²) worst - very fast usually
- Bubble Sort: O(n²) - simple but inefficient
- Structure: Document ID → Keywords
- Example: Document 123 => "the quick red fox"
- Considerations: Capitalization, punctuation, offensive terms, phrases
- Signals: Position, formatting, relevance indicators
- Structure: Keywords → Document IDs + Positions
- Example:
- "Palm tree" → (432,1), (36,1235), (432,55)
- "Dinosaur" → (22,2), (22,253), (724,4342)
- Term Frequency (TF): How often word appears in a document
- Document Frequency (DF): How often word appears across all documents
- Inverse Document Frequency (IDF): 1/DF
Relevance Score = Term Frequency / Document Frequency
or
TF-IDF = TF × IDF
- Identifies important and unique words for each document
- Common words (a, the, and) get low scores
- Unique, frequent words get high scores
- Compute TF-IDF for every word in corpus
- For search word, sort documents by TF-IDF score
- Display results
- Inspiration: Academic paper citations
- Key Ideas:
- Analyze backlinks to a page
- Use anchor text as additional keywords
- Weight by number of links on referring page
- Apply dampening factor
PR(A) = (1-d) + d × (PR(T₁)/C(T₁) + ... + PR(Tₙ)/C(Tₙ))
Where:
- PR = PageRank
- d = dampening factor
- T = referring pages
- C = count of outbound links
- Google has moved beyond PageRank and TF-IDF
- Deep learning plays major role in ranking
- Decoupling: Separates producers from consumers
- Buffering: Handles consumer backups gracefully
- Asynchronous Processing: Producers don't wait for consumers
- Publishers/Producers: Send messages
- Queue: Stores messages temporarily
- Subscribers/Consumers: Process messages
- Single-consumer: One consumer per message
- Pub/Sub: Multiple consumers can receive same message
- Message Queues: Task-based, async processing
- Streaming Data: Real-time, massive continuous data
- Amazon SQS: Simple Queue Service
- Type: Distributed processing framework for big data
- Languages: Scala, Python, Java, R
- Storage: In-memory caching
- Not for: OLTP (Online Transaction Processing)
- Up to 100x faster than MapReduce
- Code reuse across different workloads
- Optimized query execution
- Structured data processing
- JDBC, ODBC support
- Formats: JSON, HDFS, ORC, Parquet
- Machine learning library
- Classification, regression, clustering
- Collaborative filtering
- Pattern mining
- Graph processing
- ETL, analysis, iterative graph computation
- Note: No longer widely used
- Real-time streaming analytics
- Sources: Twitter, Kafka, Flume, HDFS, ZeroMQ
- Structured streaming
- Driver Program: Contains SparkContext
- Cluster Manager: Coordinates resources (YARN, Mesos, Standalone)
- Executors: Run computations and store data
- Tasks: Individual units of work
- SparkContext coordinates independent processes
- Works through Cluster Manager
- Sends application code and tasks to executors
- Executors run computations and cache data
| Service | AWS | Google Cloud | Azure |
|---|---|---|---|
| Storage | S3 | Cloud Storage | Disk/Blob/Data Lake |
| Compute | EC2 | Compute Engine | Virtual Machines |
| NoSQL | DynamoDB | Bigtable | CosmosDB/Table Storage |
| Containers | Kubernetes/ECR/ECS | Kubernetes | Kubernetes |
| Streams | Kinesis | DataFlow | Stream Analytics |
| Big Data | EMR | Dataproc | Databricks |
| Data Warehouse | Redshift | BigQuery | Azure SQL/Database |
| Caching | ElastiCache (Redis) | Memorystore | Redis |
- Source: Server logs
- Stream: Kinesis Data Firehose
- Storage: Amazon S3
- Schema: AWS Glue (ETL)
- Query Options:
- Amazon Athena (serverless)
- Amazon Redshift (managed)
- Combines on-premises (private cloud) with public cloud
- Easy scaling of on-premises systems
- Meets regulations requiring on-premises data
- Flexibility and cost optimization
- Bridges between data center and cloud
- Implementation varies by provider
- Using more than one public cloud provider
- Reduces vendor lock-in
- Increases complexity
- Large Language Models (LLMs)
- Text-to-image generation
- Foundation models
- Input: System prompt + User prompt
- Processing: Large Language Model (GPT, Claude, Llama, Gemini)
- Output: Generated response
from openai import OpenAI
client = OpenAI()
client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "Always talk like a pirate."},
{"role": "user", "content": "What is the meaning of life?"},
]
)- Image Generation: Create images from text
- Moderation: Content filtering
- Speech to Text: Audio transcription
- Fine Tuning: Extend training with custom data
- Embedding: Create semantic vectors
- Modern LLMs have large context windows
- Include relevant data with prompt
- Maintain chat history by appending
- Costs: Charged per token
- Big context = Higher costs
- Guide answers
- Include proprietary data
- Provide examples
- "Open-book exam" for LLMs
- Query external database for relevant information
- Include search results in prompt as context
- Incorporates data not in LLM training
- Reduces hallucinations
- Easy to add new data
- User asks question
- System queries (vector) database
- Retrieved information added to prompt
- LLM generates response with context
- Vector representation of data
- Point in multi-dimensional space (100s-1000s of dimensions)
- Similar items are close in this space
- Encodes "meaning" or semantics
- Enables similarity search
- Foundation for RAG systems
- Use embedding APIs (OpenAI, etc.)
- Compute en masse for entire dataset
- Store data alongside embedding vectors
- Enable semantic search (K-Nearest Neighbor)
- Compute embedding for search query
- Query vector database
- Return top-N most similar items
- "Vector search"
Adapted Existing Databases:
- Elasticsearch
- SQL databases
- Neptune
- Redis
- MongoDB
- Cassandra
Purpose-Built Vector DBs:
- Commercial: Pinecone, Weaviate
- Open Source: Chroma, Marqo, Vespa, Qdrant, LanceDB, Milvus, vectordb
1. User Query: "Data, tell me about your daughter Lal"
2. Compute embedding vector for query
3. Search vector database of Star Trek script lines
4. Retrieve similar lines mentioning Lal
5. Construct prompt:
"You are Commander Data from Star Trek.
How might Data respond to 'tell me about your daughter Lal'
taking into account the following related lines: [retrieved context]"
6. LLM generates response
- Memory: Chat history + external data stores
- Planning Module: Break questions into sub-questions
- Tools: Functions LLM can use
- Agent Core: Coordinates everything
- Just functions provided to API
- Prompts guide LLM on tool usage
- Can access external information, services, APIs
- Standard for connecting tools to agents
- Enables consistent tool integration
- User makes request
- Planning module breaks down task
- Agent selects appropriate tools
- Tools execute and return results
- Agent synthesizes final response
- Repeat the question
- Confirm understanding with interviewer
- ASK LOTS OF QUESTIONS
- THINK OUT LOUD
- Given vague problem (e.g., "Design YouTube")
- Must turn into concrete requirements
- Start from customer experience
- Highly valued at Amazon, but works generally
- How will users discover videos?
- Need search engine?
- Recommender engine?
- Advertising engine?
- Identify WHO: The customers
- Determine WHAT: Their use cases
- Decide WHICH: Use cases to focus on
- Scope: You can't design all of YouTube in 20 minutes
- Defines clear requirements
- Limits scope appropriately
- Focuses on customer value
- Shows strategic thinking
- What should the system do?
- What features are needed?
- What user actions are supported?
- Scale: Users, requests per second, data size
- Performance: Latency requirements, throughput
- Availability: Uptime requirements (99.9%? 99.99%?)
- Consistency: Strong vs. eventual consistency
- Security: Authentication, authorization, encryption
- Load balancing
- Caching strategy
- Database choice and scaling
- API design
- Monitoring and logging
- Disaster recovery
- Jumping to solutions without understanding requirements
- Ignoring trade-offs
- Not asking about scale
- Not considering failure scenarios
- Over-engineering or under-engineering
- Simplest that works: Choose simplest architecture meeting requirements, but no simpler
- Ask questions: Always clarify requirements before proposing solutions
- Think about scale: Understand consistency, availability, and scalability needs
- Plan for failure: Every component can fail - plan accordingly
- Consider trade-offs: CAP theorem, cost vs. availability, consistency vs. performance
- Scalability: Horizontal vs. vertical scaling
- Reliability: Redundancy, failover, disaster recovery
- Performance: Caching, CDNs, database optimization
- Maintainability: Monitoring, logging, debugging
- Security: Authentication, authorization, encryption
- Cost: Infrastructure, operational, development costs