intermediate
Strings
Use strings for counters, tokens, blobs, feature values, and simple cache entries with clear serialization.
Redis strings are the simplest value type — binary-safe blobs up to 512 MB. They back counters, feature flags, serialized JSON cache entries, session tokens, and rate-limit windows when the whole value is read or replaced at once.
SET session:abc123 '{"userId":42}' EX 3600 NX
INCR page:views:home
INCRBY wallet:user:42 -50
GET feature:dark_mode
SET cache:product:9 '{"title":"Mug"}' EX 300
| Pattern | Command idea | |---------|--------------| | Cache entry | `SET key json EX ttl` | | Counter | `INCR` / `INCRBY` — atomic | | Conditional set | `SET NX` for claim or lock seed | | Compare-and-set | `WATCH` + `MULTI` / `SET` with version in value |
Strings are O(1) for most single-key ops. Serialization format must be explicit — JSON, integer, or prefixed version — so readers do not misinterpret types after a deploy.
On interviews: pick a string use case and explain TTL, atomicity, and what happens on eviction or restart.
Common pitfalls: storing huge blobs that belong in object storage; `GET`+`SET` races without `WATCH` or Lua; no TTL on cache keys; binary data without length-aware clients.
The trade-off is simplicity versus partial updates — strings are ideal when the value is small and replaced atomically; field-level changes belong in hashes or another structure.
Checklist:
- Define serialization and versioning for values.
- Use `INCR` for atomic counters.
- Set TTL when data is ephemeral.
- Explain memory and eviction impact per key.