Where the Data Goes: D1, KV, R2
Three Storage Mistakes AI Makes
Mistake 1: Treating KV Like a Database
KV has the simplest code, so AI reaches for it. Then you get a balance stored in KV, two people update it at once, and one update vanishes. No error. No log.
Two facts to keep in your head:
- A change can take 60 seconds or more to show up in other parts of the world.
- Each key takes one write per second. It can't count fast things.
So no balances, no inventory, no counters, no "has this coupon been used." Here's what it's great for:
async function getRates(env, ctx) {
const cached = await env.CACHE.get("rates", "json");
if (cached) return cached;
const res = await fetch("https://api.example.com/rates");
if (!res.ok) throw new Error("rates API returned " + res.status);
const fresh = await res.json();
// Save it for an hour, without making the visitor wait for the write
ctx.waitUntil(
env.CACHE.put("rates", JSON.stringify(fresh), { expirationTtl: 3600 }),
);
return fresh;
}
Check the cache, get the real thing if it's empty, save it for next time. If KV lost everything tonight, nothing breaks. That's the test: could you delete it all and rebuild it? If not, it doesn't belong there.
A bug from this site: a background job was supposed to save fresh numbers to the database, but it skipped the save if the cache looked recent. Page views kept refreshing that same cache. So the job always skipped, and the database froze. Green checks everywhere, old numbers on screen. A job's clock has to be its own.
Mistake 2: Gluing Strings into SQL
If a visitor's text gets pasted into the query, they can rewrite the query. The safe form has a ? and a .bind():
const { results } = await env.DB
.prepare("SELECT id, total_cents FROM orders WHERE email = ?")
.bind(email)
.all();
You don't need to know SQL to catch this. Look for ? and .bind. If you see a variable or a ${ inside the SQL instead, reject it.
Mistake 3: Reading Every Row
D1 counts the rows it scans, not the rows it returns. Search a million-row table on a column with no index and you read a million rows to find one. On the free plan, five of those use up the whole day's 5 million.
It's slow, too. One D1 database handles one query at a time. If each takes 1 ms you can do up to 1,000 a second. If each takes 100 ms, you can do 10. The fix is one line:
CREATE INDEX idx_orders_email ON orders (email);
When You Wreck It Anyway
D1 has Time Travel: you can put the database back to any minute in the last 30 days on paid, or 7 on free. It's always on. Restoring overwrites the whole database in place, so anything written since is gone from it. Have AI explain the restore command to you before anyone runs it.
Ask: "List every query in this project, the column it filters on, and the index that covers it." Blanks in the last column are your slow pages next year.
Which of these belongs in KV?
Why can a query that returns one row count as a million rows read?