Time-to-live controls record lifetime in distributed systems — caches evict stale entries, distributed locks expire, session tokens rotate, and event streams discard old events. UUID v7 adds a self-describing timestamp to each record, making TTL checks a pure computation from the ID. See Distributed Lock for a TTL application.

Extract creation time from UUID v7

// UUID v7 — first 48 bits = Unix millisecond timestamp
function createdMs(id: string): number {
  const hex = id.replace(/-/g, '').slice(0, 12);
  return parseInt(hex, 16);
}

function ageMs(id: string): number {
  return Date.now() - createdMs(id);
}

function isExpired(id: string, ttlMs: number): boolean {
  return ageMs(id) > ttlMs;
}

Application-level TTL cache

import { v7 as uuidv7 } from 'uuid';

interface CacheEntry<T> {
  id:    string; // UUID v7 — creation time embedded
  value: T;
}

class UUIDv7TTLCache<T> {
  private store = new Map<string, CacheEntry<T>>();
  private ttlMs: number;

  constructor(ttlMs: number) {
    this.ttlMs = ttlMs;
  }

  set(key: string, value: T): void {
    this.store.set(key, { id: uuidv7(), value });
  }

  get(key: string): T | null {
    const entry = this.store.get(key);
    if (!entry) return null;

    if (isExpired(entry.id, this.ttlMs)) {
      this.store.delete(key);
      return null;
    }
    return entry.value;
  }

  // Evict all expired entries
  evict(): number {
    let evicted = 0;
    for (const [key, entry] of this.store) {
      if (isExpired(entry.id, this.ttlMs)) {
        this.store.delete(key);
        evicted++;
      }
    }
    return evicted;
  }
}

PostgreSQL TTL range delete using UUID v7

-- Build minimum UUID v7 for a given timestamp
CREATE OR REPLACE FUNCTION uuid_v7_min_at(ts TIMESTAMPTZ)
RETURNS UUID AS $$
DECLARE
  ms   BIGINT := EXTRACT(EPOCH FROM ts) * 1000;
  hex  TEXT   := LPAD(TO_HEX(ms), 12, '0');
BEGIN
  RETURN (
    SUBSTRING(hex, 1, 8) || '-' ||
    SUBSTRING(hex, 9, 4) || '-' ||
    '7000-8000-000000000000'
  )::UUID;
END;
$$ LANGUAGE plpgsql IMMUTABLE;

-- Delete records older than 30 days using UUID v7 range
DELETE FROM cache_entries
WHERE id < uuid_v7_min_at(NOW() - INTERVAL '30 days');

Redis TTL with UUID v7 key

import { createClient } from 'redis';
import { v7 as uuidv7 } from 'uuid';

const redis = createClient();

async function cacheWithTTL<T>(data: T, ttlSeconds: number) {
  const key = `cache:${uuidv7()}`; // UUID v7 key — creation time embedded
  await redis.set(key, JSON.stringify(data), { EX: ttlSeconds });
  return key;
}

async function getCached<T>(key: string): Promise<T | null> {
  const value = await redis.get(key);
  return value ? JSON.parse(value) : null;
}

TTL pattern comparison

ApproachTTL expiry detectionStorage overhead
created_at column + queryRequires DB queryExtra column per table
Redis EXPIRENative key expiryExternal store required
UUID v7 embedded timestampIn-process computationZero extra storage
Separate TTL tableJoin requiredExtra table

Further reading

Frequently asked questions

What is time-to-live in databases?

In databases, TTL is a per-record duration after which the record is automatically deleted. DynamoDB, Redis, and Cassandra support native TTL. PostgreSQL requires a scheduled job or pg_cron to delete expired rows. UUID v7 enables efficient TTL range deletes: DELETE FROM cache WHERE id < uuid_v7_from_timestamp(now() - ttl_interval). See Event ID.

How does UUID v7 enable TTL without a created_at column?

UUID v7 encodes the creation time in its first 48 bits. Extract it with parseInt(id.replace(/-/g,'').slice(0,12), 16). Compare Date.now() - createdMs to the TTL to determine if the record has expired — no extra column, no extra query. This works in application code, Redis scripts, and PostgreSQL functions. See Distributed Lock for a lock TTL example.

How does UUID v7 work with Redis TTL?

Redis TTL is set with EXPIRE key seconds or SET key value PX milliseconds. Use the UUID v7 string as the Redis key — the embedded timestamp lets you verify when a key was created even if Redis expiry metadata is unavailable (e.g., in a recovered dump). See UUID in Redis.