Search

Search papers and lessons

Key-Value Store

Level 2 · 11 min read

A key-value store keeps values under unique keys and offers three operations, put, get and delete, while a distributed one spreads those pairs across many machines.

On this page

  • Colour = topic mix
  • Discrete math
  • Probability
  • Calculus
  • Algorithms
  • Distributed systems
  • Networking
  • ReadReady to readNot yet

TL;DR

A key-value store is a database whose whole interface is three operations: put(key, value) stores a value under a key, get(key) returns the value for that key, and delete(key) removes it. It solves the problem of finding one record instantly, without writing a query language or scanning a table. A distributed key-value store runs those same three operations across many machines, so it can hold more data and survive machine failures.

Builds on: Hash Table, Distributed System, Quorum · Leads to: Distributed Hash Table, Cache-Aside Caching

Where it's used

Shopping carts and sessions at Amazon. The Dynamo paper (2007) describes a store that kept shopping carts and similar session data under a key such as the customer's ID. The reason for a key-value design was simple: a cart is always read and written by its key, never searched by its contents, and the site must keep answering even when some machines are down.

Caches in front of databases. Large web services often put a key-value store such as memcached or Redis between the application and the main database. A page asks the cache for user:1042:profile; on a hit it gets the answer from memory, without touching the database, and on a miss it reads the database and stores the result under the same key. The pattern is described in Cache-Aside Caching.

Cluster metadata. Systems such as etcd and ZooKeeper store small pieces of configuration, such as which server is the leader, as keys and values that every machine in a cluster reads. Here the store is small but must be correct, so it is replicated with care.

How it works

Take a tiny distributed store with three nodes, called N0, N1 and N2. To keep the arithmetic visible, use a toy hash function: give each letter its position in the alphabet (a = 1, b = 2, ..., z = 26), add the positions in the key, and take the remainder after dividing by 3. Call this hh. So h("ann")h(\text{"ann"}) is computed as follows.

  1. The client wants to store the pair ann -> "x1". It does not know which node should hold it, so it computes the owner of the key. Its position values are a = 1, n = 14, n = 14, which add to 29. The remainder of 29 divided by 3 is 2, so the owner is N2.
  2. The client sends put("ann", "x1") to N2. N2 writes the pair into its own memory (or disk) and sends back "ok".
  3. Later, another client calls get("ann"). It computes the same owner, 2, and asks N2 directly. N2 finds ann in its table and returns "x1".
  4. The client never asked every node. It went straight to one node because the key told it where to go. This is the whole trick: a deterministic function from key to node.
flowchart LR
  C[Client] -->|"put or get ann"| H["owner = h(ann) mod 3 = 2"]
  H --> N2[Node N2 holds ann]
  N2 -->|"x1"| C

Two more keys show the placement. "bob" has position sum 2 + 15 + 2 = 19, and 19 mod 3 = 1, so N1 holds it. "cy" has 3 + 25 = 28, and 28 mod 3 = 1, so N1 holds it too. Each node keeps only the keys it owns.

Real stores add three things to this picture: the nodes are on different machines reached by a network, each value is copied to several nodes so one crash does not lose it, and the owner function is designed so that adding a node moves few keys. The last point is the one that most often breaks naive designs, and it gets its own section below.

The math

A key-value store is a partial function. Let KK be the set of all possible keys and VV the set of all possible values. The store is a mapping S:K→VS : K \to V that has a value for only some keys. The three operations are:

put(k,v):S(k)←v\text{put}(k, v): \quad S(k) \leftarrow v get(k):return S(k) if defined, otherwise "not found"\text{get}(k): \quad \text{return } S(k) \text{ if defined, otherwise "not found"} delete(k):remove k from the domain of S\text{delete}(k): \quad \text{remove } k \text{ from the domain of } S

Step 1 in symbols: choosing the owner

With nn nodes numbered 00 to n−1n-1, the owner of a key is

owner(k)=h(k) mod n\text{owner}(k) = h(k) \bmod n

