Database Indexing and Scaling for High-Volume Profile Lookups
System DesignModel answerLast updated
Design indexing, caching, and scaling strategies for a user profile database handling 10K QPS with regional skew.
Context
You're building the data layer for a global customer management platform. The system stores user profiles in a relational database with approximately 5 million records today, increasing by roughly 50,000 records monthly. The application serves two primary query patterns: direct profile retrieval using a user identifier and region code, and batch operations that fetch or count all users within a particular region.
Current Scale and Traffic
- Data volume: 5 million user records, approximately 5 GB total size
- Read load: 10,000 queries per second at peak (roughly 9,000 individual lookups and 1,000 regional queries)
- Write load: 500 updates per second at peak, primarily to preference and compliance fields
- Geographic distribution: Traffic and data are heavily skewed—65% North America, 25% Europe/Middle East/Africa, 10% Asia-Pacific
- Performance target: 99th percentile latency under 10 milliseconds for individual profile lookups
- Consistency: Updates must be visible to the updating user immediately (read-after-write consistency)
Schema Overview
The user profile table contains:
user_id: unique identifier (assume globally unique)region: geographic region code (3 distinct values)status: account status (active, suspended, closed, etc.)entitlements,preferences,compliance: structured data fieldsupdated_at: last modification timestamp
Your Task
Design a comprehensive solution covering:
-
Indexing decisions: Which columns should be indexed, in what order, and why? Consider both query patterns and how index selectivity affects performance.
-
Partitioning evaluation: Should the table be partitioned? If so, by what key and at what scale? What are the trade-offs of partitioning early versus deferring it?
-
Horizontal scaling approach: How would you scale reads and writes beyond a single database instance? Compare different replication and sharding strategies given the regional skew.
-
Practical trade-offs: Discuss maintenance overhead, write amplification from indexes, cache consistency challenges, and how your design would evolve as data grows 10x.
Include specific schema definitions, configuration choices, and quantitative reasoning about when different optimizations become necessary.
Hints
Hint 1
Calculate whether the entire dataset and indexes fit in memory on a single modern database instance—this fundamentally changes your architecture choices.
Hint 2
For composite indexes, think about which query pattern benefits from each column ordering and what the cardinality of each column tells you about index effectiveness.
Hint 3
Regional skew matters differently for partitioned versus replicated architectures—consider how load distributes in each approach.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Database Design for High-Volume Profile Access
A strong solution begins with quantitative analysis before proposing infrastructure changes. Let's work through the architecture systematically.
1. Size the Problem and Establish Constraints
Start by calculating actual resource requirements:
- Storage: 5M rows × ~1 KB per row ≈ 5 GB of data. At 50K rows/month, growth is ~600 MB annually. In five years, expect ~8.5M rows and ~8.5 GB.
- Index overhead: B-tree indexes typically add 20-40% overhead. Total working set with indexes: ~7-10 GB.
- Memory availability: A standard 64 GB database instance keeps the entire dataset in the buffer pool with room to spare.
- Read capacity: Modern database servers handle 20,000-50,000 simple primary key lookups per second on cached data. The 10K QPS requirement is well within single-instance capability.
- Write capacity: 500 writes/second is modest for any production database.
Key insight: This is not a big-data problem. The entire dataset fits comfortably in memory, making complex distributed architectures premature. Focus on efficient indexing and simple replication.
Questions to clarify:
- Is
user_idguaranteed unique globally, or only within a region? - Do regional queries return full result sets, counts, or paginated data?
- Are there regulatory data residency requirements forcing geographic separation?
- What exactly changes in a typical update—just preferences, or also entitlements?
2. Index Strategy: Matching Indexes to Query Patterns
CREATE TABLE user_profiles (
user_id UUID PRIMARY KEY,
region VARCHAR(10) NOT NULL,
status VARCHAR(20) NOT NULL,
entitlements JSONB,
preferences JSONB,
compliance JSONB,
updated_at TIMESTAMPTZ DEFAULT NOW()
) WITH (fillfactor = 90);
-- Secondary index for regional queries
CREATE INDEX idx_region_status_users
ON user_profiles (region, status)
INCLUDE (user_id, updated_at);
-- Alternative: partial index if most queries filter to active users
CREATE INDEX idx_region_active
ON user_profiles (region, user_id)
WHERE status = 'active';
For individual lookups by (user_id, region):
The primary key index on user_id already provides optimal performance—typically 3-4 page reads from a cached B-tree. The region parameter serves as a post-fetch filter to validate that the caller has access to that region's data, not as an index column.
Adding a composite index on (user_id, region) provides no benefit because user_id uniquely identifies the row. If you must create a composite index, put user_id first: it has high cardinality (5 million distinct values), making it selective for equality comparisons.
For regional queries:
The region column has only 3 distinct values, making it a poor candidate for standalone indexing. However, it's the correct leading column for range scans that fetch "all users in EMEA" or "active users in APAC."
The composite index (region, status) with included columns enables index-only scans, avoiding table lookups entirely. The database can answer queries like "count active users in NA" by scanning only the index.
Important caveat: A query scanning 65% of the table (all NA users) will likely trigger a sequential scan regardless of indexes—and should. For these large aggregates, maintain a separate summary table updated asynchronously, or use materialized views refreshed periodically.
Write optimization:
Place frequently updated columns (preferences, compliance) in the base table only, not in index INCLUDE clauses. Set fillfactor below 100 to enable heap-only tuple (HOT) updates in PostgreSQL, which avoid index maintenance entirely for updates that don't change indexed columns. This dramatically reduces write amplification.
3. Partitioning: Defer Until Necessary
Partitioning the table by region now would be premature and introduce several problems:
Why partitioning hurts at this scale:
- No performance gain: Point lookups hitting a cached B-tree are already sub-millisecond. Partition pruning saves nothing measurable.
- Skew remains: List partitioning by region creates 65/25/10 data distribution. The skew doesn't disappear; you've just renamed it.
- Uniqueness weakens: In PostgreSQL, partition keys must be part of all unique constraints. Your primary key becomes
(user_id, region), losing database-enforced global uniqueness. - Operational complexity: Queries might require cross-partition scans, and adding/rebalancing partitions requires schema changes.
When partitioning becomes valuable:
- Working set exceeds memory: Beyond ~100M rows or several hundred GB, when index pages start missing the buffer cache
- Maintenance windows impact availability: VACUUM, REINDEX, or backup operations take too long on a single table
- Data lifecycle needs: Bulk archival or deletion (e.g., range partitioning by date to drop old closed accounts)
- Regulatory requirements: Physical data separation mandated by law
At 50K rows/month growth, you won't hit size triggers for many years. Monitor buffer cache hit ratios, index bloat, and VACUUM duration to know when partitioning becomes necessary.
4. Scaling Reads: Replication and Caching
Architecture:
Application Tier
↓
PgBouncer (connection pooling)
↓
Primary DB ← writes + read-after-write reads
↓ (streaming replication)
Read Replicas (2-3) ← majority of read traffic
↓
Redis Cache ← hot user profiles
Replication setup:
- One primary instance handles all writes (500/s is trivial load)
- Two to three replicas in the same availability zone provide read scale and failover capability
- Use synchronous or nearly-synchronous replication (e.g., PostgreSQL synchronous_commit = 'remote_apply' or AWS Aurora) to minimize lag
- Route read traffic through a load balancer or DNS endpoint that distributes across replicas
Cache layer (Redis):
- Cache individual profiles keyed by
user_id - Cache-aside pattern: check cache first, fetch from database on miss, populate cache
- Short TTL (30-60 seconds) as a safety mechanism against stale data
- On write: invalidate cache entries immediately after database commit—don't attempt cache updates, as they race with concurrent fills
Handling read-after-write consistency:
Option A (preferred): LSN-based routing
- After a write, return the Log Sequence Number (LSN) to the client
- Subsequent reads include the LSN; route to replicas only if their replay position ≥ LSN
- Otherwise, temporarily route that read to the primary
Option B (simpler): Sticky routing
- Pin a user's reads to the primary for N seconds after any write (e.g., 5 seconds)
- Simpler but wastes primary capacity on reads that could be served by replicas
Regional skew handling:
In a replicated architecture, skew is not a problem. Every replica holds complete data, so 65% NA traffic is simply load distributed across identical nodes. This is a major advantage over sharded architectures.
If you eventually need to shard (e.g., write throughput exceeds single-instance capacity), shard by hash(user_id), not by region. Hash-based sharding distributes NA/EMEA/APAC evenly across shards. Region-based shards would put 65% of traffic on one shard with no rebalancing option short of splitting regions.
5. Trade-offs and Evolution
| Decision | Benefits | Costs | When to Reconsider |
|---|---|---|---|
| Multiple secondary indexes | Fast regional scans, flexible querying | Write amplification, storage overhead | If write throughput approaches limits; mitigate with HOT updates |
| Read replicas | Linear read scaling, simple failover | Replication lag, consistency complexity | If lag exceeds application tolerance |
| Redis caching | Sub-millisecond latency, offloads hot keys | Cache invalidation complexity, operational burden | If hit rate is poor (<80%) or consistency bugs appear |
| Deferring partitioning | Simple schema, strong constraints, lower ops burden | Future migration cost if needed | When VACUUM takes >1 hour or cache hit ratio drops |
| Hash sharding (future) | Write scale beyond one node | Cross-shard queries, resharding difficulty | Only when write load exceeds ~10K/s |
6. Common Mistakes to Avoid
- Over-engineering for scale: Jumping to sharding or NoSQL without establishing that single-instance limits are actually reached
- Wrong composite index order: Putting low-cardinality
regionbefore high-cardinalityuser_idfor point lookups - Premature partitioning: Partitioning before the dataset exceeds working memory
- Cache update races: Updating cache entries in-place after writes instead of invalidating them
- Ignoring write amplification: Creating many indexes on frequently updated columns without considering HOT updates or partial indexes
7. Monitoring and Evolution Path
Monitor these metrics:
- Buffer cache hit ratio (should be >99% for this workload)
- Index bloat and VACUUM duration
- Replication lag (should be <100ms for synchronous replicas)
- Cache hit rate (target >85%)
- p99 query latency
Evolution as scale grows 10x:
- At 50M rows (~50 GB): Still fits in memory; add more replicas for read scale
- At 100M+ rows: Consider partitioning by date or lifecycle stage; evaluate SSD vs. larger RAM
- At 10K writes/s: Investigate sharding by hash(user_id); use distributed transaction coordination (2PC or Saga pattern)
The key principle: add complexity only when measurements prove it's necessary. Start simple, instrument thoroughly, and scale incrementally based on actual bottlenecks.