14.1 Vertical vs Horizontal Scaling
Vertical Scaling (Scale Up): Horizontal Scaling (Scale Out):
┌──────────────┐ ┌──────┐ ┌──────┐ ┌──────┐
│ Bigger │ │Node 1│ │Node 2│ │Node 3│
│ Server │ │ 1/3 │ │ 1/3 │ │ 1/3 │
│ (More CPU, │ │ data │ │ data │ │ data │
│ RAM, SSD) │ └──────┘ └──────┘ └──────┘
└──────────────┘
Simpler, has a hard ceiling More complex, near-unlimited headroom
14.2 Read Replicas
┌──────────────┐
Writes ─────────▶│ Primary │
│ (Leader) │
└──────┬───────┘
Async replication
┌──────┼───────┐
▼ ▼ ▼
┌────────┐┌────────┐┌────────┐
Reads ────▶│Replica ││Replica ││Replica │
│ 1 ││ 2 ││ 3 │
└────────┘└────────┘└────────┘
Read replicas scale read throughput horizontally, but reads from a replica are subject to replication lag — a write to the primary may not be visible on a replica for milliseconds to seconds. Route “read-your-own-write” scenarios (e.g., a user viewing the order they just placed) to the primary or use a session-consistency mechanism.
14.3 Sharding Strategies
| Strategy | How | Pros | Cons |
|---|---|---|---|
| Hash-based | hash(key) % N determines the shard |
Even distribution across shards | Cross-shard queries and range scans become hard; resharding requires rehashing most keys |
| Range-based | Contiguous key ranges assigned to shards | Efficient range queries | Hot spots — sequential keys (e.g., auto-increment IDs, recent timestamps) pile onto one shard |
| Directory-based | A lookup table maps key → shard | Flexible rebalancing, easy to move individual keys | The directory itself becomes a bottleneck/SPOF unless made highly available |
| Tenant-based | One shard (or shard group) per tenant | Strong isolation, straightforward compliance story | Uneven load if tenant sizes vary widely; needs a placement/rebalancing strategy for growth |
14.4 Connection Pooling
Connection pooling avoids the cost of establishing a new DB connection (TCP handshake, auth, TLS negotiation) per request by reusing a fixed pool of long-lived connections.
// Connection pooling is built into most .NET data providers via the connection string
"Server=db;Database=orders;Max Pool Size=100;Min Pool Size=10;Connection Timeout=15"
# SQLAlchemy connection pooling
from sqlalchemy import create_engine
engine = create_engine(
"postgresql://user:pass@db/orders",
pool_size=20, # steady-state connections kept open
max_overflow=10, # extra connections allowed under burst load
pool_timeout=30, # seconds to wait for a free connection before erroring
pool_recycle=1800, # recycle connections older than 30 min (avoids stale conns)
)
Common pitfall: sizing the connection pool per service instance without accounting for total instance count — 20 pods × a pool of 100 connections can easily exceed the database’s max_connections limit. A pooler/proxy layer (PgBouncer, RDS Proxy) in front of the database is the standard fix at scale — it multiplexes many client connections onto a smaller number of actual DB connections.
14.5 Materialized Views
A materialized view stores the result of a query physically, refreshed on a schedule or on demand, trading staleness for read speed — especially valuable for expensive aggregations that would otherwise be recomputed on every request.
CREATE MATERIALIZED VIEW mv_daily_order_totals AS
SELECT customer_id, DATE(created_at) AS order_date, SUM(total) AS daily_total
FROM orders
GROUP BY customer_id, DATE(created_at);
CREATE UNIQUE INDEX ON mv_daily_order_totals (customer_id, order_date);
-- Refresh strategies:
REFRESH MATERIALIZED VIEW mv_daily_order_totals; -- blocking
REFRESH MATERIALIZED VIEW CONCURRENTLY mv_daily_order_totals; -- non-blocking, needs the unique index above
14.6 Caching Patterns with Redis
| Pattern | Description | Use When |
|---|---|---|
| Cache-Aside | Application checks cache first; on a miss, loads from DB and populates the cache | Most common, general-purpose default |
| Read-Through | Cache itself loads from the DB automatically on a miss | Simplifies app code; cache library/proxy owns the loading logic |
| Write-Through | Write goes to cache and DB together, synchronously | Strong consistency between cache and DB needed |
| Write-Behind (write-back) | Write goes to cache immediately, DB write happens asynchronously | High write throughput, some risk of data loss on crash before flush |
| Refresh-Ahead | Cache proactively refreshes an entry before its TTL expires | Predictable, hot-key access patterns where a cache miss would be costly |
// Cache-aside with HybridCache (.NET 9) — L1 in-process + L2 Redis
builder.Services.AddHybridCache(options =>
{
options.DefaultEntryOptions = new HybridCacheEntryOptions
{
Expiration = TimeSpan.FromMinutes(5),
LocalCacheExpiration = TimeSpan.FromMinutes(1)
};
});
public class ProductService
{
private readonly HybridCache _cache;
public async Task<Product> GetProductAsync(int id) =>
await _cache.GetOrCreateAsync($"product:{id}",
async cancel => await _db.Products.FindAsync(id, cancel),
tags: ["products"]);
public async Task UpdateProductAsync(Product product)
{
await _db.SaveChangesAsync();
await _cache.RemoveByTagAsync("products"); // event-based invalidation
}
}
# Cache-aside pattern in Python with redis-py
import json
import redis
r = redis.Redis()
def get_product(product_id: str) -> dict:
cached = r.get(f"product:{product_id}")
if cached:
return json.loads(cached)
product = db.query_product(product_id) # cache miss -> load from source of truth
r.setex(f"product:{product_id}", 600, json.dumps(product)) # 10-min TTL
return product
def update_product(product: dict) -> None:
db.save_product(product)
r.delete(f"product:{product['id']}") # invalidate on write
Cache invalidation strategies:
- TTL — simplest, accept bounded staleness.
- Event-based invalidation — publish an event on data change, consumers invalidate the relevant keys; near-real-time but needs messaging infrastructure.
- Write-through + explicit invalidation — strongest consistency, most complex to manage cache-dependency graphs.
- Version-based keys — include a version in the cache key and bump it on change; old versions simply age out via TTL, no explicit deletes needed.
“There are only two hard things in computer science: cache invalidation and naming things.” — in practice, TTL combined with event-based invalidation on write covers the large majority of real cases.
14.7 Interview Q&A
Q1: Design a caching strategy for an e-commerce product catalog with 1M products.
Layered: CDN for static assets, API Gateway response caching for idempotent GET requests, an in-process L1 cache (IMemoryCache/local dict) holding the top ~10K hot products with a short TTL (~1 min), and Redis as L2 holding all 1M products with a longer TTL (~10 min) — PostgreSQL remains the source of truth. Invalidation: on product update, publish an event that invalidates the specific Redis key; the L1 cache expires naturally on its own short TTL, so brief staleness there is an acceptable tradeoff. Warm the top products into cache on service startup so cold-start doesn’t hammer the database. At roughly 1KB per product, 1M products is about 1GB in Redis — comfortably within a standard tier.
Q2: How do you decide on a sharding strategy?
It follows from the dominant query pattern. If most access is by a natural even-distribution key (user ID, order ID) and range scans across shards aren’t common, hash-based sharding gives the most even load. If range queries (e.g., “all orders in this date range”) are common, range-based sharding keeps those queries within one or few shards — but needs care to avoid hot-spotting on monotonically increasing keys (e.g., shard by a hash of a composite key rather than raw timestamp). If tenants have strict isolation or compliance requirements (a SaaS product with enterprise customers), tenant-based sharding is the clearest choice even though it risks uneven load, which I’d manage by grouping small tenants and giving large tenants dedicated shards.
Q3: What is a materialized view and when do you use one instead of a normal view or a cache?
A normal (virtual) view just stores the query definition and re-executes it every time; a materialized view stores the actual result set on disk, refreshed on a schedule or on demand — so reads are fast but the data can be stale between refreshes. I use materialized views for expensive aggregations (daily rollups, reporting dashboards) that are read far more often than the underlying data changes, and where staleness on the order of minutes-to-hours is acceptable. Compared to an application-level cache (Redis), a materialized view lives inside the database, can be indexed and joined like a normal table, and is refreshed by the database engine — I’d choose it over an app-level cache when the consumers are other SQL queries/reports rather than an application service.