Here hh is a hash function that turns a key into a whole number, and  mod \bmod gives the remainder after division. In the toy example, h("ann")=29h(\text{"ann"}) = 29 and 29 mod 3=229 \bmod 3 = 2.

The cost of changing the number of nodes

Suppose the store grows from nn to n+1n+1 nodes. A key stays where it was only if h(k) mod n=h(k) mod (n+1)h(k) \bmod n = h(k) \bmod (n+1). For a hash that spreads keys evenly, about a fraction 1n+1\frac{1}{n+1} of keys stay put, so the fraction that move is about

1−1n+1=nn+11 - \frac{1}{n+1} = \frac{n}{n+1}

Going from 3 nodes to 4 moves about 34\frac{3}{4}, or 75 percent, of all keys. Check this with the toy example: "ann" moves from 2 to 29 mod 4=129 \bmod 4 = 1, "bob" moves from 1 to 19 mod 4=319 \bmod 4 = 3, and "cy" moves from 1 to 28 mod 4=028 \bmod 4 = 0. All three moved. The approximation is for large numbers of keys; three keys are too few to show it well.

Replication and quorums

To survive a crash, each key is stored on NN nodes. A write waits for WW of them to confirm, and a read asks RR of them. If R+W>NR + W > N, every read group shares at least one node with every write group, so a read sees the latest confirmed write. This is the rule from Quorum.

Worked examples

Example
1. Tiny: one put and one get

Store ann -> "x1" in the three-node toy store, then read it back.

  1. Compute the sum for "ann": a = 1, n = 14, n = 14. Total 29.
  2. Divide by 3: 29 = 3 × 9 + 2. Remainder 2. Owner is N2.
  3. put goes to N2, which stores the pair.
  4. get("ann") computes the same remainder, 2, and asks N2. N2 returns "x1".

The answer is "x1", and only N2 was contacted.

Example
2. Standard: adding a node with plain modulo

The store grows from 3 nodes to 4. Recompute the owner of "bob" and "cy".

  1. "bob": sum 19. Before, 19 mod 3 = 1. Now, 19 mod 4: 4 × 4 = 16, remainder 3. Owner changes from N1 to N3.
  2. "cy": sum 28. Before, 28 mod 3 = 1. Now, 28 mod 4 = 0, since 4 × 7 = 28. Owner changes from N1 to N0.
  3. "ann": sum 29. Before, 2. Now, 29 mod 4: 4 × 7 = 28, remainder 1. Owner changes from N2 to N1.
  4. All three keys moved. A client that still uses the old count of 3 nodes will look in the wrong place for every one of them.

Moving almost every key is the cost the consistent hashing lesson removes.

Example
3. Realistic: a shopping cart with three replicas

A cart for customer 88 is stored on three replicas, A, B and C, with N=3N = 3, W=2W = 2, R=2R = 2. Each copy carries a version number.

  1. A write adds a book. The client sends put("cart:88", v2) to all three replicas. A and B confirm, which is 2 = WW. The write counts as successful, even though C has not answered yet.
  2. C is slow, and it still holds the old cart v1, which has no book.
  3. A read asks two replicas chosen at random, say B and C. Each returns its copy: B returns v2 and C returns v1.
  4. Among the two replies the read keeps the highest version, v2, so the customer sees the book.
  5. The read can also repair C by sending v2 back to it, so the stale copy is updated.
  6. Check the overlap. The write group {A, B} and read group {B, C} share B, because R+W=4>3=NR + W = 4 > 3 = N. That shared node is why the read found the newest version.

Try it: a store has N=5N = 5 replicas, and it uses W=3W = 3 and R=2R = 2. Does every read group share a replica with every write group? Answer: No. R+W=5R + W = 5, which is not greater than N=5N = 5, so a read of two replicas can miss all three replicas that confirmed the write. Changing to R=3R = 3 gives R+W=6>5R + W = 6 > 5, and then the groups always overlap.

Common mistakes and tradeoffs

It is tempting to think a key-value store is just a hash table on a network. In fact a hash table lives in one machine's memory, while a key-value store must handle machines that crash, messages that arrive late or never, and copies that disagree. The hash table lesson gives the local idea, and Distributed System explains the new failures.

