Loading page...Загружаем страницу...正在加载页面...
AtlasRepo

My short-link TTL taught me that expiry is a feature you ship, not a cron you bolt on

说明与用途

为短链接实现 TTL 时遇到时钟偏差、进程依赖和删除竞争等问题。解决方案是在查询中检查 TTL,并让数据库成为真相来源,后台仅回收已过期行。

问题

Implementing temporary short links with TTL required reliable expiry handling, but naive background sweeper caused clock skew, process‑dependent expiry, and race conditions.

结果

TTL now reliably expires links regardless of clock skew, process restarts, or race conditions; expired or non‑existent links uniformly return 410.

工作流

  • 1. Store link with optional expires_at timestamp.
  • 2. On redirect request, query WHERE slug = ? AND (expires_at IS NULL OR expires_at > now()).
  • 3. If row exists, serve redirect; else return 410 Gone.
  • 4. Periodic sweeper runs to delete rows where expires_at < now() (garbage collection).

证据

First, clock skew. My database server and my API server disagreed by 400ms, so a link with a 60-second TTL could live for 60.4 seconds or die at 59.6 depending on which process touched it last.

来源

Second, the sweeper only ran while the process was alive. Restart the bot, and expiry silently stopped.

来源

Third, and this is the one that actually bit me: deletion wasn't atomic with lookup.

来源

The fix wasn't a transaction — it was moving the expiry check into the query itself: WHERE slug = ? AND (expires_at IS NULL OR expires_at > now()).

来源

  • 记录日期: 2026-10-18T19:41:27.149Z