Sub topic 15
Availability, failure modes, and trade-offs
This chapter closes the design. You already have the pieces: code generation, a datastore, a cache, replicas, and shards. Here you ask what happens when each piece fails, and which compromises you accept to keep the service up. It assumes you have read the earlier chapters on caching, redirects, replication and sharding, and distributed ID allocation.
What availability means for a shortener
Availability is the fraction of requests that succeed. Teams usually state it as a target such as 99.9% ("three nines"), which allows about 43 minutes of downtime in a 30-day month. 99.99% allows about 4 minutes.
A URL shortener has two paths with different needs:
- Redirect (read) path. A broken short link breaks every page, email, or QR code that contains it. This path needs the highest availability. It is also the easiest to protect, because the data rarely changes.
- Create (write) path. If creation is down, users cannot make new links, but existing links keep working. A short write outage is much cheaper than a read outage.
This asymmetry drives most decisions below. You can let writes fail so that reads keep working. The reverse is almost never acceptable.
Mapping failure modes
Walk the request path and ask what happens if each component disappears.
| Component | Failure | Effect | Typical mitigation |
|---|---|---|---|
| Load balancer | Instance dies | Some requests fail until health checks remove it | Several balancers, health checks, DNS or anycast failover |
| App server | Crash or overload | Reduced capacity | Stateless servers, autoscaling, timeouts |
| Cache | Node lost or restarted | All its keys miss, and the database takes the load | Replicated cache, warm-up, request coalescing |
| Database primary | Crash | Writes fail, and reads fail if there are no replicas | Replica promotion, read replicas |
| Database replica | Lag or loss | Stale or missing reads | Fall back to another replica or the primary |
| ID allocator | Unavailable | New links cannot be created | Pre-allocated ID ranges per server |
| Whole region | Outage | Everything fails | Multi-region deployment |
The design should make each row survivable, and the redirect path should survive most of them.
Serving stale data on purpose
Short links are close to immutable. Once a code maps to a URL, the mapping seldom changes. So a cached value that is hours old is almost always still correct. When the database is unreachable, returning a stale mapping is far better than returning an error.
This trades consistency for availability. The risk is that a link was deleted or expired while the database was down, and you still redirect to it. For most shorteners that is acceptable. For links removed because of abuse or legal requests, it may not be. Many teams keep a short list of blocked codes in memory on every app server so takedowns still apply during a database outage.
The sketch below keeps two time limits per entry. A fresh limit is used normally. A longer stale limit applies only when the database fails.
import time
class StaleCache:
def __init__(self, ttl=300, stale_ttl=86400):
self.ttl = ttl
self.stale_ttl = stale_ttl
self._data = {}
def set(self, key, value):
self._data[key] = (value, time.monotonic())
def get(self, key, allow_stale=False):
entry = self._data.get(key)
if entry is None:
return None
value, stored_at = entry
age = time.monotonic() - stored_at
limit = self.stale_ttl if allow_stale else self.ttl
return value if age <= limit else None
class DatabaseDown(Exception):
pass
def resolve(short_code, cache, db):
"""Return (long_url, source). source is 'cache', 'db', or 'stale'."""
url = cache.get(short_code)
if url is not None:
return url, "cache"
try:
url = db.get_long_url(short_code)
except DatabaseDown:
url = cache.get(short_code, allow_stale=True)
if url is not None:
return url, "stale"
raise
if url is not None:
cache.set(short_code, url)
return url, "db"
class FakeDb:
def __init__(self):
self.up = True
self.rows = {"abc1234": "https://example.com/long/path"}
def get_long_url(self, code):
if not self.up:
raise DatabaseDown()
return self.rows.get(code)
if __name__ == "__main__":
cache, db = StaleCache(ttl=0.01), FakeDb()
print(resolve("abc1234", cache, db)) # ('https://example.com/long/path', 'db')
time.sleep(0.05) # fresh TTL passes
db.up = False
print(resolve("abc1234", cache, db)) # ('https://example.com/long/path', 'stale')The function distinguishes "database says this code does not exist" (returns None) from "database cannot answer" (raises). Mixing these up is a common bug. If a database timeout is treated as "not found", the service returns 404 for valid links during an outage.
Cache failures and stampedes
A cache is an optimization, but at scale the database may not survive without it. If the read path is 100 times heavier than the write path and the cache absorbs 95% of reads, losing the cache sends 20 times more traffic to the database. That can take the database down too.
Three problems follow:
- Cold start. A freshly restarted cache is empty. Warm it gradually, or restart nodes one at a time so only a fraction of keys miss.
- Stampede on a hot key. When a popular link's entry expires, hundreds of concurrent requests miss together and all query the database. Coalesce them: let one request fetch the value while the others wait for its result. Adding random jitter to TTLs also prevents many keys from expiring at the same instant.
- Negative lookups. Requests for codes that do not exist always miss. Bots scanning random codes can bypass the cache and hit the database. Cache "not found" results for a short time, such as 30 to 60 seconds. Keep that time short so a newly created link is not hidden.
Also protect the database directly with a concurrency limit and a timeout. A slow database that never answers is worse than one that fails fast, because stuck requests pile up and exhaust app server threads.
Replication trade-offs
Replicas add read capacity and survive a primary failure, but they bring replication lag, the delay before a write on the primary appears on a replica.
- Asynchronous replication acknowledges a write once the primary has it. It is fast, but a primary crash can lose recent writes that had not reached a replica. A user could receive a short link that disappears after failover.
- Synchronous replication waits for at least one replica to confirm. It protects against that loss but makes every write slower, and writes stall if the replica is down.
A reasonable middle path for a shortener is asynchronous replication for most traffic, plus "read your own write" handling. Right after creating a link, the creator's first redirect should be served from the cache entry written at creation, or from the primary. Otherwise a lagging replica returns 404 for a link that was just created.
Failover is its own risk. If two nodes both believe they are the primary (split brain), they can issue conflicting data. Use a consensus-based or managed failover mechanism rather than a homemade script.
ID allocation failures
If a central counter issues IDs, its outage stops all link creation. As covered in the ID allocation chapter, each app server can lease a block of IDs (for example 10,000 at a time) and issue them locally. A server can then keep creating links for as long as its block lasts, even if the allocator is down.
The cost is gaps. If a server crashes, the unused part of its block is lost. With 62^7 possible codes (about 3.5 trillion), losing a few thousand IDs per crash is irrelevant. Wasting codes is cheaper than blocking writes.
Redirect choice under failure
The 301 versus 302 decision also affects availability. A 301 (permanent) can be cached by browsers and intermediaries, so repeat visitors keep reaching the target even when your service is down. A 302 (temporary) sends every click through you, which keeps your analytics accurate and lets you change or expire the link, but makes you a dependency on every click. The trade-off is resilience and lower load versus control and measurement. If you choose 302 for analytics, you are accepting that an outage affects every click.
Keeping side features off the critical path
Analytics, abuse checks, and logging must not be able to break redirects.
- Record clicks asynchronously. Push an event to a queue or buffer, and drop events if the buffer is full rather than delaying the redirect.
- Give any call to a safety or reputation service a tight timeout. Decide in advance whether it fails open (allow the redirect) or fails closed (block it). For the redirect path, failing open is usual. For link creation, failing closed is often safer.
- Rate limiters that depend on a shared store need a fallback. If that store is unreachable, fall back to a per-server limit rather than rejecting all traffic.
Deciding what to build
Every mechanism in this chapter costs money and complexity. Choose based on stated targets.
| Decision | Cheaper option | More available option | Cost of the extra availability |
|---|---|---|---|
| Replication | Single primary | Primary with replicas in several zones | More servers, lag handling |
| Cache | One node | Replicated or clustered cache | Operational complexity |
| Deployment | One region | Multiple regions | Cross-region data replication, higher cost |
| Staleness | Strict freshness | Serve stale on failure | Possible redirect of a removed link |
| Redirect | 302 | 301 | Less control and analytics |
For a service with a 99.9% target, multiple zones in one region, replicas, a replicated cache, and stale serving usually suffice. Multi-region deployment becomes worthwhile when the target is 99.99% or when users are spread worldwide and latency matters.
Exercise
Your database becomes unreachable for 20 minutes. The cache holds a fresh TTL of 5 minutes and a stale TTL of 24 hours. A user opens a short link whose cache entry is 2 hours old, and another user opens a link that was created 10 minutes ago and never cached. What does each user get, and what should the service return for the second one?
Show answer
The first user is served from the stale entry (older than the 5-minute fresh TTL, within the 24-hour stale TTL), so the redirect works. The second link has no cache entry and the database cannot answer, so the service cannot resolve it. It should return 503 with a Retry-After header, not 404, because the link exists and the failure is temporary. Writing the mapping into the cache at creation time would have avoided this case.
Exercise
A team replaces a central ID counter with per-server blocks of 1,000 IDs. Name one availability benefit and one cost.
Show answer
Benefit: servers can keep creating links while the allocator is down, until their block runs out. Cost: IDs left in a block are lost if a server crashes, which leaves gaps in the code space. With about 3.5 trillion possible 7-character codes, the gaps are harmless.