AlgoViz

Key-value database

easy 24 min

A 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

0:00 / 3:25

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

  1. 1979

    AT&T releases dbm, a small database library by Ken Thompson. It stores values under keys in a file.

  2. 2003

    Brad Fitzpatrick develops Memcached for LiveJournal: an in-memory cache shared by many web servers.

  3. 2007

    Amazon publishes the Dynamo paper, "Amazon's Highly Available Key-Value Store".

  4. 2009

    Redis is first released by Salvatore Sanfilippo, with lists and sets beside plain strings.

  5. 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.

Step 1 of 4

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.

Six is enough
12345678COAT CHECK6

The number decides everything. Lose it, and the fast way is gone.

The idea

Pairs, and nothing between them

Three entries

KeyValueWhy the key looks so
user:1name Alice, email, as JSONKind, then id
session:abc123user 1, as JSONThe browser sends abc123
counter:pageviews1000000One shared number
The colon is a convention. To the store a key is one string, and 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

OperationRedis commandWhat it does
SetSET key valueStore or replace a value
GetGET keyReturn the value, or nil
DeleteDEL keyRemove a key
ExistsEXISTS keyIs the key there?
ExpireEXPIRE key 3600Remove it after 3,600 seconds
IncrementINCR counterAdd one, atomically; a missing key counts as 0
INCR works on 64-bit signed integers stored as text.

One GET on the server

Redis removes expired keys in two ways: when someone asks for them, and by sampling in the background.

Values

Redis data types

TypeHoldsExample
StringText, numbers, bytes, up to 512 MBSET name Alice
HashFields with valuesHSET user:1 name Alice
ListOrdered items, both endsLPUSH queue task1
SetUnique members, no orderSADD tags redis db
Sorted setMembers ranked by scoreZADD board 100 ana
StreamAppend-only log of entriesXADD events * k v
Redis has more types, such as JSON, geospatial and probabilistic ones. Six cover most designs. There is no table type.

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?

Lists fit simple queues; streams fit queues where work must be acknowledged.

Keys

Designing key names

  1. 1

    Kind first

    cart:42, not 42:cart, so that people can read and group them.

  2. 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. 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. 4

    Version the shape

    v2:user:1 lets new code ignore old values after a deploy.

  5. 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

UseKey or commandNote
Session storagesession:{id} to user dataSet the TTL with the value
Cachingcache:{hash} to a resultSee caching
Rate limitingrate:{ip}:{window} to a countSee rate limiting
LeaderboardZADD board score userRank and top ten in O(log n) steps
Publish and subscribePUBLISH channel messageAt most once: offline readers miss it
Distributed lockSET lock:x token NX EX 30Release only with the same token

A lock that is released safely

The compare and delete must be one step on the server, for example a short script.

Scale

Spreading keys over machines

Slots in a cluster

An app asks for session abc. A hash of the key picks slot 8000. Node 1 holds slots 0 to 5460, node 2 holds 5461 to 10922 and node 3 holds 10923 to 16383, so the request goes to node 2.
Redis Cluster has 16,384 slots. The slot number here is an example. Clients remember the slot map and go straight to the right node.

Which slot?

slot=CRC16(key) mod 16384163843≈5461 slots per node\text{slot} = \text{CRC16}(\text{key}) \bmod 16384 \qquad \frac{16384}{3} \approx 5461 \text{ slots per node}
Moving a slot moves only its keys. With plain 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

ProblemSignRemedy
Hot keyOne node busy, others idleCopy it to several keys, or cache it in the app for a second
Big valueSlow commands, network peaksSplit it, compress it, or use object storage
Same expiryMany misses at one momentAdd 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

Users send requests to an app. The app first gets from a key-value store that holds copies and sessions, and on a miss reads the database that holds the truth.
The most common place for a key-value store. Losing it makes the system slow, not wrong.

Numbers

Sizing a session store

Ten million users a day

10,000,000×20100,000=2,000/s×3=6,000/s\frac{10{,}000{,}000 \times 20}{100{,}000} = 2{,}000/\text{s} \qquad \times 3 = 6{,}000/\text{s}
Assume 20 requests per user and day, each reading the session once. The peak is three times the average.

Memory

10,000,000×(1,000+100) B=11 GB10{,}000{,}000 \times (1{,}000 + 100)\,\text{B} = 11\,\text{GB}
Assume 1 KB per session and 100 bytes for the key and bookkeeping. One machine with 32 GB leaves room for growth and for a copy while saving; a second one is for failure, not for load.

Products

Popular key-value databases

ProductCharacterSeen in
RedisIn memory, many data types, optional persistenceStack Overflow's 2016 design used it for caching and publish and subscribe
MemcachedSimple, multi-server cache; servers do not know each otherFacebook described its use in a 2013 paper
DynamoDBManaged by AWS, items up to 400 KBAmazon.com and its fulfilment centres
etcdStrongly consistent store for small, critical dataKubernetes keeps its cluster data in it
etcd limits a request to 1.5 MiB and storage to 2 GiB by default. It is for configuration, not for user data.

Decide

When it fits

Is key-value enough?

The second question picks the product; the first decides whether the family fits at all.

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

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.

Sources