QA
Intermediate LevelSystem Design & Architecture

How do you architect Database Read/Write Splitting with Sticky Replica routing?

❓ Interview Prompt: Explain Read/Write Splitting, asynchronous primary-to-replica replication lag, and Sticky Replica routing to prevent stale read glitches.

Architecting database read/write splitting routes 'INSERT/UPDATE' traffic to the Primary DB and 'SELECT' traffic to Read Replicas:

Replication Lag Glitch & Sticky Fix:

β€’
Problem: User updates profile name $\rightarrow$ Redirects to profile page $\rightarrow$ Reads from replica before replication completes $\rightarrow$ User sees old profile name!
β€’
Sticky Replica Routing: When a user writes data, flag their session to route ALL subsequent reads to the Primary DB for 5 seconds, guaranteeing they read their own writes!

Code Implementation Example

typescript
export async function handleProfileRead(req: Request, res: Response) {
  const userWroteRecently = req.session.lastWriteTimestamp > Date.now() - 5000;
  
  // Route to Primary DB if user wrote recently; otherwise use Read Replica!
  const dbClient = userWroteRecently ? primaryDb : readReplicaDb;
  const profile = await dbClient.user.findUnique({ where: { id: req.user.id } });
  res.json(profile);
}
πŸ’‘Routing recent writers to Primary DB to prevent replication lag glitches.
🎯 Interview Key Takeaway

Use Sticky Replica routing to direct recent writers to the primary database, eliminating replication lag read glitches.

#System Design#Read Write Split#Replication Lag#Databases#Intermediate
Back to all System Design & Architecture Questions→

More System Design & Architecture Interview Questions

Beginner LevelSystem Design & Architecture

Explain the CAP Theorem and PACELC Theorem with real-world database examples.

Beginner LevelSystem Design & Architecture

What is Vertical Scaling (Scale Up) vs Horizontal Scaling (Scale Out)?

Beginner LevelSystem Design & Architecture

How do Load Balancers distribute traffic (Round Robin, Least Connections, IP Hash)?