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.
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
| key | value |
|---|---|
| user:1 | Alice |
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
| key | value |
|---|---|
| session:k9f | user 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
majorA crash between them leaves a key that never ends.
WrongSET session:abc dataEXPIRE session:abc 3600RightSET session:abc data EX 3600Read, add, write
criticalTwo clients overwrite each other.
Wrongn = GET stockSET stock n - 1RightDECR stock # then check the result# or a script that checks firstListing keys to answer a question
criticalIt walks every key while other requests wait.
WrongKEYS user:*RightSADD users 1SMEMBERS users # small sets onlyThe only copy in a cache
criticalA restart, an eviction or a failover can remove it.
WrongSET order:9 data EX 86400RightINSERT 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.