Library

Volume 1 · System Architecture & Distributed Systems

Notebook
Sign in

Section 3

Scalability Patterns

2,006 words · about 9 min

3.1 Vertical vs. Horizontal Scaling

flowchart LR
    subgraph Vertical["Vertical Scaling (Scale Up)"]
        S1["Single Server\n▲ RAM (128GB)\n▲ CPU (64 Cores)\n▲ NVMe SSD"]
    end

    subgraph Horizontal["Horizontal Scaling (Scale Out)"]
        LB["Load Balancer"]
        N1["Node 1 (33% load)"]
        N2["Node 2 (33% load)"]
        N3["Node 3 (33% load)"]
        LB --> N1
        LB --> N2
        LB --> N3
    end
Approach Pros Cons When to Use
Vertical Simple, zero code changes, no distributed state complexity Strict hardware ceiling, single point of failure (SPOF), exponential cost curve RDBMS before sharding, legacy monoliths that cannot be clustered, quick tactical capacity fixes
Horizontal Near-linear unlimited scale, high fault tolerance, commodity infrastructure Requires strictly stateless application architecture, distributed consistency overhead Web/API tiers, stateless microservices, read-heavy workloads, stream processors

Hybrid Architecture in Practice:

  • Stateless Compute: Horizontally auto-scaled behind load balancers from Day 1 using Auto Scaling Groups or Kubernetes HPAs.
  • Data Stores: Vertically scaled up initially (Read Replicas + beefier instances) until throughput or IOPS reach limits, after which horizontal sharding or distributed databases are introduced.

3.2 CQRS (Command Query Responsibility Segregation)

Separates write models (Commands) from read models (Queries), enabling each side to be independently scaled, optimized, and maintained.

flowchart LR
    Client["Client Request"]

    subgraph WritePath["Command Side (Writes)"]
        Command["Command Handler\n(Validation & Business Logic)"]
        WriteDB[("Write Database\n(Normalized / Relational)")]
    end

    subgraph MessageBus["Event Propagation"]
        Bus["Event Bus\n(Kafka / RabbitMQ / SQS)"]
    end

    subgraph ReadPath["Query Side (Reads)"]
        ReadDB[("Read Database / Cache\n(Denormalized / Elasticsearch / Redis)")]
        Query["Query Handler\n(Optimized Projections)"]
    end

    Client -->|POST / PUT / DELETE| Command
    Command -->|ACID Transaction| WriteDB
    WriteDB -.->|Domain Events| Bus
    Bus -->|Async Projection Worker| ReadDB
    Client -->|GET Queries| Query
    Query -->|Low-Latency Fast Fetch| ReadDB

When to Apply CQRS:

  • Asymmetric Traffic: Read-to-write ratios are heavily skewed (e.g., 100:1 read-to-write).
  • Complex Domain Validation: Write flows involve rich domain logic and validation, whereas read flows require flat, denormalized UI views.
  • Multiple Read Projections: A single write needs to feed multiple specialized read stores simultaneously (e.g., Elasticsearch for full-text search, Redis for leaderboards, and relational views for reporting).

When to Avoid CQRS:

  • Standard CRUD applications with simple read/write parity.
  • Teams without operational observability to manage eventual consistency lags and projection pipeline failures.

3.3 Event Sourcing

Instead of storing current state, Event Sourcing persists the append-only sequence of domain events that produced the state. Current state is deterministically derived by replaying the event stream.

flowchart LR
    subgraph EventStream["Append-Only Event Store"]
        E1["1. AccountCreated\n(Initial: $0)"]
        E2["2. MoneyDeposited\n(+$100)"]
        E3["3. MoneyDeposited\n(+$50)"]
        E4["4. MoneyWithdrawn\n(-$30)"]
        E1 --> E2 --> E3 --> E4
    end

    subgraph Replay["State Reconstruction"]
        State["Current Balance:\n$120.00"]
        E4 -.->|Fold / Replay Events| State
    end
public class BankAccount : EventSourcedAggregate
{
    public decimal Balance { get; private set; }

    public void Deposit(decimal amount)
    {
        if (amount <= 0) throw new DomainException("Amount must be positive");
        Apply(new MoneyDepositedEvent(Id, amount, DateTime.UtcNow));
    }

    public void Withdraw(decimal amount)
    {
        if (amount > Balance) throw new DomainException("Insufficient funds");
        Apply(new MoneyWithdrawnEvent(Id, amount, DateTime.UtcNow));
    }

