UUID v7’s 48-bit millisecond timestamp makes it more useful than UUID v4 as a cache key: you can derive TTL windows, sort cache entries by age, and build time-scoped invalidation without auxiliary metadata. This article covers Redis, CDN edge caching, and application-layer cache key design using RFC 9562 UUID v7.

Redis: UUID v7 as a cache key

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

const redis = createClient();
await redis.connect();

const sessionId = uuidv7(); // time-sortable session key

// Store with TTL
await redis.set(`session:${sessionId}`, JSON.stringify(payload), { EX: 3600 });

// Extract creation time without a metadata lookup
const tsMs = parseInt(sessionId.replace(/-/g, '').slice(0, 12), 16);
const age = Date.now() - tsMs; // ms since this session was created

UUID v7 session keys sort chronologically in Redis sorted sets — ZADD with score=0 and ZRANGEBYLEX gives time-ordered results. See UUID in Redis for sorted set patterns.

Time-windowed cache keys

For per-resource caches that should invalidate together (e.g. all cached responses for a given user within a 5-minute window), derive the window from the UUID v7 timestamp:

function cacheWindow(uuidV7: string, windowMs = 300_000): string {
  const tsMs = parseInt(uuidV7.replace(/-/g, '').slice(0, 12), 16);
  const bucket = Math.floor(tsMs / windowMs) * windowMs;
  return bucket.toString(16).padStart(12, '0'); // consistent hex prefix
}

// Two UUIDs in the same 5-min window get the same cache bucket
const key = `resource:${userId}:${cacheWindow(resourceId)}`;

This enables bulk invalidation: when a user’s data changes, delete all keys matching resource:{userId}:* — the time-window prefix keeps the keyspace manageable. The Redis SCAN command with MATCH is safe for bulk key discovery.

CDN cache keys with UUID v7 ETags

// Express / Node.js — set ETag to UUID v7 of current resource version
app.get('/api/products/:id', async (req, res) => {
  const product = await db.query('SELECT * FROM products WHERE id = $1', [req.params.id]);
  const etag = `"${product.version_id}"`; // version_id is a UUID v7 updated on each write

  if (req.headers['if-none-match'] === etag) {
    return res.status(304).end();
  }

  res.set('ETag', etag);
  res.set('Cache-Control', 'public, max-age=60, stale-while-revalidate=300');
  res.json(product);
});

Using a UUID v7 as the version_id (updated on every write) gives a monotonically increasing ETag — CDNs like Cloudflare and Fastly can compare ETags to determine freshness. Because UUID v7 is time-ordered, a higher UUID v7 value always represents a more recent write. See UUID in Databases for the version column pattern.

Cache invalidation by UUID v7 timestamp range

import redis
import time

r = redis.Redis()

def invalidate_stale_sessions(max_age_ms: int = 3_600_000):
    """Delete all session keys whose UUID v7 timestamp is older than max_age_ms."""
    cutoff_ms = int(time.time() * 1000) - max_age_ms
    # UUID v7 hex prefix for the cutoff timestamp
    cutoff_prefix = hex(cutoff_ms)[2:].zfill(12)

    cursor = 0
    deleted = 0
    while True:
        cursor, keys = r.scan(cursor, match='session:*', count=200)
        for key in keys:
            session_id = key.decode().split(':', 1)[1]
            ts_hex = session_id.replace('-', '')[:12]
            if ts_hex < cutoff_prefix:  # lexicographic = chronological for v7
                r.delete(key)
                deleted += 1
        if cursor == 0:
            break
    return deleted

Lexicographic comparison of UUID v7 hex prefixes equals chronological comparison — a property explained in Lexicographical Order. This makes range-based cache invalidation possible without a separate timestamp index.

Further reading

External references

Frequently asked questions

Can I use UUID v7 as a Redis cache key?

Yes. UUID v7 strings work as Redis keys without modification. The advantage over UUID v4 is that the timestamp prefix lets you extract creation time directly from the key — useful for TTL auditing, cache warm-up ordering, and identifying stale entries without a separate metadata field. The Redis SET command accepts any binary-safe string as a key. See UUID in Redis.

How do UUID v7 timestamps help with cache invalidation?

UUID v7 encodes creation time to millisecond precision in its first 12 hex characters: parseInt(id.replace(/-/g,'').slice(0,12), 16) gives Unix ms. You can group cache entries by time window (e.g., all UUIDs created in the same 5-minute bucket have the same prefix range), bulk-scan with SCAN and a pattern, and expire them together — without storing a separate created_at field per key. See Time-Based UUID.