Design a Key-Value Store: The Ask
A key-value store is a store that saves a value under a key and returns that value when the key is presented. This lesson clarifies the ask, the first step of the interview method.
Put saves, get returns
A put saves a value under a key. A get with the same key returns that value.
store = {}
store["user:1:name"] = "Ana"
store["user:1:city"] = "Oslo"
store["cart:9:items"] = "books"
print("get user:1:name ->", store.get("user:1:name"))
print("get user:1:city ->", store.get("user:1:city"))
print("keys stored:", len(store))An overwrite and a missing key
A second put under the same key replaces the first value. A get for a key that was never saved finds nothing.
store = {"user:1:name": "Ana"}
store["user:1:name"] = "Ana Lee"
print("after overwrite:", store.get("user:1:name"))
print("missing key:", store.get("user:2:name"))
print("keys stored:", len(store))Only the exact key works
The store answers only the exact key presented. A shorter part of a key is a different key and finds nothing.
store = {"user:1:name": "Ana", "user:1:city": "Oslo", "user:2:name": "Ben"}
print("exact key:", store.get("user:1:name"))
print("part of a key:", store.get("user:1"))
print("keys stored:", len(store))Example
store = {}
store["session:a"] = "Ana"
store["session:b"] = "Ben"
store["session:c"] = "Cid"
store["session:b"] = "Ben Fox"
del store["session:a"]
print("session:b ->", store.get("session:b"))
print("session:c ->", store.get("session:c"))
print("session:a ->", store.get("session:a"))
print("entries left:", len(store))Key points
- Key-value store: a store built around one promise, that a value saved under a key comes back when that key is presented.
- Key: the short name a value is saved under and asked for by.
- Value: the data saved under a key, such as a name, a cart or a session.
- Put: the write that saves a value under a key.
- Get: the read that returns the value saved under a key.
- Delete: the write that removes the value saved under a key.
- Stated scale: this design must serve 50,000 gets and puts per second, the load named in the ask.
In this example, puts, an overwrite and a delete run against one store and 2 entries are left at the end. A get for the deleted key finds nothing, while the other keys still return their latest values.
Note
a key-value store is the NoSQL shape from the Beginner course, built for one-key lookups and not for SQL-style joins or questions across keys.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which promise does a key-value store make?