Implementing Key-Value Stores

1. Designing Key Naming Conventions

ConventionExample
Colon-separateduser:42:profile
Namespacedapp:env:entity:id:field
Versionedv2:user:42
AvoidSpaces, very long keys
Hash-tagged (Redis Cluster){user:42}:profile co-locates keys

2. Storing Simple Values

Example: Redis Strings

SET user:42:name "Ada Lovelace"
GET user:42:name
SET counter 100
INCR counter            # → 101
SET session:abc "..." EX 3600   # 1-hour TTL
MSET k1 v1 k2 v2

3. Implementing Complex Data Structures

TypeUse
HashHSET user:42 name Ada age 36
ListLPUSH / RPUSH queue work
SetSADD tags:42 "ml" — uniqueness
Sorted SetZADD leaderboard 100 user:42 — ranking
StreamXADD events * field val — event log
HyperLogLogPFCOUNT — approximate cardinality
Bitmap / GeoSETBIT, GEOADD

4. Setting TTL and Expiration

CommandUse
EXPIRE k 60Seconds TTL
PEXPIRE k 1000Milliseconds
EXPIREAT k timestampAbsolute
PERSIST kRemove TTL
SET k v EX 60 NXSet if not exists with TTL

5. Implementing Atomic Operations

MechanismDetail
Single commandINCR, GETSET — atomic
MULTI / EXECPipeline as transaction
WATCHOptimistic concurrency
Lua script (EVAL)Server-side atomic block
SETNX / SET ... NXDistributed lock primitive

6. Using Key-Value for Caching

PatternDetail
Cache-asideApp reads cache → DB on miss
Write-throughWrite both cache & DB
Write-behindBuffered async DB write
InvalidationTTL + explicit DEL on update
Cache stampedeMutex / probabilistic early refresh

7. Implementing Session Storage

AspectDetail
Keysession:<sid>
ValueHash or serialized JSON
TTLSliding (refresh on access)
SecurityLong random sid; httpOnly cookie
Sticky-lessCentralized store allows any app server

8. Designing for High Throughput

TipDetail
PipeliningBatch commands per round-trip
Cluster sharding16,384 slots in Redis Cluster
Avoid O(N) commandsKEYS *, large HGETALL
SCAN over KEYSNon-blocking iteration
Connection poolingReuse TCP connections

9. Implementing Persistence Strategies

OptionDetail
RDB snapshotPeriodic; smaller files; some data loss
AOF (append-only)Log every write; fsync policy controls RPO
RDB + AOFBest of both
No persistencePure cache; rebuildable
Replica + AOF on replicaOffload disk I/O

10. Handling Hot Keys

MitigationDetail
Local in-process cacheReduce remote hits
Key shardingcounter:{shard} + aggregate
Read replicasFan out hot reads
DetectRedis MONITOR / redis-cli --hotkeys