系统设计 Lab
URL shortener 本质是一个 read-heavy 的 key-value lookup,会先从读这一侧撑爆单机。
调节 redirect 和 create 的速率、存了多少 link、hot-link 倾斜程度、short-code 长度、latency 目标和 region 数量。设计会从单个 database 逐步演进到 cache-aside 读、专门的 key-generation 策略、sharded KV store,以及多 region 的 edge redirect。
分步讲解
一步一步把它想清楚
要点
常规演进场景
从左到右点击,就是预设的演示路径。每张卡片都会改变 workload 输入。
推荐形态
当前架构路径
Client
Client 点开 short link,并提交新的 long URL 去缩短
Edge / API
Edge / CDN 就近为用户解析热门 redirect,不用回 origin
App server 为 redirect 查 code,并处理 create 请求
Key + cache
Key service 分发无冲突的 short code(区间、Snowflake,或预生成的 key)
Read cache 为热门 link 提供 code 到 URL 的 lookup,让 store 少受压
Mapping store
Mapping DB 持久保存每个 short code 及其 long URL
KV shards 把 mapping 分散到多个 node 上,以扩 storage 和写 throughput
Analytics
Click stream 在 hot path 之外收集 redirect event 供 dashboard 用
瓶颈
读路径负载
写路径负载
Mapping storage
Code keyspace 填充率
全球 redirect latency
为什么会变
决策权衡
有出处支撑的规则
这些是模型背后那些经得起时间考验的 system design 论断。而 slider 的具体阈值,则被刻意标注为教学用的假设。
URL shortener 由读(redirect)主导,而不是写
经典写法把 redirect lookup 当成高流量路径,link 创建相对罕见,所以才先做读扩展。
System Design PrimerCache-aside 让热门读不打到 database
cache-aside 模式按需把数据加载进 cache;对倾斜的 redirect 流量,一个小 cache 就能吸收掉大部分 lookup。
Azure ArchitectureRedis 是热门 key-value lookup 常用的 in-memory store
in-memory 的 point lookup 能以亚毫秒 latency 服务热门 short code,远低于基于磁盘的 store。
Redis DocsCDN 从离用户近的位置提供可缓存的响应
热门 link 的 redirect 可以在 edge 缓存,对全球用户能省掉跨 region 的往返。
AWS CloudFront教学用假设
- redirect 被建模成可缓存的 point lookup;cache 命中率由 hot-link 占比估算。
- 单 node 的读、写、storage 预算是保守的教学数字,不是厂商上限。
- Code keyspace 填充率用 base62^length 计算;真实系统还会给每个 ID server 预留 key 区间来避免冲突。