Choosing a Database · Lesson 66 of 112

Database Key-Value Stores and Caches

What you will learn

  • What a key-value store is
  • What a cache is and why expiry matters
  • What a key-value store cannot do
  • Typical uses

About the examples in this lesson. The Python code below is a small model of the idea, built from plain Python data (dictionaries, lists, JSON text) so you can run it in your browser. It is not a real database product. Real products of this kind are separate programs, usually run on a server, with many more features. This course does not run them; it teaches the idea so that you can recognise the kind and choose well.

1. The simplest database

A key-value store is like a Python dictionary that lives in a server: you put a value under a key and get it back by the same key. Nothing else is needed to find it, so lookups can be very fast. The value is usually opaque to the store: it does not look inside it.

import time

cache = {}

def put(key, value, seconds):
    cache[key] = (value, time.time() + seconds)

def get(key):
    item = cache.get(key)
    if item is None:
        return None
    value, expires = item
    if time.time() > expires:
        del cache[key]
        return None
    return value

def incr(key):
    new = (get(key) or 0) + 1
    put(key, new, 60)
    return new

put("user:1:name", "Rina", 0.2)
print(get("user:1:name"), get("missing"))
print(incr("visits"), incr("visits"), incr("visits"))
time.sleep(0.3)
print(get("user:1:name"))
Rina None
1 2 3
None
  • A key that exists returns its value; a missing key returns None.
  • incr is a counter: the first call creates it, and each later call adds one.
  • After 0.3 seconds the name had expired (it only lived 0.2 seconds), so it was gone.

Keys like user:1:name are a naming habit, not a rule: the store only sees a string.

2. Caches

A cache keeps a copy of an answer that is slow to produce, so the next request is quick. A key-value store is a natural cache. The pattern: look in the cache first; if the answer is missing, ask the real database and store the answer.

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE slow (id INTEGER PRIMARY KEY, name TEXT)")
con.executemany("INSERT INTO slow VALUES (?, ?)", [(1, "Rina"), (2, "Sam")])
calls = {"db": 0}
c2 = {}

def name_of(i):
    if i in c2:
        return c2[i]
    calls["db"] += 1
    c2[i] = con.execute("SELECT name FROM slow WHERE id = ?", (i,)).fetchone()[0]
    return c2[i]

for i in [1, 1, 2, 1, 2, 1]:
    name_of(i)
print("asked 6 times, database queried", calls["db"], "times")
asked 6 times, database queried 2 times

Six requests cost only two real queries. The price is stale data: if Rina's name changes in the database, the cache still holds the old one until it expires or is removed. Expiry times and "delete the cached copy when the data changes" are the usual cures.

3. What you give up

  • No joins and no SQL questions such as "all users in Dhaka": you must know the key.
  • Few or no rules about the values.
  • Data is often kept in memory for speed, so check what happens to it when the server restarts before trusting it with anything important. Redis, a well-known key-value store, lets you choose: periodic snapshots (RDB), a log of every write (AOF), both, or no persistence at all, which its documentation says is sometimes used when caching. The lesson is to choose the setting on purpose.

4. Typical uses

Use Example
Cache the result of a slow query or a rendered page
Sessions who is logged in, found by a session id
Counters page visits, rate limits
Temporary data one-time codes that expire

Worked example: a login session

When Rina logs in, the program creates a random session id, stores session:<id> with her user id and a 30-minute expiry, and sends the id to her browser. Each request looks up the id by key. After 30 minutes the key expires and she must log in again. No search, join or report is needed, so a key-value store is ideal. Her account details (name, password hash, orders) stay in a relational database.

The user is made up.

Common mistakes

  • Using a cache as the only copy of important data.
  • Forgetting expiry, so old answers live forever.
  • Trying to search by value in a store built to look up by key.

Key takeaways

  • A key-value store puts a value under a key and fetches it by that key, very fast.
  • A cache keeps answers to slow questions and relies on expiry to avoid stale data.
  • You give up joins, searching by value and most rules.
  • Keep the real, important data in a database built to keep it safe.

Practice

1. What is the only way to find a value in a key-value store?

Show answer

By its key.

2. In the demo, why did get("user:1:name") return None the second time?

Show answer

The value had expired after 0.2 seconds, and the 0.3-second sleep passed that time.

3. What is the risk of a cache?

Show answer

Stale data: the cached copy can differ from the real database until it expires or is removed.

4. In the second demo, how many real queries were made for 6 requests, and why?

Show answer

Two, one for each different id; the other four were answered from the cache.

5. Why is a key-value store a poor choice for "all customers in Dhaka"?

Show answer

It finds values only by key and does not look inside values, so it cannot filter by city.

6. Name two typical uses of a key-value store.

Show answer

For example caches and login sessions (also counters and expiring codes).