Stop 07 · NoSQL DatabasesTopics · 8/12

Key-Value Store

Part of the Backend Developer Roadmap

In short

The simplest database idea there is: give it a key, get back a value. That simplicity is exactly why key-value stores are so fast and so easy to scale.

The simplest data model — every value is retrieved by a unique key, with no schema or query language beyond lookups — Redis and DynamoDB are common examples.

The blob takes a brass token from a traveller and hands back the matching suitcase.

Think of it like this

The railway cloakroom

At the station cloakroom you hand over your bag and get a brass token. Later you show the token and get that exact bag back. The attendant never opens bags or searches by colour. Key in, value out. That's a key-value store.

Watch it happen

Keys and their values

user:7:name = Riya
0
cart:7 = [3 items]
1
otp:7 = 482913
2
views:home = 1042
3

1/5Each entry is a key and a value. Colons in keys fake folders, like user:7:name.

The big ideas

What you need to know

Only the key is searchable

You fetch by exact key. Finding things by what's inside the value needs another tool or clever key design.

Name keys well

Use a pattern like object:id:field. Keys stay readable and different features don't collide.

Great for short-lived data

OTPs, sessions, rate-limit counters and carts fit perfectly: small, looked up by key, often expiring.

Easy to spread out

Keys can be split across many servers by hashing them, which is how stores like DynamoDB scale.

See it in code

Walk through the code

bash
1# Store and read a value2SET user:7:name "Riya"3GET user:7:name            # "Riya"4 5# An OTP that deletes itself after 5 minutes6SET otp:7 482913 EX 3007TTL otp:7                  # (integer) 3008 9# Atomic counter10INCR views:home            # (integer) 111 12# Set only if the key doesn't exist yet (a simple lock)13SET lock:report 1 NX EX 30

1/4The simplest pair: one key, one string value.

Type each command into redis-cli without the # notes. The notes just show what you'll get back.

Save yourself the pain

Common mistakes

Oops

Running KEYS * in production to find things.

Do this instead

KEYS walks every key and blocks Redis meanwhile. Use SCAN for browsing, and design keys you can look up directly.

Oops

Storing a huge JSON blob and rewriting it for every tiny change.

Do this instead

Use a hash (HSET) for objects whose fields you update separately.

Your mission

Build an OTP service

~30 min

Quick check

Which question can a plain key-value store answer quickly?

Go deeper

  1. 1Model a session store using simple key-value pairs.
  2. 2Compare lookup performance of a key-value store to indexed SQL lookups.
  3. 3Learn why key-value stores trade query flexibility for raw speed.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge