Sub topic 3
Speeding Up Reads with a Cache
Assume you know HTTP status codes, key-value or relational databases, hashing, and basic Python. This chapter focuses on the read-heavy path of a URL shortener.
Cache-aside lookup
Most requests resolve a short code into a long URL. A cache stores frequently used mappings in memory, close to the application. With the cache-aside pattern, the application checks the cache first, queries the database after a miss, and then stores the result.
def resolve(short_code: str, cache, db):
long_url = cache.get(short_code)
if long_url is not None:
return long_url
long_url = db.get_long_url(short_code)
if long_url is not None:
cache.set(short_code, long_url, ttl=3600)
return long_urlA time-to-live (TTL) removes entries after a period. Invalidate or refresh an entry when a link changes or expires. Protect the database from a cache stampede, where many requests miss simultaneously, with request coalescing or short-lived locks.
Allocating IDs across servers
Counter-based codes need unique IDs. A single database sequence is simple but can limit write availability. Multiple servers can reserve non-overlapping ID ranges, such as 1–1,000,000 and 1,000,001–2,000,000. Snowflake-style IDs combine a timestamp, server identifier, and per-millisecond counter. Base62 then converts the numeric ID into a shorter code.
Replication and sharding
Replicas handle read traffic and provide failover, but replication lag means a newly created link might not appear on a replica immediately. Route a creator’s first lookup to the primary when read-after-write behavior matters. Sharding partitions rows by short-code hash or prefix. Sharding increases capacity but makes rebalancing and cross-shard operations harder.
Aliases and expiry
Custom aliases require uniqueness checks and reserved-name rules. Store expires_at and reject expired links during resolution. Keep expired rows briefly for cleanup and audit needs.
Click analytics
Do not delay redirects while writing analytics. Publish an event containing the code, time, and coarse client information to a queue. Consumers can aggregate events separately. Avoid storing unnecessary personal data.
Abuse and availability
Validate URLs, block unsafe schemes such as javascript:, rate-limit creation and resolution, and monitor repeated enumeration of sequential codes. A cache outage should fall back to the database. Database failure requires replicas or a clear temporary error. Every dependency adds cost and another failure mode.
Exercise
Why might a newly created link be read from the primary database instead of a replica?
Show answer
Replication can lag, so the replica might not contain the new row yet.