miles990-claude-software-skills-system-design.ocm.json json Copy{
"ocm" : "1" ,
"id" : "miles990-claude-software-skills-system-design" ,
"kind" : "skill" ,
"name" : "system-design" ,
"description" : "Scalability, availability, and distributed systems design" ,
"publisher" : "miles990" ,
"version" : "1.0.0" ,
"capabilities" : {
"domains" : [
"coding"
],
"tags" : [
"skill-md" ,
"scalability" ,
"availability" ,
"distributed" ,
"caching" ,
"load-balancing" ,
"database" ,
"skills-sh"
],
"languages" : [
"en"
]
},
"quality_prior" : 0.6 ,
"examples" : [
"Scalability, availability, and distributed systems design"
],
"primary" : false ,
"metadata" : {
"source" : {
"provider" : "skills.sh" ,
"repository" : "https://github.com/miles990/claude-software-skills" ,
"path" : "software-design/system-design/SKILL.md" ,
"ref" : "HEAD" ,
"url" : "https://github.com/miles990/claude-software-skills/blob/HEAD/software-design/system-design/SKILL.md" ,
"key" : "miles990/claude-software-skills/software-design/system-design/SKILL.md"
}
},
"instructions" : "# System Design\n\n## Overview\n\nPrinciples for designing systems that handle scale, remain available, and perform well under load.\n\n---\n\n## Scalability Fundamentals\n\n### Vertical vs Horizontal Scaling\n\n```\nVertical Scaling (Scale Up):\n┌─────────────────────┐\n│ Bigger Server │\n│ - More CPU │\n│ - More RAM │\n│ - Faster disk │\n└─────────────────────┘\nLimit: Hardware ceiling\n\nHorizontal Scaling (Scale Out):\n┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐\n│Server│ │Server│ │Server│ │Server│\n└──────┘ └──────┘ └──────┘ └──────┘\n ↑\n Load Balancer\nLimit: Coordination complexity\n```\n\n### Stateless Services\n\n```typescript\n// ❌ Stateful - stores session in memory\nclass BadService {\n private sessions = new Map();\n\n login(userId: string) {\n this.sessions.set(userId, { loggedIn: true });\n }\n}\n\n// ✅ Stateless - external session store\nclass GoodService {\n constructor(private sessionStore: Redis) {}\n\n async login(userId: string) {\n await this.sessionStore.set(`session:${userId}`, { loggedIn: true });\n }\n}\n```\n\n---\n\n## Load Balancing\n\n### Strategies\n\n| Strategy | Description | Use Case |\n|----------|-------------|----------|\n| Round Robin | Cycle through servers | Equal capacity servers |\n| Weighted RR | Based on server capacity | Mixed capacity |\n| Least Connections | Route to least busy | Long-lived connections |\n| IP Hash | Same IP → same server | Session stickiness |\n| URL Hash | Same URL → same server | Cache optimization |\n\n### Health Checks\n\n```yaml\n# Kubernetes-style health checks\nlivenessProbe:\n httpGet:\n path: /health/live\n port: 8080\n initialDelaySeconds: 3\n periodSeconds: 10\n\nreadinessProbe:\n httpGet:\n path: /health/ready\n port: 8080\n initialDelaySeconds: 5\n periodSeconds: 5\n```\n\n```typescript\n// Health check endpoints\napp.get('/health/live', (req, res) => {\n // Am I running?\n res.status(200).json({ status: 'alive' });\n});\n\napp.get('/health/ready', async (req, res) => {\n // Can I serve traffic?\n const dbOk = await checkDatabase();\n const cacheOk = await checkCache();\n\n if (dbOk && cacheOk) {\n res.status(200).json({ status: 'ready' });\n } else {\n res.status(503).json({ status: 'not ready', db: dbOk, cache: cacheOk });\n }\n});\n```\n\n---\n\n## Caching Strategies\n\n### Cache Patterns\n\n```\nCache-Aside (Lazy Loading):\n┌────────┐ miss ┌────────┐\n│ App │ ──────────→ │ Cache │\n│ │ ←────────── │ │\n└────────┘ null └────────┘\n │\n │ read\n ↓\n┌────────┐\n│ DB │ ──── write ──→ Cache\n└────────┘\n\nWrite-Through:\nApp → Cache → DB (synchronous)\n\nWrite-Behind (Write-Back):\nApp → Cache → (async) → DB\n```\n\n```typescript\n// Cache-aside implementation\nclass CachedUserService {\n constructor(\n private cache: Redis,\n private db: Database\n ) {}\n\n async getUser(id: string): Promise<User> {\n // Try cache first\n const cached = await this.cache.get(`user:${id}`);\n if (cached) return JSON.parse(cached);\n\n // Cache miss - read from DB\n const user = await this.db.users.findById(id);\n if (user) {\n // Store in cache with TTL\n await this.cache.set(`user:${id}`, JSON.stringify(user), 'EX', 3600);\n }\n return user;\n }\n\n async updateUser(id: string, data: Partial<User>): Promise<User> {\n const user = await this.db.users.update(id, data);\n // Invalidate cache\n await this.cache.del(`user:${id}`);\n return user;\n }\n}\n```\n\n### Cache Invalidation\n\n| Strategy | Description | Complexity |\n|----------|-------------|------------|\n| TTL | Expire after time | Simple |\n| Event-based | Invalidate on write | Medium |\n| Version-based | Key includes version | Medium |\n| Tag-based | Group related keys | Complex |\n\n---\n\n## Database Scaling\n\n### Read Replicas\n\n```\n ┌─────────────────┐\n Writes ──────→ │ Primary DB │\n └────────┬────────┘\n │ replication\n ┌─────────────────┼─────────────────┐\n ↓ ↓ ↓\n ┌──────────┐ ┌──────────┐ ┌──────────┐\n │ Replica 1│ │ Replica 2│ │ Replica 3│\n └──────────┘ └──────────┘ └──────────┘\n ↑ ↑ ↑\n └─────── Reads ───┴────────────────┘\n```\n\n### Sharding (Partitioning)\n\n```typescript\n// Hash-based sharding\nfunction getShard(userId: string, numShards: number): number {\n const hash = crypto.createHash('md5').update(userId).digest('hex');\n return parseInt(hash.slice(0, 8), 16) % numShards;\n}\n\n// Range-based sharding\nfunction getShardByDate(date: Date): string {\n const year = date.getFullYear();\n const month = date.getMonth() + 1;\n return `orders_${year}_${month.toString().padStart(2, '0')}`;\n}\n\n// Consistent hashing for dynamic shards\nclass ConsistentHash {\n private ring: Map<number, string> = new Map();\n\n addNode(node: string) {\n for (let i = 0; i < 150; i++) { // Virtual nodes\n const hash = this.hash(`${node}:${i}`);\n this.ring.set(hash, node);\n }\n }\n\n getNode(key: string): string {\n const hash = this.hash(key);\n // Find next node on ring\n for (const [nodeHash, node] of [...this.ring.entries()].sort()) {\n if (nodeHash >= hash) return node;\n }\n return this.ring.values().next().value;\n }\n}\n```\n\n---\n\n## Message Queues\n\n### Patterns\n\n```\nPoint-to-Point:\nProducer → Queue → Consumer\n\nPub/Sub:\n ┌─→ Subscriber 1\nPublisher → Topic ─→ Subscriber 2\n └─→ Subscriber 3\n\nWork Queue:\n ┌─→ Worker 1\nProducer → Queue ─→ Worker 2 (competing consumers)\n └─→ Worker 3\n```\n\n### Delivery Guarantees\n\n| Guarantee | Description | Implementation |\n|-----------|-------------|----------------|\n| At-most-once | May lose messages | Fire and forget |\n| At-least-once | May duplicate | Ack after process |\n| Exactly-once | No loss, no dupe | Idempotency + dedup |\n\n```typescript\n// Idempotent processing\nasync function processOrder(event: OrderEvent) {\n // Check if already processed\n const processed = await redis.get(`processed:${event.id}`);\n if (processed) {\n console.log(`Already processed ${event.id}`);\n return;\n }\n\n // Process the order\n await db.orders.create(event.order);\n\n // Mark as processed (with TTL for cleanup)\n await redis.set(`processed:${event.id}`, '1', 'EX', 86400 * 7);\n}\n```\n\n---\n\n## High Availability\n\n### Redundancy Patterns\n\n```\nActive-Active:\n┌────────┐ ┌────────┐\n│Server A│ ←─→ │Server B│ Both handle traffic\n└────────┘ └────────┘\n\nActive-Passive:\n┌────────┐ ┌────────┐\n│ Active │ ──→ │Standby │ Failover on failure\n└────────┘ └────────┘\n```\n\n### Circuit Breaker\n\n```typescript\nclass CircuitBreaker {\n private failures = 0;\n private lastFailure: Date | null = null;\n private state: 'closed' | 'open' | 'half-open' = 'closed';\n\n constructor(\n private threshold: number = 5,\n private timeout: number = 30000\n ) {}\n\n async execute<T>(fn: () => Promise<T>): Promise<T> {\n if (this.state === 'open') {\n if (Date.now() - this.lastFailure!.getTime() > this.timeout) {\n this.state = 'half-open';\n } else {\n throw new Error('Circuit is open');\n }\n }\n\n try {\n const result = await fn();\n this.onSuccess();\n return result;\n } catch (error) {\n this.onFailure();\n throw error;\n }\n }\n\n private onSuccess() {\n this.failures = 0;\n this.state = 'closed';\n }\n\n private onFailure() {\n this.failures++;\n this.lastFailure = new Date();\n if (this.failures >= this.threshold) {\n this.state = 'open';\n }\n }\n}\n```\n\n---\n\n## CAP Theorem\n\n```\n Consistency\n /\\\n / \\\n / \\\n / \\\n / CA \\\n /──────────\\\n / \\\n / CP AP \\\n /________________\\\nPartition Availability\nTolerance\n\nCA: Single node (RDBMS)\nCP: MongoDB, HBase (may reject writes during partition)\nAP: Cassandra, DynamoDB (eventual consistency)\n```\n\n### Consistency Models\n\n| Model | Description | Example |\n|-------|-------------|---------|\n| Strong | Read sees latest write | RDBMS |\n| Eventual | Eventually consistent | DNS, Cassandra |\n| Causal | Respects causality | Chat apps |\n| Read-your-writes | See your own writes | Social feeds |\n\n---\n\n## Rate Limiting\n\n### Algorithms\n\n```typescript\n// Token Bucket\nclass TokenBucket {\n private tokens: number;\n private lastRefill: number;\n\n constructor(\n private capacity: number,\n private refillRate: number // tokens per second\n ) {\n this.tokens = capacity;\n this.lastRefill = Date.now();\n }\n\n consume(tokens: number = 1): boolean {\n this.refill();\n if (this.tokens >= tokens) {\n this.tokens -= tokens;\n return true;\n }\n return false;\n }\n\n private refill() {\n const now = Date.now();\n const elapsed = (now - this.lastRefill) / 1000;\n this.tokens = Math.min(\n this.capacity,\n this.tokens + elapsed * this.refillRate\n );\n this.lastRefill = now;\n }\n}\n\n// Sliding Window\nclass SlidingWindowRateLimiter {\n constructor(\n private redis: Redis,\n private limit: number,\n private window: number // seconds\n ) {}\n\n async isAllowed(key: string): Promise<boolean> {\n const now = Date.now();\n const windowStart = now - this.window * 1000;\n\n const pipe = this.redis.pipeline();\n pipe.zremrangebyscore(key, 0, windowStart);\n pipe.zadd(key, now, `${now}`);\n pipe.zcard(key);\n pipe.expire(key, this.window);\n\n const results = await pipe.exec();\n const count = results[2][1] as number;\n\n return count <= this.limit;\n }\n}\n```\n\n---\n\n## Common System Designs\n\n| System | Key Components |\n|--------|----------------|\n| URL Shortener | Hash function, Redis cache, DB |\n| Twitter Feed | Fan-out, Redis timeline, Kafka |\n| Chat App | WebSocket, Presence, Message queue |\n| E-commerce | Cart service, Inventory, Payment |\n| Video Streaming | CDN, Chunking, Adaptive bitrate |\n\n---\n\n## Related Skills\n\n- [[architecture-patterns]] - Microservices, event-driven\n- [[database]] - Database optimization\n- [[caching-implementation]] - Cache strategies\n- [[reliability-engineering]] - SRE practices" ,
"cost" : {
"context_tokens" : 2532
}
}