    // Replayed to rebuild state
    private void On(MoneyDepositedEvent e) => Balance += e.Amount;
    private void On(MoneyWithdrawnEvent e) => Balance -= e.Amount;
}
// Event Store: [AccountCreated] → [Deposited $100] → [Deposited $50] → [Withdrawn $30]
// Current Balance = $120, rebuilt by replaying all events (or from a snapshot + delta)

Architectural Trade-offs:

  • Advantages: Complete immutable audit trail, point-in-time time-travel queries, and zero data loss from destructive updates.
  • Challenges: Event schema versioning over time, eventual consistency lag, and the necessity of periodic snapshotting to avoid replaying millions of historical records on every aggregate hydration.

3.4 Sharding (Horizontal Data Partitioning)

Splits large database tables across multiple physical database instances according to a specific shard key.

flowchart TD
    Router["Shard Router / Query Coordinator"]

    subgraph ShardTier["Physical Database Shards"]
        S1[("Shard 1 (Asia-Pacific)\nUser IDs: 1 – 10M")]
        S2[("Shard 2 (Europe)\nUser IDs: 10M – 20M")]
        S3[("Shard 3 (Americas)\nUser IDs: 20M+")]
    end

    Router -->|User ID Hash / Range| S1
    Router -->|User ID Hash / Range| S2
    Router -->|User ID Hash / Range| S3
Strategy How Pros Cons
Hash-based hash(key) % N shards Even distribution Range queries and resharding are expensive
Range-based Contiguous key ranges per shard Efficient range queries Hotspots if data/access isn’t uniform across ranges
Directory-based Lookup service maps key → shard Flexible, easy rebalancing Lookup service is a new single point of failure/bottleneck
Tenant-based One shard per tenant Strong isolation, easy compliance/GDPR deletes Uneven load if tenants vary wildly in size
Consistent Hashing Ring topology; nodes own hash ranges; virtual nodes smooth distribution Minimizes data movement when nodes are added/removed More complex to implement/reason about

Shard Key Selection Rules:

  • High Cardinality: Choose keys with massive variety (e.g., user_id or uuid) to avoid partition skews.
  • Avoid Low Entropy Attributes: Never partition on low-cardinality fields like status or country_code, which inevitably produce massive hot shards.

3.5 Caching Patterns

flowchart LR
    Client["Client / App"]
    CDN["Edge CDN"]
    GW["API Gateway Cache"]
    AppCache["Distributed Cache\n(Redis / Memcached)"]
    DB[("Primary Database")]

    Client --> CDN --> GW --> AppCache --> DB
Pattern Description Trade-off
Cache-Aside (Lazy Loading) App checks cache first; on miss, loads from DB and populates cache Most common; first request after expiry is always slow (“thundering herd” risk)
Read-Through Cache itself is responsible for loading from DB on a miss Simpler application code
Write-Through Write goes to cache and DB synchronously Strong cache/DB consistency, higher write latency
Write-Behind (Write-Back) Write goes to cache immediately, DB write is async Fast writes, risk of data loss if cache fails before flush
Refresh-Ahead Proactively refresh hot keys before TTL expiry Avoids cache-miss latency spikes for predictable access patterns
// Cache-aside example
public Product GetProduct(string productId)
{
    var cached = cache.Get(productId);
    if (cached != null) return cached;

    var product = productRepository.FindById(productId);
    cache.Set(productId, product, TimeSpan.FromMinutes(15));
    return product;
}

Cache invalidation strategies: TTL-based expiration (simplest, accept staleness); event-driven invalidation (publish on data change, consumer invalidates — real-time but needs messaging infra); version-based keys (cache key embeds a version number, no explicit invalidation needed, old versions just expire naturally). As Phil Karlton said: “There are only two hard things in Computer Science: cache invalidation and naming things.” In practice, TTL + event-driven invalidation covers the large majority of real cases.

3.6 Auto Scaling

# Target tracking — keep CPU at a target utilization
TargetTrackingScaling:
  TargetValue: 70
  ScaleOutCooldown: 300
  ScaleInCooldown: 300

# Step scaling — finer control over scaling magnitude by how far over threshold
StepScaling:
  - LowerBound: 0,  UpperBound: 20, ScalingAdjustment: 2
  - LowerBound: 20, UpperBound: 50, ScalingAdjustment: 4
  - LowerBound: 50,                 ScalingAdjustment: 8
# Kubernetes HorizontalPodAutoscaler
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: { name: order-api-hpa }
spec:
  scaleTargetRef: { apiVersion: apps/v1, kind: Deployment, name: order-api }
  minReplicas: 2
  maxReplicas: 20
  metrics:
  - type: Resource
    resource: { name: cpu, target: { type: Utilization, averageUtilization: 70 } }

