Redis uses arbitrary byte strings as keys. UUID v7 keys carry their creation time in the first 12 hex characters, enabling TTL alignment and chronological scanning without secondary indexes. See UUID v7 and Caching Strategies for the full cache key design.

Session IDs — UUID v4

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

const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

// Session tokens: UUID v4 for maximum entropy
async function createSession(userId: string): Promise<string> {
  const sessionId = uuidv4();   // 122 bits of randomness
  await redis.setEx(
    `session:${sessionId}`,
    86_400,                     // 24h TTL
    JSON.stringify({ userId, createdAt: Date.now() }),
  );
  return sessionId;
}

async function getSession(sessionId: string) {
  const raw = await redis.get(`session:${sessionId}`);
  return raw ? JSON.parse(raw) : null;
}

Session IDs are security credentials — use UUID v4’s full 122-bit randomness. See UUID Security.

Job and request IDs — UUID v7 with TTL alignment

// Job IDs: UUID v7 so they sort chronologically
async function enqueueJob(payload: object): Promise<string> {
  const jobId = uuidv7();
  const ttlMs = 7 * 24 * 60 * 60 * 1000;   // 7 days

  await redis.setEx(
    `job:${jobId}`,
    Math.ceil(ttlMs / 1000),
    JSON.stringify({ payload, status: 'queued' }),
  );
  return jobId;
}

// Derive when the job was created from its ID — no stored timestamp needed
function jobCreatedAt(jobId: string): Date {
  const ms = parseInt(jobId.replace(/-/g, '').slice(0, 12), 16);
  return new Date(ms);
}

// Check if a job key has "expired" (> 7 days old) using its ID alone
function isJobExpired(jobId: string): boolean {
  return Date.now() - jobCreatedAt(jobId).getTime() > 7 * 86_400_000;
}

See UUID Epoch for the 48-bit millisecond extraction pattern.

Distributed locks — UUID v7 as lock token

// Distributed lock: UUID v7 as lock token for safe release
async function acquireLock(
  resource: string,
  ttlMs: number,
): Promise<string | null> {
  const token = uuidv7();
  const key   = `lock:${resource}`;

  // SET NX EX — atomic acquire
  const ok = await redis.set(key, token, { NX: true, PX: ttlMs });
  return ok ? token : null;
}

async function releaseLock(resource: string, token: string): Promise<boolean> {
  // Lua script for atomic check-and-delete
  const script = `
    if redis.call("get", KEYS[1]) == ARGV[1] then
      return redis.call("del", KEYS[1])
    else
      return 0
    end
  `;
  const result = await redis.eval(script, { keys: [`lock:${resource}`], arguments: [token] });
  return result === 1;
}

Using UUID v7 as the lock token means you can inspect when the lock was acquired from the token value itself — useful for debugging stuck locks. See UUID as Idempotency Keys for related patterns.

Key namespace design

session:{uuidv4}          — user sessions (no timestamp needed)
job:{uuidv7}              — background jobs (sortable, TTL-derivable)
lock:{resource-name}      — distributed locks (value = uuidv7 token)
idempotency:{uuidv4}      — API idempotency keys (value = response)
cache:{uuidv7}:{version}  — versioned cache entries

UUID v7 keys in the job: namespace let you SCAN for old jobs:

// Find all job keys older than 7 days — no secondary index
const sevenDaysAgoMs = Date.now() - 7 * 86_400_000;
const sevenDaysAgoHex = sevenDaysAgoMs.toString(16).padStart(12, '0');
const cutoff = `job:${sevenDaysAgoHex}`;   // keys before this are old

// SCAN + filter by prefix comparison
for await (const key of redis.scanIterator({ MATCH: 'job:*' })) {
  const jobId = key.replace('job:', '');
  if (jobId < cutoff.replace('job:', '')) {
    await redis.del(key);   // cleanup old job
  }
}

See UUID v7 Caching Strategies for TTL alignment and CDN ETag patterns.

Further reading

External references

Frequently asked questions

Should I use UUID v4 or UUID v7 for Redis session tokens?

UUID v4 for session tokens — the full 122 bits of randomness are needed because session tokens are security credentials. UUID v7 embeds a timestamp that an attacker could use to narrow a brute-force window. For non-secret keys (job IDs, request IDs, cache keys where the value is the secret), UUID v7 is preferable because it sorts and lets you set TTL from the timestamp. See UUID Security.

Can I use UUID v7 as a Redis Stream message ID?

Redis Streams use millisecondsTimestamp-sequenceNumber as the native message ID (e.g., 1699000000000-0). UUID v7 is not a valid Redis Stream ID format. However, you can store a UUID v7 as a field inside the stream entry (XADD mystream * event_id 018fbe3a-4c5d-7b12-...) to correlate events across systems. The UUID v7's timestamp and the Redis Stream timestamp will match closely. See UUID v7 in Event Sourcing.