Vibe Coding: build real apps with AI · Episode 29. Every agent run below is real: Claude Code 2.1.322 (model claude-opus-5-5) in print mode (claude -p --permission-mode acceptEdits), on 12 November 2026, in /home/asha/projects/trip-gallery. The agent could write files but needed approval to run commands, and nobody approved, so it never ran its own scripts or its server. We ran every command and every measurement ourselves.
What was written by hand: the first version of the page (trip-gallery, commit b10c879) was written by hand for this video, the obvious way, to show the classic mistakes. It is not the AI's code. The 24 "phone photos" are test images generated for this video at phone-camera size (4000 × 3000 pixels, about 3.8 MB each). Asha, Ravi and Neha are fictional.
Tools: Node.js v22, Express 5.3.0, better-sqlite3 13.1.1, ImageMagick (convert), Chromium driven by Playwright with network throttling (1.6 Mbps down, 150 ms delay), Python 3 sqlite3 in the SyntaxPilot compiler.
Sources (read on 12 November 2026): - web.dev, The performance effects of too much lazy loading: lazy loading's "overuse can negatively affect performance"; the tested fix "avoids lazy loading images that are above the fold". - Vercel docs, Hobby plan (page updated 2026-09-14): free; Fast Data Transfer first 100 GB, Function Invocations first 1,000,000, Image Transformations first 5,000 a month; "if you exceed your usage limits on the Hobby plan, you will have to wait until 30 days have passed"; personal, non-commercial use only. - Open-Meteo, Terms: the free API allows "Less than 10'000 API calls per day, 5'000 per hour and 600 per minute", non-commercial use only. - Anthropic, Claude API pricing: Claude Haiku 5.5 $0.10 input / $0.50 output per million tokens (prompts up to 100,000 tokens); Claude Sonnet 5.5 $2 / $10; Claude Opus 5.5 $4 / $20.
Prices and free tiers change often: always check the provider's own page and its date.
The problem: "it never loads"
Class 10B went on a trip to Lonavala. Asha made a photo page and shared the link in the parents' WhatsApp group. The replies: it never loads.
| Real life | Your web page |
|---|---|
| Posting a whole photo album to show one small picture | Huge images: a 4000 px photo shown in a ~380 px box. Send the size they'll see. |
| A teacher phoning 24 parents one by one, waiting for each call to end | One request per photo, 24 round trips in a row. Ask once, for everything. |
| A chai stall keeping a flask ready instead of boiling a fresh pot per cup | Caching: keep a ready copy and reuse it. Don't redo the same work. |
The obvious page (written by hand)
// public/index.html (script part) — written by hand for this video, NOT the AI's code
async function show(photos) {
const grid = document.getElementById("grid");
grid.innerHTML = "";
for (const p of photos) {
const res = await fetch("/api/photos/" + p.id + "/likes"); // one request per photo...
const { likes } = await res.json(); // ...and wait for each one
const card = document.createElement("div");
card.className = "card";
const img = document.createElement("img");
img.src = "photos/" + p.file; // 4000 x 3000, ~3.8 MB
const cap = document.createElement("p");
cap.textContent = p.title + " · ❤ " + likes;
card.append(img, cap);
grid.append(card);
}
}
fetch("/api/photos").then(r => r.json()).then(show);
document.getElementById("search").addEventListener("input", async (e) => { // on EVERY key press
const res = await fetch("/api/search?q=" + encodeURIComponent(e.target.value));
show(await res.json());
});
On Asha's laptop, on home WiFi, the whole gallery loads in about three seconds. On a parent's phone it's a different story.
Measure first (real)
Rule one of performance: measure, don't guess.
$ du -ch public/photos/*.jpg | tail -1
91M total # 24 photos, 4000 x 3000
# Chromium, phone screen, throttled: 1.6 Mbps, 150 ms delay
$ node measure.js
first photo on screen: 119 seconds
after 2 minutes: 2 of 24 photos, 8 MB
(The measurement script prints JSON; it is summarised above. The raw line was {"label":"naive","firstPhotoSeconds":120.27,"lcpMs":118884,"after30s_MB":8,"imagesDone30s":2,"apiCalls30s":10}; lcpMs is when the browser finished painting the biggest picture: 118.9 s.)
Twenty seconds after opening, the page showed only thin strips of the first photos and white boxes.
Why it's slow
- Page weight: the total size of everything a page downloads. Here: 91 MB.
- Bandwidth: how much data per second the connection carries. 1.6 Mbps = 1.6 million bits per second; 8 bits = 1 byte.
- 91 MB = 728 megabits; 728 ÷ 1.6 ≈ 455 seconds (about 7.6 minutes) just to download.
- Latency: the waiting time for each round trip (150 ms here). 24 requests one after another = 24 waits.
- Each photo is 4000 px wide but shown in a box about 380 px wide on a phone: almost every byte is thrown away.
Prompt 1 (real): "make it load fast on a phone"
claude -p "Parents in our class WhatsApp group say the trip photo page takes forever on their phones. Make it load fast on a phone. The photos in public/photos are straight from our phones." --permission-mode acceptEdits
What it did (from the real transcript):
Write make-small-photos.sh 1200 px copies in photos/small/
Write public/index.html small photos, lazy loading (not the
first 2), reserved space, debounce
Write server.js likes inside /api/photos, an index,
photos cached by phones for 7 days
Reply: "the page downloaded 91 MB ... I couldn't run anything to
test it. Running the resize script, ImageMagick, node and
npm install all needed approval that wasn't given."
Untested is not done, so we ran its script and measured again:
$ sh make-small-photos.sh && du -sh public/photos/small
6.4M public/photos/small # 24 copies, ~270 KB each
$ node measure.js # same phone, same slow network
first photo on screen: 8.9 seconds (was 119)
API calls on page load: 1 (was 25)
$ node typing.js # type "waterfall"
API calls while typing: 1 (was 19)
(Raw: {"label":"ai1","firstPhotoSeconds":8.873,"lcpMs":8644,"after30s_MB":1.7,"imagesDone30s":6,"apiCalls30s":1} and {"pageLoadCalls":1,"typingCalls":1,"urls":["/api/search?q=waterfall"]}.) First photo: 119 s → 8.9 s, about 13 times faster.
1. Image sizes
The AI's resize script (the first version; the later version below adds "only redo changed photos"):
#!/bin/sh
set -e
cd "$(dirname "$0")/public/photos"
mkdir -p small
for f in *.jpg *.jpeg *.JPG *.JPEG; do
[ -f "$f" ] || continue
convert "$f" -auto-orient -resize '1200x1200>' -strip -interlace Plane -quality 78 "small/$f"
echo "small/$f"
done
- Resize: 4000 px → 1200 px wide (fewer pixels). ImageMagick is a free command-line image tool.
- Compress: JPEG at quality 78: 3.8 MB → about 270 KB, with a barely visible difference.
-strip: removes hidden data stored in phone photos, such as the GPS location where the photo was taken. For photos of children, that matters.- Send each picture at the size it will be seen. Keep the big originals on the server for downloading.
2. Lazy loading (but not for the first photos)
img.width = 800;
img.height = 600; // reserve the space: the page doesn't jump
img.loading = i < 2 ? "eager" : "lazy"; // first screen at once, the rest on scroll
img.src = "photos/small/" + p.file;
img.onerror = () => { img.onerror = null; img.src = "photos/" + p.file; }; // fallback to the original
Lazy loading = the browser downloads an image only when you scroll near it. The AI did not lazy-load the first two photos: web.dev found that overusing lazy loading slows down the first picture people see. Load what's on screen at once, the rest later.
3. Too many API calls
An API call is a request from your page to a server's API (the menu of things the server can do).
One request per photo → one request for everything
-- server.js (the AI's): every photo WITH its like count, in one query
SELECT p.*,
(SELECT COUNT(*) FROM reactions r
WHERE r.photo_id = p.id AND r.kind = 'like') AS likes
FROM photos p ORDER BY p.id;
This mistake has a name: the N + 1 problem (one request for the list, then N more, one per item). When you see a fetch inside a loop, ask: can the server send it all at once?
One request per key press → debounce
// the AI's search box: wait for a pause in typing
let timer;
search.addEventListener("input", (e) => {
clearTimeout(timer); // a new key cancels the wait
timer = setTimeout(() =>
load("/api/search?q=" + encodeURIComponent(e.target.value)), 200);
});
// load() also ignores answers to older searches
Debouncing: wait a short time after the last key press, and only then send the request (like a shopkeeper who waits until you finish your list). Typing "waterfall" went from 19 calls to 1.
Why fewer calls matter
Every call is a round trip, server work and often money. Free APIs have limits: Open-Meteo's free weather API allows less than 10,000 calls a day, 5,000 an hour and 600 a minute, for non-commercial use. An app making 19 calls per search uses that up fast.
4. Caching, and the real AI mistakes
Caching = keeping a copy of something you already fetched or worked out, and reusing it instead of doing the work again.
// server.js (the AI's, prompt 1)
// Photos never change once uploaded, so phones can keep them for a week.
app.use("/photos", express.static("public/photos", { maxAge: "7d" }));
// what the phone receives with every photo:
Cache-Control: public, max-age=604800
max-age=604800 = 604,800 seconds = 7 days: "keep this and don't even ask me again for a week". A second visit downloaded nothing. But the comment is an assumption: photos never change.
AI mistake 1: the old photo that wouldn't go away (real)
Ravi asked Asha to swap the photo called "Ravi slips". She replaced it and re-made the small copies. Then a parent's phone that had opened the page earlier opened the link again:
# Asha swaps photo 16 and remakes the small copies
$ cp new16.jpg public/photos/IMG_16.jpg
$ sh make-small-photos.sh
# a parent's phone that had opened the page, opens the link again
small/IMG_16.jpg status 200 fromDiskCache: true # the OLD photo
The server had the new photo; the phone showed the old one, and would for up to a week. Closing the tab doesn't help, and you can't clear thirty parents' caches. A copy that is out of date but still used is called stale.
Prompt 2 (real)
claude -p "I replaced public/photos/IMG_16.jpg because Ravi asked me to swap his photo, and ran make-small-photos.sh again. The server sends the new photo now (I checked with curl), but on a phone that had opened the page before, the OLD photo still shows, even after closing the tab and opening the link again. Parents have already opened it. Fix this, keep everything else the same, no new npm packages." --permission-mode acceptEdits
Edit server.js each photo gets v = the time its file was saved
Edit index.html photos/small/IMG_16.jpg?v=1794498045296
Reply: "Ravi's photo changed after the others, so only its address
is new ... The other 23 photos keep their old addresses, so
phones still load them from what they saved."
The fix is cache busting: put a version in the address (?v=...). A new version = a new address = the browser must download it.
AI mistake 2: the promise (real)
We counted downloads on a test phone:
# same test: a phone visits, Asha swaps photo 16, the phone visits again
visit 1: 24 downloaded, 0 from cache, 6.58 MB
visit 1 again: 0 downloaded, 24 from cache, 0 MB
...swap photo 16, run make-small-photos.sh...
visit 2: 24 downloaded, 0 from cache, 6.32 MB
Ravi's new photo did appear, but all 24 photos downloaded again. Why? The version was the file's save time, and the resize script re-made all 24 copies on every run, so all 24 save times (and addresses) changed. The AI had written that script one prompt earlier and didn't connect the two. We caught it only by measuring.
Prompt 3 (real)
claude -p "Ravi's new photo shows up now, thanks. But I tested it: after I swapped that one photo and ran make-small-photos.sh, a phone that had seen the page before downloaded ALL 24 small photos again (24 downloads, 6.3 MB), not just Ravi's. You said the other 23 keep their old addresses. On mobile data that matters. Fix it so only changed photos are downloaded again. Keep everything else the same, no new npm packages." --permission-mode acceptEdits
Reply: "I was wrong before when I said the other 23 would keep their
old addresses ... make-small-photos.sh re-made all 24 small
copies on every run, so all 24 got a new save time."
Edit server.js v = a fingerprint of the photo's contents
Edit make-small-photos.sh only redo photos newer than their copy
# our retest
visit 2: 1 downloaded, 23 from cache, 0.02 MB
The final server code:
// v is a fingerprint of the photo's contents (original + small copy), so it changes only when the
// picture itself changes.
const hashCache = new Map();
function fileHash(path) {
let st;
try { st = fs.statSync(path); } catch { return "0"; }
const key = st.mtimeMs + ":" + st.size;
const hit = hashCache.get(path);
if (hit && hit.key === key) return hit.hash;
const hash = crypto.createHash("sha1").update(fs.readFileSync(path)).digest("hex").slice(0, 10);
hashCache.set(path, { key, hash });
return hash;
}
function withVersion(rows) {
return rows.map((p) => ({ ...p, v: fileHash("public/photos/" + p.file) + fileHash("public/photos/small/" + p.file) }));
}
and the line added to the script: if [ "$1" != "--all" ] && [ -f "small/$f" ] && [ ! "$f" -nt "small/$f" ]; then continue; fi.
A fingerprint (hash) is a short code worked out from a file's bytes: same picture, same fingerprint, whatever the save time.
5. Database indexes (run in the compiler)
A database index is like the index at the back of a textbook: a sorted list that points from a value (photo 16) straight to its rows, instead of reading every row.
import sqlite3, random, time
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE reactions (photo_id INTEGER, kind TEXT)")
random.seed(1)
rows = [(random.randint(1, 24), random.choice(["view"] * 4 + ["like"])) for _ in range(300000)]
db.executemany("INSERT INTO reactions VALUES (?, ?)", rows)
sql = "SELECT COUNT(*) FROM reactions WHERE photo_id = ? AND kind = 'like'"
def count_all():
start = time.perf_counter()
for photo in range(1, 25):
db.execute(sql, (photo,)).fetchone()
return (time.perf_counter() - start) * 1000
print("plan:", db.execute("EXPLAIN QUERY PLAN " + sql, (16,)).fetchall()[0][3])
print("24 counts, no index: %.1f ms" % count_all())
db.execute("CREATE INDEX reactions_photo_kind ON reactions (photo_id, kind)")
print("plan:", db.execute("EXPLAIN QUERY PLAN " + sql, (16,)).fetchall()[0][3])
print("24 counts, with index: %.1f ms" % count_all())
Output (our run; your times will differ a little):
plan: SCAN reactions
24 counts, no index: 295.4 ms
plan: SEARCH reactions USING COVERING INDEX reactions_photo_kind (photo_id=? AND kind=?)
24 counts, with index: 1.5 ms
EXPLAIN QUERY PLANasks the database how it will answer.- SCAN: read every one of the 300,000 rows. SEARCH ... USING INDEX: jump straight to the matching rows.
- The cost, in one line: an index takes extra space and makes every insert a bit slower (the index is updated too). Index the columns you search by, not everything.
6. Free-tier limits
A free tier is a free amount of a paid service each month. Vercel's Hobby plan (docs, 12 Nov 2026) includes the first 100 GB of Fast Data Transfer a month.
| Page | Data per visit | Visits before 100 GB |
|---|---|---|
| The obvious page | 91 MB | about 1,100 |
| The AI's page, even if a parent scrolls through all 24 photos | 6.6 MB | about 15,000 |
If you go over on Hobby, the docs say you wait until 30 days have passed. Hobby is for personal, non-commercial projects. Read the limits page of every service you use, with its date.
7. Your AI bill
AI APIs charge per token (a small piece of text, episode 6), per million tokens, separately for input and output. Claude API page, 12 Nov 2026: Haiku 5.5 $0.10 in / $0.50 out; Sonnet 5.5 $2 in / $10 out.
Worked example (our assumptions): the page asks Sonnet 5.5 for a caption for every photo on every visit, about 2,000 tokens in and 100 out per call:
- One call: 2,000 × $2 / 1,000,000 + 100 × $10 / 1,000,000 = $0.004 + $0.001 = $0.005
- 24 photos × 900 visits = 21,600 calls → about $108
- Cached (caption each photo once, store it, reuse it): 24 calls → about $0.12, 900 times cheaper.
The coding agent uses tokens too. Each run reports its own cost estimate:
$ for f in run1 run2 run3; do printf "%s " $f
> grep -o '"total_cost_usd":[0-9.]*' $f.jsonl; done
run1 "total_cost_usd":0.4176848 # make it fast
run2 "total_cost_usd":0.38224719999999995 # the old photo
run3 "total_cost_usd":0.36888800000000005 # only changed photos
# 3 prompts: about $1.17
On a subscription plan you don't pay per run but have usage limits; with an API key, you pay for every run. Clear prompts with evidence get it right in fewer runs. Set a spending limit or budget alert wherever your provider offers one.
The performance and cost checklist
- Measure on a slow phone network, before and after every change.
- Images resized for the screen, compressed, width and height set.
- Lazy load below the first screen only.
- No
fetchinside a loop; debounce typing. - Cache, with a plan for change: versioned URLs.
- Index the columns you search by.
- Read free-tier limits, cache AI answers, set budget alerts.
Common mistakes (real)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
| Phone photos at full size | 91 MB; first photo after 119 s | 4000 px in a ~380 px box | Resized, compressed copies |
fetch inside a loop |
25 calls, one after another | N + 1 requests | One query, one request |
| Search on every key | 19 calls for one word | No pause | Debounce |
| 7-day cache, same URL (the AI's) | fromDiskCache: true (old photo) |
"Photos never change" | ?v= version in the URL |
v = save time (the AI's) |
24 downloaded, not 1 | The script rewrote every file | Content fingerprint, redo only changed files |
| No index | SCAN reactions, 295 ms in the video's run |
Every row read | CREATE INDEX → SEARCH, 1.5 ms |
Mini project
Take one of your own pages:
- Open DevTools → Network, tick "Disable cache", reload: note the total transferred size (page weight).
- Choose a throttled network preset and reload: how long until the first image appears?
- Resize and compress your images; add
loading="lazy"to images below the first screen; setwidthandheight. - Find any
fetchinside a loop and any request sent on every key press; fix them. - Measure again and write down before/after numbers.
Practice questions
- A page has 10 photos of 2 MB each on a 1.6 Mbps connection. Roughly how long just to download them?
Answer
20 MB = 160 megabits; 160 ÷ 1.6 = 100 seconds.
- Why shouldn't you lazy-load the first photo on the page?
Answer
It's already on screen; lazy loading delays the first picture people see. web.dev found overusing lazy loading hurts; load the first screen eagerly and the rest lazily.
- Rewrite this to make one request instead of N:
for (const p of photos) { const r = await fetch("/api/photos/" + p.id + "/likes"); ... }
Answer
Add the like count to the list endpoint on the server (one SQL query with a subquery or JOIN) and render all cards from that single response.
- Your photos have
max-age=604800. You replace one. Why does a parent still see the old one, and what's the fix?
Answer
The browser was told it may reuse its copy for 7 days without asking. Give the changed file a new URL (e.g. ?v=<content fingerprint>), so only that photo downloads again.
- What does
SEARCH ... USING INDEXin a query plan tell you?
Answer
The database jumps to matching rows through an index instead of scanning every row.
Quiz
Photos are cached for 7 days. You replace one. What's the right fix?
A) Tell every parent to clear their browser · B) Change max-age from 7 days to 7 minutes · C) Give the photo a new URL, e.g. IMG_16.jpg?v=<fingerprint> · D) Rename the website
Answer
C. A new URL is a new file to the browser, so only the changed photo downloads again. A is impossible in practice; B keeps a short stale window and throws away most of the caching; D is overkill.
Interview questions
- How do you find out why a page is slow? Measure: page weight and requests in DevTools, a throttled network, time to the main content; then fix the biggest cause first.
- What is the N + 1 problem? One request (or query) for a list, then one more per item; fix by fetching everything in one request or one joined query.
- What is debouncing? Delaying an action until input pauses for a set time, so typing a word sends one request, not one per key.
- How do you cache static files for a long time and still update them? Long
max-ageplus versioned URLs (content hash in the URL or file name); a change produces a new URL. - When should you add a database index, and what does it cost? On columns you filter or join by often; it uses extra space and slows writes slightly.
- How do you keep an AI feature's bill under control? Cache results, use the cheapest model that works, limit calls per user, and set budget alerts.
Glossary
| Term | Meaning (with an example from this episode) |
|---|---|
| Performance | How fast an app feels and responds (first photo in 8.9 s instead of 119 s). |
| Slow page | A page that takes too long to show its content, usually from too many bytes or too many requests. |
| Page weight | The total size of everything a page downloads (91 MB for the obvious page). |
| Byte / bit | A byte is one unit of stored data; a bit is the smallest unit; 8 bits = 1 byte. |
| KB / MB / GB | Kilobyte ≈ a thousand bytes, megabyte ≈ a million, gigabyte ≈ a thousand MB (a small photo copy ≈ 270 KB). |
| Bandwidth | How much data a connection carries per second (1.6 Mbps = 1.6 million bits per second). |
| Mbps | Megabits per second, a bandwidth unit. |
| Latency | The waiting time for each round trip to the server (150 ms in our test). |
| Throttling | Slowing the network on purpose to test like a weak phone connection. |
| Request / round trip | One message from the browser to a server and its reply. |
| Pixel (px) | One dot of an image or screen (4000 px wide photo, ~380 px box). |
| Resize | Making an image smaller in pixels (4000 → 1200 px). |
| Compression | Storing data in fewer bytes; JPEG at quality 78 is much smaller and looks almost the same. |
| JPEG | The common photo file format (.jpg). |
| ImageMagick | A free command-line tool to convert and resize images (convert). |
| GPS data in photos | Location data a phone saves inside a photo; -strip removes it. |
| Lazy loading | Downloading an image only when it scrolls near the screen (loading="lazy"). |
| Above the fold / first screen | What's visible without scrolling. |
| Layout shift | Content jumping as images load; setting width/height reserves space. |
| API | The set of requests a server accepts (/api/photos, /api/search). |
| API call | One request to an API. |
| N + 1 problem | One request for a list, then one per item (24 like-count calls). |
| Debounce | Waiting for a pause before acting (200 ms after the last key). |
| Rate limit (API limit) | A cap on calls per minute/hour/day (Open-Meteo: 600 a minute). |
| Cache / caching | Keeping a copy to reuse instead of fetching or computing again (the chai flask). |
| Browser cache | Copies of files saved by the browser on the device. |
Cache-Control / max-age |
A response header telling the browser how long it may reuse a file (max-age=604800 = 7 days). |
| Stale | A cached copy that's out of date but still used (the old photo 16). |
| Cache busting / versioned URL | Changing a file's address when it changes (?v=...) so browsers fetch the new one. |
| Hash / fingerprint | A short code computed from a file's bytes; same content, same code (SHA-1, first 10 hex characters). |
| File save time (mtime) | When a file was last written; changes even if the content is the same. |
| Database | Organised stored data (SQLite file trip.db). |
| Database index | A sorted lookup structure that points from a value to its rows. |
| SCAN / SEARCH | Query plan words: read every row vs. jump via an index. |
EXPLAIN QUERY PLAN |
SQLite command showing how a query will run. |
| Free tier | A free monthly amount of a paid service (Vercel Hobby: first 100 GB transfer). |
| Data transfer | Bytes your host sends to visitors; free tiers cap it. |
| Hosting bill | What a hosting service charges when you go beyond free limits. |
| Token | A small piece of text that AI models read and write; APIs charge per token. |
| AI bill | What an AI API charges for the tokens your app or agent uses. |
| Budget alert / spending limit | A setting that warns or stops you when spending reaches a set amount. |
| Coding agent | An AI tool that reads and edits your project files (Claude Code). |
Summary
- Measure first: page weight and a throttled phone network showed 91 MB and 119 seconds to the first photo.
- Send images at the size they'll be seen, lazy-load below the first screen, ask the server once instead of per item, and debounce typing: first photo 8.9 s, 1 API call.
- Caching saves time and money, but every cache has an assumption. The AI's "photos never change" kept an old photo on phones, and its first fix re-downloaded all 24 photos despite its promise; counting downloads caught both. Content fingerprints fixed it: 1 download, 23 from cache.
- An index turned a full SCAN (295 ms in the video's run) into an index SEARCH (1.5 ms).
- Read free-tier limits, cache AI answers, and set budget alerts.
Next episode: Refactoring and keeping code clean.