SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Relational Databases
  • Document Databases
  • Key-Value Databases
  • Full-Text Search Engines
  • Wide Column Databases
  • Time Series Databases
  • Graph Databases
  • Vector Databases
  • NewSQL Databases
  • Columnar Databases
  • In-Memory Databases
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Types (Deep Dive)

Key-Value Databases

A giant dictionary: give a key, get a value, very fast (Redis, DynamoDB).

โฑ 12 min readBeginnerMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A key-value database is a giant dictionary. You put a value under a key, and later get it back by that same key. Nothing more.

  • The store does not look inside the value. It only needs the key.
  • Because the access is so simple, it can be very fast and easy to spread over many machines.
  • Examples: Redis (in memory), DynamoDB (managed, on disk), Memcached, etcd, RocksDB.

02Concept: What is it?

Think of the dict in Python or the Map in JavaScript, but shared by many servers and able to survive a restart. The key is a string like user:42. The value can be anything: text, a number, a JSON blob, an image thumbnail.

The database hashes the key (turns it into a number) and uses that number to find the right machine, called a partition or node. One hash, one machine, one lookup. That is why it is fast, and why it scales so well: adding machines adds capacity.

How a key finds its machine
๐Ÿ”‘Keyuser:42
โ†’โ†“hash
#๏ธโƒฃNumber2 913 077 100
โ†’โ†“mod N
๐ŸงฑP0
๐ŸงฑP1
๐ŸงฑP2
โ†’โ†“value
๐Ÿ“ฆValue{"name":"Asha"}
The same key always hashes to the same number, so the same machine always has it.
๐Ÿง The trade you make
You give up rich queries (no joins, usually no "find all users in Pune"). In return you get tiny, predictable latency and easy scaling.

03Real-Life Example

๐ŸตThe Cloakroom Counter
At a theatre, you hand over your coat and get a numbered token. To get the coat back, you show the token. The attendant does not search by coat colour or owner name. He goes straight to hook 42. If you lose the token, the coat is hard to find. If the cloakroom is very busy, you add more attendants, each in charge of a range of hooks.
Cloakroom
Key-value database
The numbered token
The key
The coat
The value
Handing in a coat
PUT key value
Showing the token
GET key
Going straight to hook 42
Hash the key to find the partition
Several attendants, each owning some hooks
Partitions over many nodes
Coats are thrown out after closing time
TTL (time to live)
Everyone queues for the same VIP coat
A hot key
A cache-aside lookup with a key-value store
๐Ÿง‘โ€๐Ÿ’ปApp
โ†’โ†“GET user:42
โšกRediskey-value
โ‡ขโ‡ฃmiss
๐Ÿ—„๏ธMain database

04Why Do We Need It?

โšกVery low latency
In-memory stores like Redis answer in well under a millisecond on a good network.
๐Ÿ“ˆEasy to scale
The key tells you the machine. No joins across machines.
๐Ÿง Simple to use
Three verbs: put, get, delete. Little to learn.
โณExpiry built in
Set a TTL and the store removes old data by itself.
๐Ÿ›ก๏ธPredictable
Every request does the same small amount of work.
๐ŸงฐMany shapes
Redis adds lists, sets, sorted sets and counters on top of plain values.
If you always know the key, you do not need a query language.

05Where Do We Use It?

โšกCaches
Hold results of slow queries or API calls.
๐Ÿ”Sessions and tokens
Login sessions with an expiry time.
๐ŸšฆRate limits and counters
Count requests per user per minute.
๐Ÿ†Leaderboards
Redis sorted sets keep scores in order.
๐Ÿ›’Shopping carts and preferences
Look up by user id, read and write often.
๐ŸงญConfig and coordination
etcd and similar stores keep settings and leader locks.

06Types / Parts / How It Works

Flavours of key-value stores

KindHow it keeps dataGood for
In-memoryAll data in RAM. Optional snapshots or a log on disk. (Redis, Memcached)Caches, sessions, counters, leaderboards. Fastest, but memory is costly.
Persistent on diskData on SSD, often with a cache in front. (DynamoDB, Riak, Aerospike)Primary data at huge scale with steady latency.
Embedded enginesA library inside your process. (RocksDB, LevelDB)The building block inside other databases.
Consistent coordination storesSmall, strongly consistent data replicated with a consensus protocol. (etcd, ZooKeeper)Config, locks, leader election. Not for big data.
Redis
In-memory
  • Sub-millisecond reads
  • Rich types: lists, sets, hashes
  • Data limited by RAM
  • Persistence is optional
