Expiration and Time-to-Live in URL Shorteners
You'll learn how to automatically reclaim storage by implementing configurable URL expiration with background cleanup jobs.
The Core Problem
Not all short URLs should live forever. Marketing campaigns end, temporary event links expire, and free-tier users might only get 30-day URLs. Without expiration, your database fills with stale links that waste storage and complicate analytics.
Implementing TTL
At creation time, store an expires_at timestamp alongside each URL. This can be:
- User-configurable (7 days, 30 days, never)
- Plan-based (free = 30 days, premium = infinite)
- Default if not specified (e.g., 90 days)
Your schema might include:
created_at: timestamp
expires_at: timestamp (nullable)
is_expired: boolean (indexed)
Handling Expired URLs
When a user accesses a short URL, check expires_at before redirecting. If expired, return a friendly "Link Expired" page instead of a 404. This improves user experience and distinguishes between invalid and expired links.
Background Cleanup Jobs
Don't delete immediately on access—use background workers that:
- Run periodically (e.g., daily at 3 AM)
- Query for URLs where
expires_at < NOW() AND is_expired = false - Batch-delete in chunks (e.g., 10,000 at a time) to avoid locking issues
- Optionally mark as expired first, delete later for safety
This lazy deletion approach prevents runtime overhead during redirects while keeping the database lean.
Storage Reclamation
After deletion, consider:
- Recycling short codes back into the pool after a grace period (prevents accidental reuse)
- Archiving analytics before deletion (preserves click history)
- Vacuum operations in PostgreSQL or compaction in NoSQL to reclaim disk space
Key Takeaway: Implement TTL by storing expiration timestamps, checking them at access time, and running background cleanup jobs to reclaim storage efficiently—balancing user experience with operational cost.