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

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

Описание и применение

Внедрение 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