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.

See it run

Store by name, fetch by name, let entries end, count and lock safely, and spread names over machines.

Operations

Basic commands

Set, get, increment, expire and delete on one store.

Step 1 of 6

Set

keyvalue
user:1Alice

Alice is stored under user:1.

Step 1: Set

SET user:1 "Alice"SET session:abc '{"user":1}'GET user:1INCR counterEXPIRE session:abc 3600DEL session:abc
Cost
1 lookup each
Guarantee
By exact key

A missing key returns nil. Decide what your code does with nil before you write it.

In the real world

The same key-value database doing real jobs. Pick one and step through it.

A login is remembered for 30 minutes.

Step 1 of 3

Log in

keyvalue
session:k9fuser 7, 1800 s

The server makes a random id, stores the session under it for 1,800 seconds and sends the id in a cookie.

Step 1: Log in

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Value and lifetime in two steps

    major

    A crash between them leaves a key that never ends.

    Wrong
    SET session:abc dataEXPIRE session:abc 3600
    Right
    SET session:abc data EX 3600
  • Read, add, write

    critical

    Two clients overwrite each other.

    Wrong
    n = GET stockSET stock n - 1
    Right
    DECR stock   # then check the result# or a script that checks first
  • Listing keys to answer a question

    critical

    It walks every key while other requests wait.

    Wrong
    KEYS user:*
    Right
    SADD users 1SMEMBERS users    # small sets only
  • The only copy in a cache

    critical

    A restart, an eviction or a failover can remove it.

    Wrong
    SET order:9 data EX 86400
    Right
    INSERT the order in the databasethen cache a copy

Interview tips

  • How to explain it

    • A big dictionary behind a network.
    • Get, set, delete by exact key.
    • Hash the key to choose a machine.
  • Memory trick: KV

    • The Key opens the Vault.
    • No ticket, no coat.
    • NX: only if it does not exist.
  • Reach for it when

    • The key is always known.
    • Data is small and short-lived.
    • You need a counter, rank or lock.
  • Watch out for

    • Hot keys and big values.
    • Many keys expiring together.
    • What a crash loses.