Designing a URL Shortener on GCP: Short Codes, Fast Redirects, Simple Storage
One write, a million reads: random base62 codes, layered caching and Firestore. A shop creates one Diwali promo link in the morning and sends it by SMS. By evening, say a million people have clicked it. That is one write and a million reads, and every click should feel instant.
一次写入,百万次读取:随机 base62 编码、分层缓存和 Firestore。一家商店在早上创建了一个排灯节促销链接并通过短信发送。到晚上,可能有上百万人点击了它。这就是一次写入和一百万次读取,且每次点击都应感觉即时。
The problem: A URL shortener looks simple: store a code, look it up, redirect. The difficulty is in the shape of the traffic and in a few details: Unique codes. Two links must never get the same code, even if they are created at the same moment. Read-heavy traffic. If every click hits the database, cost and latency grow with popularity, and one viral link can become a hotspot. Storage choice. Picking a heavier database than the data needs means running replicas and, later, a sharding project for no reason.
问题:URL 缩短器看起来很简单:存储代码、查找、重定向。难点在于流量的形态和一些细节:唯一代码。两个链接绝不能获得相同的代码,即使它们在同一时刻创建。读取密集型流量。如果每次点击都访问数据库,成本和延迟会随流行度增加,一个病毒式链接可能成为热点。存储选择。选择比数据需求更重的数据库意味着要运行副本,以后还要无缘无故地进行分片项目。
To size it, I start with assumptions. Say 100 million new links a month, which is about 40 creates a second. With a 100:1 read-to-write ratio, that is about 4,000 redirects a second. The system is read-heavy, so the redirect path gets the most attention.
为了确定规模,我从假设开始。假设每月有 1 亿个新链接,即每秒约 40 个创建请求。按 100:1 的读写比计算,每秒约有 4,000 次重定向。该系统是读取密集型的,因此重定向路径最受关注。
The solution: Two endpoints: POST /shorten returns sho.rt/aB3x9, and GET /aB3x9 redirects. Create path: Load Balancer, then API Gateway, then Cloud Run, then Firestore. The gateway sits in front of /shorten only. It checks the API key and rate-limits, so a bot sending thousands of creates gets 429s. Redirects skip the gateway, because they must be fast.
解决方案:两个端点:POST /shorten 返回 sho.rt/aB3x9,GET /aB3x9 执行重定向。创建路径:负载均衡器,然后是 API 网关,接着是 Cloud Run,最后是 Firestore。网关仅位于 /shorten 前面。它检查 API 密钥并进行速率限制,因此发送数千个创建请求的机器人会收到 429 错误。重定向会跳过网关,因为它们必须快速。
Short code generation: I use a random 7-character base62 code (a-z, A-Z, 0-9). 62^7 is about 3.5 trillion possible codes. The code is the Firestore document ID, and create() fails if that ID already exists. The check and the write happen as one atomic step, so two creators cannot both win. Even after a billion links, only about 1 in 3,000 creates would hit a collision and retry. A custom alias that is already taken returns 409 instead of retrying. A counter needs a separate ID service, since Firestore has no auto-increment, and a truncated hash still collides.
短代码生成:我使用 7 位随机 base62 代码(a-z, A-Z, 0-9)。62^7 约有 3.5 万亿种可能的代码。该代码是 Firestore 文档 ID,如果该 ID 已存在,create() 将失败。检查和写入作为一个原子步骤发生,因此两个创建者不可能同时成功。即使在十亿个链接之后,也只有约 3,000 分之一的创建请求会遇到冲突并重试。已被占用的自定义别名会返回 409 而不是重试。计数器需要单独的 ID 服务,因为 Firestore 没有自动递增功能,且截断的哈希值仍会冲突。
Storage: Firestore. The data is one collection: document ID is the short code, with fields long_url, user_id, created_at and expires_at. Only key lookups, no joins. Firestore gives atomic uniqueness, a TTL policy for expiry, automatic scaling and multi-region availability, with nothing to resize or shard. Cloud SQL would work too, but it brings replicas, failover and a future sharding project. Bigtable is built for far higher throughput and has a per-node minimum cost; it fits click events better than the link table. One detail: TTL deletion can lag, so the app also checks expires_at on read.
存储:Firestore。数据是一个集合:文档 ID 是短代码,包含 long_url、user_id、created_at 和 expires_at 字段。仅进行键查找,无连接查询。Firestore 提供原子唯一性、过期 TTL 策略、自动扩展和多区域可用性,无需调整大小或分片。Cloud SQL 也可以,但它会带来副本、故障转移和未来的分片项目。Bigtable 专为更高的吞吐量而构建,且有每节点最低成本;它比链接表更适合点击事件。一个细节:TTL 删除可能会滞后,因此应用程序在读取时也会检查 expires_at。
Redirect path: layered caching. Cloud CDN, then Load Balancer, then Cloud Run, which checks Memorystore (Redis) first and reads Firestore only on a miss. For a viral link, the first click reads Firestore and later clicks come from Redis. A CDN can also cache the redirect itself, since it is a tiny response that is the same for every user, as long as the origin sends an explicit max-age.
重定向路径:分层缓存。Cloud CDN,然后是负载均衡器,接着是 Cloud Run,它首先检查 Memorystore (Redis),仅在未命中时读取 Firestore。对于病毒式链接,第一次点击读取 Firestore,后续点击来自 Redis。CDN 也可以缓存重定向本身,因为它是一个对每个用户都相同的微小响应,只要源服务器发送明确的 max-age 即可。
301 or 302: A 301 is cached by browsers, so later clicks may never reach my server. A 302 asks the server every time. I use 302 when the business needs click counts or editable links, and keep a short CDN TTL so edits go live quickly. Clicks are published to Pub/Sub without waiting and loaded into BigQuery. Clicks answered by the CDN are counted from load balancer logs through a log sink, since those requests never reach Cloud Run.
301 或 302:301 会被浏览器缓存,因此后续点击可能永远不会到达我的服务器。302 每次都会询问服务器。当业务需要点击计数或可编辑链接时,我使用 302,并保持较短的 CDN TTL,以便编辑内容能快速生效。点击事件无需等待即发布到 Pub/Sub 并加载到 BigQuery。由 CDN 回答的点击通过日志接收器从负载均衡器日志中统计,因为这些请求从未到达 Cloud Run。
Trade-offs and limits: Per-operation billing makes the cache mandatory. Firestore bills per read, so a dropping Redis hit ratio raises the bill as well as latency. I would alert on both. Never keep a click counter in the link document. One document supports roughly one sustained write per second. Count clicks in BigQuery. Editing a link clears caches in order. Firestore first, then delete the Redis key, then invalidate the CDN path. A 301 already cached in a browser cannot be cleared at all. Revisit the database if needs change. If accounts, billing or team reports with joins appear, I would add Cloud SQL for that data only. Short links get abused. A production shortener should scan destinations for malware and phishing.
权衡与限制:按操作计费使得缓存成为必须。Firestore 按读取次数计费,因此 Redis 命中率下降会增加账单和延迟。我会对两者进行预警。永远不要在链接文档中保留点击计数器。一个文档大约支持每秒一次持续写入。在 BigQuery 中统计点击量。编辑链接会按顺序清除缓存。先是 Firestore,然后删除 Redis 键,最后使 CDN 路径失效。已在浏览器中缓存的 301 根本无法清除。如果需求发生变化,请重新评估数据库。如果出现需要连接查询的账户、计费或团队报告,我会仅为这些数据添加 Cloud SQL。短链接会被滥用。生产环境的缩短器应扫描目标地址是否存在恶意软件和钓鱼网站。
Takeaway: A URL shortener is read-heavy, so design the redirect path first. Random base62 codes with an atomic create give uniqueness without a counter service. CDN and Redis absorb the reads; Firestore stays the simple source of truth.
要点:URL 缩短器是读取密集型的,因此应首先设计重定向路径。带有原子创建功能的随机 base62 代码无需计数器服务即可提供唯一性。CDN 和 Redis 吸收了读取压力;Firestore 保持作为简单的单一事实来源。