S
Supanote
Sign in Sign up

Redis 8.0 Granular Hash Field TTL (HEXPIRE, HSETEX & HGETDEL)

plain (bash) 1 day ago · 28 lines · 2 views
Verified Blueprint Redis 8.0+

Cut Redis keyspace metadata memory by 40%+ using per-field hash expiration (HEXPIRE, HSETEX, HTTL, HGETDEL) for sessions and OAuth tokens.

  • ✓ Consolidates per-user device tokens and feature flags into one Hash instead of proliferating top-level keys
  • ✓ Assigns independent field TTLs via HSETEX and conditional HEXPIRE NX/GT without resetting sibling fields
  • ✓ Atomically consumes one-time OTP / magic-link fields in 1 RTT using HGETDEL
Quick Fetch
1#!/usr/bin/env bash
2# Redis 7.4 / 8.0+ Granular Hash Field Expiration Blueprint
3# Replaces sprawling user:1042:device:<id> top-level keys with a single compact Hash per user
4
5set -euo pipefail
6REDIS_CLI="${REDIS_CLI:-redis-cli}"
7USER_KEY="acct:1042:auth"
8
9# 1. HSETEX (Redis 8.0+): Atomically Set Multiple Hash Fields With Shared Expiration (Seconds)
10# Stores desktop & mobile sessions with a 7-day (604800s) sliding TTL
11${REDIS_CLI} HSETEX "${USER_KEY}" EX 604800 FIELDS 2 \
12 "sess:macbook" '{"ip":"192.0.2.10","mfa":true}' \
13 "sess:iphone" '{"ip":"198.51.100.24","mfa":true}'
15# 2. Store a Short-Lived 5-Minute Step-Up OTP Inside the Exact Same Hash (300s TTL)
16${REDIS_CLI} HSETEX "${USER_KEY}" EX 300 FIELDS 1 \
17 "otp:stepup" "849201"
19# 3. Extend ONLY the Mobile Session TTL If New Expiry Is Greater (GT Flag)
20${REDIS_CLI} HEXPIRE "${USER_KEY}" 1209600 GT FIELDS 1 "sess:iphone"
22# 4. Inspect Remaining Per-Field TTLs (Seconds) Without Fetching Payload Values
23${REDIS_CLI} HTTL "${USER_KEY}" FIELDS 3 "sess:macbook" "sess:iphone" "otp:stepup"
25# 5. One-Time Atomic Read + Delete of Step-Up OTP (Prevents Replay Attacks in 1 RTT)
26CONSUMED_OTP=$("${REDIS_CLI}" HGETDEL "${USER_KEY}" FIELDS 1 "otp:stepup")
27echo "Verified & burned one-time OTP: ${CONSUMED_OTP}"

No replies yet

Every reply is a note. Start a discussion, ask a question, or attach a code snippet.

Related Redis 8.0+ & Database, Cache & SQL Blueprints

Production-ready configurations and diagnostics from the verified Supanote library.

All Database, Cache & SQL →
Interactive Developer Workbench: .env, Log & API Key Secret Scanner

Detect and redact leaked AWS keys, JWTs, database URIs, private keys, and Bearer tokens before sharing.

Open Secret Scanner →

Share Note

Open
Download SVG
Social Card Preview
Open on mobile
Point your phone camera to open this note directly

Report this note

Notification