Valkey Tutorial: Cache Your Shop Pages the Fast Way
Quick answer
Valkey is an open source, in-memory data store that speaks the same protocol as Redis, so existing Redis clients and commands work with it unchanged. It started as a community fork of Redis. This post starts a local Valkey server, caches a shop product page, counts page views, and fixes the error when a counter command hits a string key.
A customer opens the White Cotton Kurta page on a small Karachi clothing shop. The page shows the name, the price of Rs 2,450, and sizes in stock. Behind it, the app asks the database for those details on every visit, even though the price and sizes change once a week. The database repeats the same work hundreds of times a day for an answer that barely moves. That is the exact job a cache exists for: keep the answer in fast memory, and fetch it again only when it changes. Valkey is one of the simplest tools for the job, and runs on a laptop in seconds.
What I would check before using it
My first check is whether the cached data is safe to lose. A cache is a copy, not the original. If Valkey restarts and the pages vanish, the shop must rebuild them from the database, and the PostgreSQL Explained: The Reliable Database You Default To post covers the database that should hold the originals. If losing the data would lose orders or payments, it never belongs in a cache.
My second check is what the team already runs. Valkey speaks the Redis protocol, so a shop already using Redis can point its client at Valkey and keep the same commands, and the Redis Explained: The In-Memory Store That Speeds Things Up post covers that shared ground. The switch is mostly a connection string change, not a rewrite.
My third check is the memory budget. Valkey keeps everything in RAM, so a cache that grows without a limit will run the machine out of memory. Every key that can grow, like a cart or a session, needs an expiry, and the server needs a maxmemory limit with an eviction policy that drops least recently used keys first. A cache that rebuilds from the database rarely needs snapshots to disk.
My verdict, as judgement: adopt Valkey when the same reads repeat often and answers change slowly, like product pages, featured lists, and sessions. It flips when the data must never be lost, when the working set is bigger than the RAM, or when there is no database to rebuild the cache from.
Caching a Karachi shop page, counting views, and fixing the wrong-type error
The demo is a small Karachi clothing shop, a White Cotton Kurta for Rs 2,450 and an Embroidered Lawn Suit for Rs 4,850, against a local Valkey 9.2.1 server on 7777. The usual route is Docker:
$ docker run -p 7777:6379 valkey/valkey
I built the server from the official source tarball instead: the release ships source, not a prebuilt Linux binary:
$ tar xzf valkey-9.2.1.tar.gz
$ cd valkey-9.2.1
$ make BUILD_TLS=no MALLOC=libc
$ ./src/valkey-server --port 7777 --daemonize yes --save '' --dir .
$ ./src/valkey-cli -p 7777 PING
PONG
The script below is plain Python with only the standard library. It opens a socket and speaks RESP, the protocol Valkey and Redis share:
import socket
import time
def send_recv(sock, *args):
parts = [f"*{len(args)}\r\n".encode()]
for a in args:
b = a if isinstance(a, bytes) else str(a).encode()
parts.append(f"${len(b)}\r\n".encode() + b + b"\r\n")
sock.sendall(b"".join(parts))
buf = b""
while not buf.endswith(b"\r\n"):
chunk = sock.recv(4096)
if not chunk:
break
buf += chunk
return parse(buf)
def parse(buf):
kind = buf[:1]
rest = buf[1:]
if kind == b"+":
return rest.rstrip(b"\r\n").decode()
if kind == b"-":
return "ERROR: " + rest.rstrip(b"\r\n").decode()
if kind == b":":
return int(rest.rstrip(b"\r\n"))
if kind == b"$":
n = int(rest.split(b"\r\n")[0])
if n == -1:
return None
start = rest.index(b"\r\n") + 2
return rest[start:start + n].decode()
if kind == b"*":
n = int(rest.split(b"\r\n")[0])
items, pos = [], rest.index(b"\r\n") + 2
for _ in range(n):
assert rest[pos:pos + 1] == b"$"
end = rest.index(b"\r\n", pos)
ln = int(rest[pos + 1:end])
pos = end + 2
items.append(rest[pos:pos + ln].decode())
pos += ln + 2
return items
return repr(buf)
def main():
s = socket.create_connection(("127.0.0.1", 7777), timeout=5)
c = lambda *a: send_recv(s, *a)
print("PING:", c("PING"))
print("FLUSHALL:", c("FLUSHALL"))
# 1. Cache a product page (JSON string) with a 60 second TTL.
page = '{"name": "White Cotton Kurta", "price_rs": 2450, "sizes": ["S", "M", "L"]}'
print("SET page:product:1:", c("SET", "page:product:1", page, "EX", 60))
print("GET page:product:1:", c("GET", "page:product:1"))
print("TTL page:product:1:", c("TTL", "page:product:1"), "seconds left")
# 2. A short-lived flash-sale banner: 2 second TTL, then it is gone.
print("SET flash banner:", c("SET", "flash:banner", "Eid sale: 20% off lawn", "EX", 2))
print("GET flash banner now:", c("GET", "flash:banner"))
time.sleep(3)
print("GET flash banner after 3s:", c("GET", "flash:banner"))
# 3. Page-view counter for the kurta page.
print("INCR views:", c("INCR", "views:product:1"))
print("INCR views:", c("INCR", "views:product:1"))
print("INCR views:", c("INCR", "views:product:1"))
print("GET views:", c("GET", "views:product:1"))
# 4. The thing that goes wrong: INCR on a string key.
print("INCR on page:product:1:", c("INCR", "page:product:1"))
print("Fix: use a separate counter key, page stays a string:",
c("GET", "page:product:1")[:40] + "...")
# 5. A product as a hash, and featured products as a sorted set.
print("HSET product:2:", c("HSET", "product:2", "name",
"Embroidered Lawn Suit", "price_rs", "4850",
"stock", "14"))
print("HGETALL product:2:", c("HGETALL", "product:2"))
print("ZADD featured:", c("ZADD", "featured:products", "10", "product:1",
"8", "product:2", "6", "product:3"))
print("ZRANGE featured (top first):",
c("ZREVRANGE", "featured:products", "0", "1", "WITHSCORES"))
# 6. A cart as a hash with a 30 minute TTL, like a guest session.
print("HSET cart:", c("HSET", "cart:guest-42", "product:1", "2",
"product:2", "1"))
print("EXPIRE cart 1800s:", c("EXPIRE", "cart:guest-42", 1800))
print("HGETALL cart:guest-42:", c("HGETALL", "cart:guest-42"))
s.close()
if __name__ == "__main__":
main()
The real output:
PING: PONG
SET page:product:1: OK
GET page:product:1: {"name": "White Cotton Kurta", "price_rs": 2450, "sizes": ["S", "M", "L"]}
TTL page:product:1: 60 seconds left
SET flash banner: OK
GET flash banner now: Eid sale: 20% off lawn
GET flash banner after 3s: None
INCR views: 1
INCR views: 2
INCR views: 3
GET views: 3
The flash-sale banner shows why expiry matters: the key held the banner for 2 seconds, then the next GET returned None. No cleanup job, no delete call. The counter shows the other side: INCR starts a missing key at 1, so three visits read back as 3.
Then the thing that went wrong: the page cache key holds a JSON string, and INCR only works on numbers:
INCR on page:product:1: ERROR: ERR value is not an integer or out of range
Valkey refused instead of guessing, and the key was untouched: a GET after still returned the kurta JSON. The fix is to keep counters on their own keys: the views live under views:product:1 while the page lives under page:product:1. One key, one type, one job. The rest of the run used a hash for the lawn suit, a sorted set for featured products, and a cart hash with a 30 minute expiry:
HSET product:2: 3
HGETALL product:2: ['name', 'Embroidered Lawn Suit', 'price_rs', '4850', 'stock', '14']
ZADD featured: 3
ZRANGE featured (top first): ['product:1', '10', 'product:2', '8']
HSET cart: 2
EXPIRE cart 1800s: 1
HGETALL cart:guest-42: ['product:1', '2', 'product:2', '1']
In a real shop, the API reads the cache first and only queries the database on a miss; the FastAPI Explained: Python APIs at Full Speed and Build Your First REST API With Node.js and Express posts show that side.

