Redis Data Structures and NestJS Integration for AI Chat Context
Redis is the default session and cache store across most backend stacks, but developers often reach for it without understanding which data structure fits their access pattern. Picking the wrong type — Hash when you need a queue, or String when you need field-level updates — creates serialization overhead and loses atomicity. The List-plus-pipeline pattern shown here is a reusable blueprint for any bounded, append-heavy log, from chat history to audit trails.
Redis's String, Hash, and List types each solve distinct backend problems. String handles counters and cached blobs; Hash stores objects with field-level updates; List works as a high-performance queue for ordered message streams. Choosing between Hash and List comes down to access pattern: field-based lookups versus append-and-trim sequences.
A complete NestJS integration uses ioredis with a global provider module. The chat service stores each message as a JSON string in a List keyed by user ID, keeping only the last 20 messages via LTRIM and refreshing a 30-minute TTL on every interaction. Pipeline commands batch the RPUSH, LTRIM, and EXPIRE calls into a single atomic operation.
The resulting session store costs O(1) per append, holds constant memory per user, and self-destructs after inactivity. The same pattern extends to rate limiting, task queues, or any ordered log that needs bounded retention.
Many developers treat Redis as a dumb cache, but the List-plus-pipeline pattern for chat history shows it functioning as a lightweight, self-purging database — no separate cleanup job required.
The Hash-versus-List decision table is a useful heuristic, but the article's real insight is that production systems often combine both: Hash for user metadata, List for the message stream, each doing what it does best.
Sliding expiration is underused in practice. Resetting TTL on every user action turns a fixed window into an activity-based window, which matches how most session and context lifetimes should actually work.