3.7 Rate Limiting & Throttling Algorithms

Algorithm Description Use Case
Token Bucket Tokens added at a fixed rate; each request consumes a token; bucket allows bursts up to its capacity General-purpose API rate limiting
Leaky Bucket Requests processed at a strictly fixed output rate; excess is queued or dropped Traffic shaping, smoothing bursty input
Fixed Window Count requests within fixed time windows (e.g., per minute) Simple, but bursts at window boundaries
Sliding Window Log Track exact timestamp of every request Most precise, higher memory cost
Sliding Window Counter Weighted average of current + previous window counts Good balance of accuracy and cost
// Distributed sliding-window rate limiter using Redis sorted sets
public async Task<bool> IsAllowedAsync(string clientId, int maxRequests, TimeSpan window)
{
    var key = $"ratelimit:{clientId}";
    var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
    var windowStart = now - (long)window.TotalMilliseconds;

    var tx = _redis.CreateTransaction();
    _ = tx.SortedSetRemoveRangeByScoreAsync(key, 0, windowStart);
    _ = tx.SortedSetAddAsync(key, now.ToString(), now);
    var countTask = tx.SortedSetLengthAsync(key);
    _ = tx.KeyExpireAsync(key, window);
    await tx.ExecuteAsync();

    return await countTask <= maxRequests;
}

At extreme scale (100K+ RPS), exact distributed rate limiting via a central Redis becomes a bottleneck — use local, per-instance approximate limiters with periodic sync instead.

3.8 Section 3 — Interview Q&A

Q1: When would you introduce CQRS, and what’s the biggest mistake teams make when adopting it?

A: I introduce CQRS when there’s a real, measured asymmetry between read and write patterns — typically when reads outnumber writes by 10:1 or more, or when the read side needs a fundamentally different shape than the write side (e.g., a search-optimized denormalized view vs. a normalized transactional write model). The biggest mistake I see is teams adopting CQRS (often bundled with Event Sourcing) for a simple CRUD domain because it sounds architecturally sophisticated — it adds real operational cost: eventual consistency between write and read sides, more infrastructure (event bus, projection workers), and a debugging story that’s harder than “just query the database.” I only recommend it when the asymmetry or the audit-trail requirement is real and specific.

Q2: How do you choose a shard key, and what happens if you choose badly?

A: A good shard key distributes both data volume and access load evenly across shards, and ideally supports the most common query patterns without needing a cross-shard fan-out. A bad choice — like sharding by a low-cardinality “status” column — creates a hot shard: nearly all “Active” rows land on one shard, so that shard absorbs a disproportionate share of traffic while others sit idle, and adding more shards doesn’t help because the hot key space isn’t being split. My default is a high-cardinality, evenly distributed key like user ID or a hash of it, and I explicitly check the access pattern for “will 90% of queries filter or join on this key” before committing, because resharding a live production system afterward is one of the more disruptive migrations you can undertake.

Q3: Explain the trade-offs between cache-aside and write-through caching.

A: Cache-aside is the more common default: the application checks the cache, and on a miss, loads from the database and populates the cache — writes go straight to the database and the cache is left to expire or be explicitly invalidated. It’s simple and resilient to cache failures (a cold cache just means a temporary latency hit, not an outage), but the very first read after an update can be stale until invalidation happens, and a cold start can cause a “thundering herd” of simultaneous cache misses. Write-through keeps the cache and database in lockstep by writing to both synchronously — reads are always consistent with the latest write, but every write now pays the latency cost of the cache write too, and if the cache is unavailable, writes may fail or need a fallback path. I default to cache-aside for most read-heavy data and reserve write-through for a narrow set of keys where staleness is unacceptable even for a few seconds.

Q4: How would you design auto-scaling for a service with a sudden, predictable daily traffic spike (e.g., 9am login rush)?

A: I’d combine reactive and predictive scaling. Reactive: a target-tracking policy on CPU or request-queue-length keeps a baseline safety net for unpredictable spikes. Predictive: since the spike is known and recurring, I’d add a scheduled scaling action that pre-warms capacity 10–15 minutes before 9am, because reactive auto-scaling always lags behind the actual spike by the time it takes new instances to boot, pass health checks, and receive traffic — for a stateless container that might be under a minute, but for anything with a slower cold start (JVM warm-up, connection pool initialization) it can be several minutes, which is exactly when users are hitting login failures. I’d also make sure downstream dependencies (auth service, database connection pool limits) are sized to handle the pre-warmed capacity, since scaling the front tier without checking the backend just moves the bottleneck.