Common mistakes and how to fix them
First, running INCR on a key that holds a string. The symptom is the error above, "ERR value is not an integer or out of range". The fix is to keep counters on separate keys, or delete the string key first.
Second, caching without an expiry. The symptom is a price change that never shows up, because the old page sits in the cache forever. The fix is to set an expiry when the key is written, with EX on SET, and delete the key when the product changes.
Third, connecting to the wrong port. The symptom is "Could not connect to Valkey at 127.0.0.1:6390: Connection refused", which I hit while testing: the server runs on 7777 and the default Redis port is 6379. The fix is to use the port the server actually started on.
Fourth, treating the cache as the only copy of the data. The symptom is an empty shop after a restart, because everything lived in memory. The fix is to keep the database as the source of truth and let the cache rebuild from it.
Frequently Asked Questions
Is Valkey the same as Redis? Not the same project, but the same protocol. Valkey is a community fork of Redis, so Redis clients and commands work against it. The Redis Explained: The In-Memory Store That Speeds Things Up post covers the shared concepts.
Do I need Docker to try Valkey? No. This post built the server from source with one make command, and the Docker image is an alternative.
What happens to my data when Valkey restarts? Anything held only in memory is gone, unless persistence is on. For a cache that is fine: the pages rebuild on the next visit.
Can Valkey replace PostgreSQL or SQLite? No, they do different jobs. Valkey is fast temporary storage, while Postgres holds the records that must last. The SQLite Explained: The Database That Lives Inside Your App post covers the small single-file case.
What to remember
- Valkey speaks the Redis protocol, so existing Redis clients work unchanged.
- A cache is a copy: the database stays the source of truth.
- Give every key an expiry, or stale data outlives the change.
- One key holds one type: counters live on their own keys.
- INCR creates a missing key at 1, and an expired key simply disappears.
Where this leaves you
The shop page started with the database answering the same kurta question hundreds of times a day. One local Valkey server later, the page serves from memory with a 60 second expiry, the flash-sale banner deletes itself, the view counter reads 3, and the one error taught the rule that matters most: a key holds one type, so counters and cached pages live apart. Take one page of your own that rarely changes, cache it with an expiry, and watch the database go quiet.
Further reading
- Valkey documentation
- Valkey commands reference
- Valkey on GitHub
- Redis Explained: The In-Memory Store That Speeds Things Up
- PostgreSQL Explained: The Reliable Database You Default To
- FastAPI Explained: Python APIs at Full Speed
- Build Your First REST API With Node.js and Express
- SQLite Explained: The Database That Lives Inside Your App
Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.
Comments
Post a Comment