DynamoDB
Managed, on disk
  • Single-digit millisecond at any size
  • Almost no servers to run
  • Limited queries (key + indexes)
  • Pay for reads and writes

Spreading keys over machines

MethodIdeaNote
Hash mod Npartition = hash(key) mod N.Simple, but changing N moves almost every key.
Consistent hashingKeys and nodes sit on a ring. A key belongs to the next node.Adding a node moves only a small share of keys.
Hash slotsA fixed number of slots (Redis Cluster has 16,384) map to nodes. Move slots, not keys.Easy to rebalance.
Range partitioningKeys are split by sorted ranges.Allows range scans, but can create hot ranges.
Hot key: one popular key overloads one machine
Even load
Partition 0
Partition 1
Partition 2
One hot key
Partition 0
Partition 1hot
Partition 2
Fine Overloaded
More machines do not help. Split the key or cache it in front.
VisualizerHash a key, set a TTL, and break a partition with a hot keyPut and get a few keys and watch which partition owns them. Press Wait to see a TTL expire. Then drag the hot key share and try splitting the key into copies.
Key
Clock
0 s
Live keys
0
0 expired
The key space is cut into 4 partitions. Each key goes to the partition hash(key) mod 4. The tag shows where each sample key would live.
user:1 โ†’ P3user:2 โ†’ P0cart:7 โ†’ P0session:ab โ†’ P2product:42 โ†’ P2otp:991 โ†’ P1
Partition 0
empty
Partition 1
empty
Partition 2
empty
Partition 3
empty
Pick a key, then Put it. The key is hashed, and the hash decides which partition (machine) owns it.
Now the hot key problem
Mitigation
Load per partition (dashed line = what one partition can serve: 1,000 req/s)
468
P0
468
P1
1632
P2
432
P3
Busiest partition
1632
req/s
Overloaded partitions
1
Average load
750
if perfectly even
Partition 2 gets 1632 req/s, above its 1,000 limit, even though the average is only 750. Adding more machines does not help, because the one hot key still lives on one machine. Try splitting it into copies.

A simulated clock and a fixed hash, so the picture is the same every time. Real stores use stronger hashes and often consistent hashing or hash slots (Redis Cluster has 16,384) instead of a plain modulo, so that adding a machine does not reshuffle every key.

07How to Use It / Steps / Implementation

Using a key-value store well

  1. 1
    Check that you always know the key
    If you need to search by other fields, add an index store or choose another database.
  2. 2
    Design readable keys
    Use a pattern such as user:42:profile. Keep keys short. They use memory too.
  3. 3
    Keep values small
    Large values slow the network and block a single-threaded server like Redis. Big blobs belong in object storage.
  4. 4
    Set a TTL when data is temporary
    Sessions, caches and one-time codes should expire. Add jitter so they do not all expire together.
  5. 5
    Choose durability on purpose
    Decide if losing the last second of data is acceptable (snapshots, append-only log, or replicas).
  6. 6
    Watch for hot keys
    Monitor the top keys. Split a hot counter into several sub-keys, or add a local cache.
  7. 7
    Plan the partition scheme
    Prefer consistent hashing or hash slots so you can add nodes without a reshuffle.
Redis style commands
SET session:ab91 "{user:42}" EX 1800    # value + expire in 30 minutes
GET session:ab91
INCR rate:user:42:2026-12-02T10:15       # atomic counter
EXPIRE rate:user:42:2026-12-02T10:15 60
DEL session:ab91
โš ๏ธDo not use KEYS * in production
Commands that scan every key can freeze a busy server. Use cursor-based commands like SCAN, or avoid the need.

08Key Terms to Know

TermMeaning in easy words
KeyThe unique name you use to find a value
ValueThe data stored under a key. The database usually treats it as opaque bytes
Hash functionA function that turns a key into a number in a repeatable way
Partition / nodeOne machine (or slice of the key space) that stores part of the data
TTLTime to live: after this time the key is removed
Hot keyA key that gets far more traffic than others
Consistent hashingA way to place keys so adding or removing a node moves few of them
Hash slotOne of a fixed number of buckets (Redis Cluster: 16,384) that keys are assigned to
EvictionRemoving keys when memory is full (see Cache Eviction Policies)
PersistenceSaving in-memory data to disk, for example snapshots or an append-only log
Atomic operationAn operation that cannot be seen half-done, such as INCR