It is tempting to think that get always returns the latest put. In fact, with replication and R+W≤NR + W \le N, a read can return an older version, as the Try it in Example 3 shows with N=5N = 5, W=3W = 3 and R=2R = 2. Systems document which guarantee they give, and that is a choice with a price.

It is tempting to place keys with hash(k) mod n. In fact, this is simple and fast, but it moves about nn+1\frac{n}{n+1} of all keys when a node joins. Consistent Hashing places nodes and keys on a ring so that a join or leave moves only about 1n+1\frac{1}{n+1} of keys.

It is tempting to add replicas until nothing can go wrong. In fact each extra replica costs storage and write time, and a larger WW makes writes wait for slower nodes. The right values of NN, RR and WW depend on whether the workload reads more than it writes and whether stale reads are acceptable.

When to use a key-value store: the access pattern is by a known key, the value is opaque to the store, and speed and availability matter more than complex queries. When not to use it: you need to search by fields of the value, join tables, or enforce relations between records. In that case a relational database or a document store is the better fit. Alternatives for hot data are an in-memory cache with a Cache-Aside Caching policy, which is itself a key-value store with a short life.

History

Before networks were common, programs stored records by key in files with an index built on hashing or sorted trees, so the idea of "get by key" was already old. What was new in the 2000s was doing it across thousands of cheap machines. The Chord paper, published in 2003, showed how to find the owner of a key in a few network hops without a central index, which is the foundation of the Distributed Hash Table. In 2007 Amazon published the Dynamo paper, which described a production store built from the same ideas: consistent hashing for placement, replicas with quorums, and versions to reconcile conflicts. Its influence is why many later stores use the same shape.

Recap

  • A key-value store offers put, get and delete over unique keys, and nothing else.
  • A key determines its owner through a function, so a client goes straight to one node.
  • Plain modulo placement moves most keys when the node count changes. Ring-based placement, as in Consistent Hashing, moves few.
  • Each key is copied to several nodes. With NN copies, WW confirmations for a write and RR replies for a read, R+W>NR + W > N makes reads see the latest confirmed write (Quorum).
  • Read next: Distributed Hash Table for placement with no central directory, and Cache-Aside Caching for using a store as a cache in front of a database.

Check yourself

QuestionWhat three operations make up the interface of a key-value store?Show answer
put(key, value) stores a value under a key, get(key) returns the value for a key, and delete(key) removes a key and its value.
QuestionA store has 4 nodes and uses owner = h(k) mod 4. A key has h(k) = 23. Which node owns it, and what would its owner be after the store grows to 5 nodes?Show answer
23 mod 4 = 3, since 4 × 5 = 20 and 23 − 20 = 3, so node 3 owns it. After growing to 5 nodes, 23 mod 5 = 3, since 5 × 4 = 20 and 23 − 20 = 3, so node 3 still owns it. The key stays in this case, but many others would move.
QuestionWhy does a write that is sent to all NN replicas count as successful once only WW confirm, and why can a read still see it?Show answer
The write counts as successful once WW replicas confirm, which is the quorum rule (Quorum). A read waits for RR replies. If R+W>NR + W > N, the read set and the write set must share at least one replica, and that shared replica holds the confirmed write, so the read can see it.
QuestionA store has N=3N = 3 replicas, with W=2W = 2 and R=1R = 1. A write is confirmed by replicas A and B. A read asks only replica C. Can the read return the old value, and why?Show answer
Yes. R+W=3R + W = 3, which is not greater than N=3N = 3, so the read group {C} and the write group {A, B} do not overlap. C may still hold the old value, so the read can return it.
QuestionWhy would a team choose a key-value store over a relational database for a user session cache, and what would it give up?Show answer
A session is read and written by its key and its value is never searched by its fields, so a key-value store matches the access pattern and is fast and simple to scale. It gives up queries on fields of the value, joins across tables, and in a replicated setup possibly the guarantee of reading the latest write unless R+W>NR + W > N is chosen.

Sources

Key-Value Store — explained simply · ungoon.me