Key-value database
easy 24 minA key-value database stores a value under a unique name and returns it when you give that name back.
Video lesson · Chapter 1 of 5
The cloakroom gives Ana a ticket
Theory
Read or listen first. About 1 min.
What it is
A key-value database is a very large dictionary that lives on one or more servers. You set a value under a key, get it by the same key, and delete it. To the simplest stores the value is just bytes.
Some, such as Redis, know a few value types: lists, sets, hashes, sorted sets, streams. You can then change part of a value on the server in one step, for example add one to a counter.
Why it exists
Many requests already know the name of what they want: this session, this user's cart, this page's cached result. Parsing a query and planning joins for that is wasted work.
A single key also makes scaling simple. A hash of the key says which machine holds it, so machines rarely need to talk to each other to answer one request.
A short history
1979
AT&T releases dbm, a small database library by Ken Thompson. It stores values under keys in a file.
2003
Brad Fitzpatrick develops Memcached for LiveJournal: an in-memory cache shared by many web servers.
2007
Amazon publishes the Dynamo paper, "Amazon's Highly Available Key-Value Store".
2009
Redis is first released by Salvatore Sanfilippo, with lists and sets beside plain strings.
2012
Amazon launches DynamoDB, a managed service.
Words to know
- Key
- The unique name. It is the only way to find the value quickly.
- Value
- What is stored: text, bytes, a number, or a structure.
- TTL
- Time to live: after it, the entry is treated as gone.
- Eviction
- Removing entries because memory is full, which is not the same as expiry.
- Hash slot or partition
- A share of the keys, owned by one machine.
- Atomic operation
- One step that others see either fully done or not done.
- Hot key
- A single key asked for far more than the rest.
How it works
Step through the idea, or press Play.
Name it. A key such as session:abc that the reader can build
Understand it
Start here
The coat check
A theatre has a coat check with numbered hooks. Your number brings your coat back at once, whatever the coat looks like. Describing the coat instead is slow. A gym locker room with numbered lockers works the same way.
The number decides everything. Lose it, and the fast way is gone.
The idea
Pairs, and nothing between them
Three entries
| Key | Value | Why the key looks so |
|---|---|---|
user:1 | name Alice, email, as JSON | Kind, then id |
session:abc123 | user 1, as JSON | The browser sends abc123 |
counter:pageviews | 1000000 | One shared number |
user:1 and user:2 have nothing to do with each other.Very fast
One average O(1) lookup. In memory it takes far less time than the network trip to reach it.
Small interface
Get, set, delete, plus expiry and counters. Easy to learn, hard to misuse as a query engine.
Easy to spread
Hash the key to choose a machine. No joins cross machines.
Commands
The operations
| Operation | Redis command | What it does |
|---|---|---|
| Set | SET key value | Store or replace a value |
| Get | GET key | Return the value, or nil |
| Delete | DEL key | Remove a key |
| Exists | EXISTS key | Is the key there? |
| Expire | EXPIRE key 3600 | Remove it after 3,600 seconds |
| Increment | INCR counter | Add one, atomically; a missing key counts as 0 |
One GET on the server
Values
Redis data types
| Type | Holds | Example |
|---|---|---|
| String | Text, numbers, bytes, up to 512 MB | SET name Alice |
| Hash | Fields with values | HSET user:1 name Alice |
| List | Ordered items, both ends | LPUSH queue task1 |
| Set | Unique members, no order | SADD tags redis db |
| Sorted set | Members ranked by score | ZADD board 100 ana |
| Stream | Append-only log of entries | XADD events * k v |
A string holding JSON is replaced as a whole. A hash lets you change one field and lets two clients change different fields without losing each other's work. Choose by what you update.
Which type?
Keys
Designing key names
- 1
Kind first
cart:42, not42:cart, so that people can read and group them. - 2
Everything the reader knows
A key must be buildable from the request. If a reader must search for it, it is the wrong key.
- 3
Include what changes the answer
A cached page that depends on language and role needs both in its key, or one user sees another's page.
- 4
Version the shape
v2:user:1lets new code ignore old values after a deploy. - 5
Keep them short
A key is stored and sent each time. DynamoDB limits a partition key to 2,048 bytes.
Uses
Six common patterns
| Use | Key or command | Note |
|---|---|---|
| Session storage | session:{id} to user data | Set the TTL with the value |
| Caching | cache:{hash} to a result | See caching |
| Rate limiting | rate:{ip}:{window} to a count | See rate limiting |
| Leaderboard | ZADD board score user | Rank and top ten in O(log n) steps |
| Publish and subscribe | PUBLISH channel message | At most once: offline readers miss it |
| Distributed lock | SET lock:x token NX EX 30 | Release only with the same token |
A lock that is released safely
Scale
Spreading keys over machines
Slots in a cluster
Which slot?
hash mod nodes, adding one node would move most keys.Keys in different slots cannot take part in one multi-key command. Redis lets you force keys together with a hash tag: only the part in braces is hashed, as in {42}:cart and {42}:profile. Use it with care, because it can also create a hot slot.
Three problems of skew
| Problem | Sign | Remedy |
|---|---|---|
| Hot key | One node busy, others idle | Copy it to several keys, or cache it in the app for a second |
| Big value | Slow commands, network peaks | Split it, compress it, or use object storage |
| Same expiry | Many misses at one moment | Add a random amount to each TTL |
Safety
Memory, disk and loss
Cache only
Memcached keeps items in memory and throws out old ones when it is full. A restart empties it. Keep the truth elsewhere.
Memory with a log
Redis can write snapshots and an append-only file. With its default of one sync a second, about a second of writes can be lost in a crash.
Replicated on disk
A store such as DynamoDB or etcd keeps several durable copies, so one lost machine does not lose the data.
Expiry
- You choose a time per key
- Happens even with free memory
- Use it for sessions and codes
Eviction
- The store needs room
- A policy picks the victim, such as least recently used
- With Redis policy noeviction, writes fail instead
Redis replication is asynchronous by default, so a write that was confirmed can be lost if the primary fails before copying it. Its cluster specification says so plainly. Put the only copy of money somewhere else.
Beside a database
Numbers
Sizing a session store
Ten million users a day
Memory
Products
Popular key-value databases
| Product | Character | Seen in |
|---|---|---|
| Redis | In memory, many data types, optional persistence | Stack Overflow's 2016 design used it for caching and publish and subscribe |
| Memcached | Simple, multi-server cache; servers do not know each other | Facebook described its use in a 2013 paper |
| DynamoDB | Managed by AWS, items up to 400 KB | Amazon.com and its fulfilment centres |
| etcd | Strongly consistent store for small, critical data | Kubernetes keeps its cluster data in it |
Decide
When it fits
Is key-value enough?
Fits
- The key is always known
- Values are read and written whole, or by one simple step
- Short-lived data: sessions, codes, carts
- Very high rate of small operations
- A copy of data whose truth is elsewhere
Does not fit
- "All users in Oslo": a SQL or document question
- Transactions over many keys in many places
- Large files: object storage
- Search by words: full-text search
- Reports and sums over everything
Summary
The whole topic in one minute.
A key-value store trades questions for speed and simplicity. With the key you go straight to the value; without it you would look at everything.
Design the key names, the lifetime and the owner of the truth. Use atomic operations for counters and locks, spread keys by hash, watch hot keys and big values, and know what is lost when a node dies.
- Get, set and delete by a unique key, O(1) on average.
- The key must be buildable from the request.
- Set the lifetime with the value, and spread expiries.
- Use atomic steps for counters and locks.
- A hash of the key picks the machine; a hot key defeats the spread.
- Know what a crash loses before you store the only copy.