The symptom and three explanations#
A fictional shop, lumen-store, sells a desk lamp with SKU LMP-204. On 2026-11-18 at 09:58 UTC a merchandiser cut its price from €21.49 to €19.99 in the admin tool. At 10:05 a customer opened a ticket with a screenshot: the product page did not show €19.99. Three explanations fit the ticket:
- The write path stored the wrong value. The admin tool converted "19.99" to integer cents and wrote something else.
- The stored value is right, and the read path changed it. Somewhere between the row and the page, a conversion, rounding, currency or serialization step altered the number.
- The page came from a cache entry written before 09:58, so the customer saw an old value.
Every explanation predicts the ticket and the screenshot. The obvious check, opening the page yourself, predicts nothing useful either: your request can fill a fresh cache entry, reach another edge location or pass through a different price list, and the admin screen has a read path of its own. Choose the observation where explanations disagree
Where the predictions differ#
| Observation | Stored wrong | Changed on read | Stale copy |
|---|---|---|---|
| The page the customer saw | wrong | wrong | wrong |
| The stored row, read with SQL | wrong | right | right |
| The API response with the cache bypassed | wrong | wrong | right |
The cache entry's write time against the row's updated_at | after | after | before |
| The wrong value equals an earlier stored price | rarely | rarely | yes |
The second row separates the write path from the other two, and the third separates the read path from the stale copy. Read them in that order, from the inside out, and stop at the first layer whose value differs from the layer inside it. That layer, or the code between it and the previous one, changed the number.
Each reading has to bypass the layer above it. Read the row with psql or another client that prints the column's text, not through the application's ORM, which is part of the read path. Read the API's raw response body with curl, not the value the browser renders. A double precision or real column stores an approximation of the number written to it, so check the column's type as well as its value. PostgreSQL numeric types
The lab: one price, three worlds#
The lab runs PostgreSQL 17 in Docker and a small Python read path with a 30-minute cache. In the write world the admin form truncates float("19.99") * 100. In the read world the API "keeps two decimals" with math.floor. In the stale world both are correct and a visitor filled the cache at 09:50. Most decimal fractions have no exact binary representation, which is what the two conversions trip over. Floating-point arithmetic
import json, math, os, subprocess, sys
def sql(query):
cmd = ["docker", "exec", os.environ["PRICE_LAB_CONTAINER"], "psql", "-U", "postgres", "-AtX", "-v", "ON_ERROR_STOP=1", "-c", query]
return subprocess.run(cmd, capture_output=True, text=True, check=True).stdout.strip()
def save_price(text, at, world):
# The admin form turns the text the merchandiser typed into integer cents.
if world == "write":
cents = int(float(text) * 100) # truncates 1998.9999999999998
else:
cents = round(float(text) * 100)
sql(f"UPDATE product SET price_cents = {cents}, updated_at = '{at}' WHERE sku = 'LMP-204'")
def api(world):
cents = int(sql("SELECT price_cents FROM product WHERE sku = 'LMP-204'"))
amount = cents / 100
if world == "read":
amount = math.floor(amount * 100) / 100 # "keep two decimals"
return json.dumps({"sku": "LMP-204", "price": amount})
cache = {} # sku -> (json, written_at)
def page(now, world):
entry = cache.get("LMP-204")
if entry is None or now - entry[1] >= 30 * 60: # 30-minute TTL
entry = (api(world), now)
cache["LMP-204"] = entry
return "EUR {:.2f}".format(json.loads(entry[0])["price"])
def clock(hhmm): # seconds since midnight
h, m = map(int, hhmm.split(":"))
return h * 3600 + m * 60
if len(sys.argv) < 2 or sys.argv[1] not in ("write", "read", "stale"):
sys.exit("usage: python3 price.py write|read|stale [price]")
world = sys.argv[1]
price = sys.argv[2] if len(sys.argv) > 2 else "19.99"
sql("DROP TABLE IF EXISTS product; CREATE TABLE product (sku text PRIMARY KEY, price_cents bigint, updated_at timestamptz)")
sql("INSERT INTO product VALUES ('LMP-204', 2149, '2026-11-18 08:00Z')")
page(clock("09:50" if world == "stale" else "09:20"), world) # the last visit before the change
save_price(price, "2026-11-18 09:58Z", world)
shown = page(clock("10:05"), world) # the customer at 10:05
print(f"world={world}")
print(" stored row ", sql("SELECT price_cents, to_char(updated_at AT TIME ZONE 'UTC', 'HH24:MI') FROM product"))
print(" API, no cache ", api(world))
value, written = cache["LMP-204"]
print(" cache entry ", value, "written", f"{written // 3600:02d}:{written % 3600 // 60:02d}")
print(" page ", shown)
Save the Python as price.py and the shell script below as run-price.sh in the same directory. Run sh run-price.sh to compare the three worlds.
#!/bin/sh
set -eu
PRICE_LAB_CONTAINER=$(docker run -d --network none -e POSTGRES_PASSWORD=lab postgres:17)
export PRICE_LAB_CONTAINER
trap 'docker rm -fv "$PRICE_LAB_CONTAINER" >/dev/null' EXIT
trap 'exit 1' HUP INT TERM
tries=0
until docker exec "$PRICE_LAB_CONTAINER" pg_isready -q -t 1 -h 127.0.0.1; do
tries=$((tries + 1))
if [ "$tries" -ge 30 ] || [ "$(docker inspect -f '{{.State.Running}}' "$PRICE_LAB_CONTAINER")" != true ]; then
echo "PostgreSQL did not start in the lab container" >&2
exit 1
fi
sleep 1
done
for world in write read stale; do python3 price.py "$world" "${1:-19.99}"; done
Before you run it, write down the first layer at which each world goes wrong. The prediction is that the stored row is wrong only in write, the API without the cache is wrong in write and read, and the page is wrong in all three. With PostgreSQL 17.12 and Python 3.11 it printed:
world=write
stored row 1998|09:58
API, no cache {"sku": "LMP-204", "price": 19.98}
cache entry {"sku": "LMP-204", "price": 19.98} written 10:05
page EUR 19.98
world=read
stored row 1999|09:58
API, no cache {"sku": "LMP-204", "price": 19.98}
cache entry {"sku": "LMP-204", "price": 19.98} written 10:05
page EUR 19.98
world=stale
stored row 1999|09:58
API, no cache {"sku": "LMP-204", "price": 19.99}
cache entry {"sku": "LMP-204", "price": 21.49} written 09:50
page EUR 21.49
From the API outward, the write and read worlds are identical: the same JSON, the same cache entry written after the update, the same €19.98. Only the stored row tells them apart. The stale world is the only one where the fresh API response is right and the cache entry predates the row's updated_at. A stored row reading 1999 in the write world, or a cache entry newer than 09:58 in the stale world, would have falsified the prediction.
Run sh run-price.sh 19.50 and compare the write and read cases. The float conversions are exact for 19.50, so both worlds show the right price, and a defect that depends on the value can hide behind the one value you test. The fictional €19.99 belongs to a class of conversion bugs that have guides of their own: cents and decimal amounts, and 64-bit IDs a JavaScript client rounds.
Read it on a real system#
All of the commands below only read. Read the row and its column type first, on the database the read path uses:
SELECT sku, price_cents, updated_at FROM product WHERE sku = 'LMP-204';
SELECT column_name, data_type, numeric_precision, numeric_scale
FROM information_schema.columns
WHERE table_name = 'product' AND column_name = 'price_cents';
Then the API's response from inside the network, addressed to the service so that no CDN or shared cache sits in between, and the public page's headers. A response that carries an Age header was not generated by the origin for this request. Its absence does not prove that the origin was contacted. RFC 9111, Age
curl -sS http://catalog.internal:8080/products/LMP-204
curl -sSI https://shop.example.test/p/LMP-204 | grep -i -E '^(age|cache-control|date):'
For an application cache in Redis, read the entry and its remaining time to live. If the code sets the key with a fixed expiry when it writes it, the entry was written at about the current time minus the configured TTL plus the remaining TTL. TTL returns -1 for a key with no expiry and -2 for a missing key. Redis TTL
redis-cli GET product:LMP-204
redis-cli TTL product:LMP-204
Replay the customer's request where you can: the same region, currency, locale and account. A price list per country or a running price experiment is a read-path layer that your own request may never touch.
Limits#
The row holds only its current value. If someone corrected it before you looked, the updated_at you read is the correction's and the write-path explanation has lost its evidence. An audit table or the admin tool's request log is what keeps it.
A cache entry that expired before you looked cannot confirm or rule out the stale copy. Capture the cache entry and the page headers first, while they still exist, and the stored row after.
A read path can read from a replica, and then the row on the primary is the wrong first layer. Read the row on the replica the API uses, with its lag. Stale reads from a read replica
The layers are not always a single line. Several caches, a CDN with per-region copies and a client-side store can each hold a different value, so read each one on the path the customer's request took.
Questions#
Why does the admin screen show the right price when the customer sees another?
The admin screen reads the value through its own path, often without the customer-facing cache, and may echo the text the merchandiser typed instead of reading the stored row. It is one more layer, and it says nothing about the others.
How do I check a value without the cache?
Call the service behind the cache directly from inside the network, or read the stored row with SQL. A Cache-Control: no-cache request header says the client prefers that a cache not answer from a stored copy without validating it at the origin. An application cache that your code reads before calling the database never sees that header. RFC 9111, no-cache
Should prices be stored as floating-point numbers?
PostgreSQL recommends numeric for monetary amounts because the floating-point types are inexact. Integer cents work too, as long as every conversion to and from a decimal amount rounds instead of truncating. PostgreSQL numeric types