Write-Through vs Write-Back for URL Creation
You'll learn how to choose between writing new short URLs synchronously to both cache and database versus writing to cache first with delayed database persistence.
The Core Tradeoff
When a user creates a new short URL, you face a critical decision: should you write to both the database and cache immediately (write-through), or write to cache first and update the database asynchronously (write-back)?
Write-Through Approach
With write-through, every new URL creation hits the database and cache simultaneously before returning success to the user:
- Generate short code
- Write to database (wait for confirmation)
- Write to cache
- Return success
Pros: Data is immediately durable and consistent. If cache fails, database has the truth. No risk of losing newly created URLs.
Cons: Slower write latency (waiting for database). Write path is as slow as your slowest component.
Write-Back Approach
With write-back, you write to cache immediately and queue the database write asynchronously:
- Generate short code
- Write to cache
- Queue async database write
- Return success immediately
Pros: Blazing fast user experience. Write latency depends only on cache speed.
Cons: Risk of data loss if cache crashes before database write completes. Requires careful queue management and retry logic.
The URL Shortener Context
For URL shorteners, write-through is typically preferred because:
- Writes are infrequent compared to reads
- Losing a newly created short URL is unacceptable
- Users can tolerate slightly slower creation (milliseconds vs microseconds)
- Durability matters more than microsecond-level write speed
Key Takeaway: Write-through prioritizes durability and consistency at the cost of write latency; write-back prioritizes speed but risks data loss—for URL shorteners, the durability guarantee of write-through usually wins despite being read-heavy systems.