intermediate

Hashes

Use hashes for small field maps when partial updates and grouped cache values fit memory behavior.

Hashes store field maps under one key — efficient for small objects where you update individual fields without rewriting the entire serialized blob. Typical uses: user session attributes, product cache fields, feature toggles per tenant.

					HSET user:42 name "Ada" plan "pro" lastSeen 1718448000
HGET user:42 plan
HMGET user:42 name plan
HINCRBY cart:42 qty 1
HGETALL user:42   # OK for small maps only
				

| Prefer hashes | Prefer strings | |---------------|----------------| | Partial field updates | Whole-value replace | | Small, stable field sets | Large JSON documents | | Grouped cache entity | Simple counter or token | | `HINCRBY` on numeric fields | Atomic string ops suffice |

Redis encodes small hashes in ziplist/listpack-style memory layouts; very large hashes degrade like many small keys. Keep field count modest and avoid `HGETALL` on hot paths with hundreds of fields.

On interviews: contrast updating one hash field versus deserializing a JSON string for the same entity.

Common pitfalls: giant hashes that should be documents in a database; `HGETALL` on large maps; treating hashes as a relational table with unbounded columns; no TTL on the parent key so stale entities linger.

The trade-off is memory-efficient partial updates versus query flexibility — hashes optimize field-level cache churn; strings or an external store win when the object is large or richly queried.

Checklist:

  • Cap field count and name keys consistently.
  • Use `HMGET` for needed fields only.
  • Set TTL on the hash key when appropriate.
  • Compare hash vs JSON string for update pattern.