09Pros, Cons and Trade-offs

โœ… Pros
  • Very fast, predictable reads and writes
  • Simple model and API
  • Scales out easily
  • TTL and counters built in
  • Great for caches and sessions
โš ๏ธ Cons
  • No rich queries, joins or relationships
  • You must know the key
  • Hot keys can overload one machine
  • In-memory stores are limited by RAM and its cost
  • Weaker or optional durability in some setups
  • Data models move into your application code

Trade-offs

ChoiceWe gainWe lose
In-memoryLowest latencyCost per GB, and risk of data loss if not persisted
On diskLarger and cheaper dataA little more latency
Persistence onSurvives restartsExtra disk work, slower writes
ReplicasAvailability and read capacityPossible stale reads, extra cost
Small valuesSpeedMore keys to manage
Eventual consistency (DynamoDB default read)Cheaper and faster readsA read may be a moment old (strong reads are optional)

10Common Problems and Mistakes

Common mistakes

  1. Treating it as a full database. Wanting "all orders of a user in March" from a plain key-value store leads to scans.
  2. Huge values. One 50 MB value stalls others behind it on a single-threaded server.
  3. No TTL. Memory grows until the server is full and starts evicting or failing.
  4. Hot keys. One global counter or one celebrity key takes all the load.
  5. Hash mod N with changing N. Adding a node remaps almost every key, so the cache goes cold at once.
  6. Assuming it is durable. An in-memory store with default settings may lose recent writes on a crash.
  7. Scanning all keys. It blocks or slows production.

Things to watch

๐Ÿ”ฅHot keys
Split into sub-keys, or put a small local cache in front.
๐Ÿ’พMemory
Track used memory and the eviction policy.
๐Ÿ•ฐ๏ธStale replicas
Replicas may lag. Do not read your own write from one by accident.
๐Ÿ”Security
A key-value store on an open port is a common data leak. Use auth and private networks.

11Real-World Examples

๐ŸŸฅRedis
Used by many companies for caches, sessions, rate limiters, queues and leaderboards.
โšกDynamoDB
Powers large shopping and gaming workloads on AWS, with steady low latency at any size. The original Dynamo paper (2007) inspired many stores.
๐ŸงชMemcached
A simple, multi-threaded in-memory cache used by large web sites.
๐ŸงฑRocksDB
An embedded engine that other databases build on.
๐Ÿงญetcd
Holds Kubernetes cluster state and settings.
๐ŸŒCloud caches
Managed offerings such as ElastiCache and Azure Cache run Redis or Memcached for you.
๐Ÿ“Note
These are general ideas. Limits and features depend on the product and version.
Mini case: login sessions
๐Ÿ‘คBrowsercookie: ab91
โ†’โ†“request
๐Ÿ–ฅ๏ธWeb serversstateless
โ†’โ†“GET session:ab91
๐ŸŸฅRedis clusterTTL 30 min
Each session is a key with a TTL. The check is one fast lookup on every request.

12Related Topics to Read Next

Common Database Typesโ†’

Where key-value stores sit among the others.

SQL vs NoSQLโ†’

Why you might pick a simple store over SQL.

Consistent Hashingโ†’

How keys are placed so nodes can join and leave smoothly.

Distributed Cache Architectureโ†’

Key-value stores are the usual cache engine.

Cache Eviction Policiesโ†’

What happens when the memory is full.

Partitioningโ†’

The wider idea of splitting data by key.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: a giant dictionary. PUT, GET, DEL by key.
  • โœ”Fast because: hash the key, go to one machine, no scans or joins.
  • โœ”Partitioning: consistent hashing or hash slots beat plain hash mod N.
  • โœ”Use for: caches, sessions, counters, rate limits, leaderboards, carts.
  • โœ”TTL: give temporary data an expiry, with jitter.
  • โœ”Weakness: no rich queries. You must know the key.
  • โœ”Watch: hot keys, big values, memory, durability settings.
  • โœ”One line: โ€œKnow the key, get the value, and scale by splitting the keys.โ€
โ† Previous
Document Databases
Next โ†’
Full-Text Search Engines