Engineering
7 Performance Traps in AI-Coded Apps
One 5 GB upload exposed what happens when agents ship feature by feature.
Debugging a slow 5 GB podcast upload across Smol’s Workers, D1, R2, web, macOS, and iOS uncovered 55.5% idle polling traffic, serial 15–22 call D1 waterfalls, a 734 kB root chunk, and stale pre-deploy tabs—resolved across PRs #495–#501.
A teammate dropped a 5 GB podcast recording into Smol—our team workspace, chat, and file-sharing app across web, macOS, and iOS—and sent one line in chat: uploading the same file to a plain drive tool felt "like 100× faster."
That single complaint triggered an overnight performance sweep across five pull requests (PRs #495, #496, #497, #499, and #501) spanning Cloudflare Workers, D1 (Cloudflare's SQLite database), R2 (object storage), React, macOS Rust, and iOS Swift. The upload path really was broken—every chunk was riding through our Worker one small piece at a time—but pulling 24 hours of production telemetry exposed a bigger surprise: 55.5% of all API traffic in Smol came from idle background polling timers that nobody had noticed while shipping features.
Smol is built mostly by coding agents—feature after feature written across Claude Opus 5.5 and GPT Sol 6.2 sessions, then audited here with Gemini. Every pull request passed its tests and looked tidy in isolation. The slowness only showed up between slices. Seven distinct performance traps had quietly compounded, and the same seven patterns tend to crop up in any fast-moving AI-coded app.
What 88,286 production requests looked like
Before changing code, we queried Smol's production D1 telemetry table (api_route_stats, which aggregates per-route request counts, D1 call histograms, and wall time for every /api request) for the 24 hours preceding our first upload fix (2026-11-30 19:00 UTC to 2026-12-01 19:00 UTC).
The question was simple: how much of our production load was real user work versus accidental overhead?
Where 88,286 production API requests went in 24 hours before PR #495. Source: Smol api_route_stats (2026-11-30 19:00 UTC – 2026-12-01 19:00 UTC).
Look at the top two bars. GET /file-imports (13,691 requests) and GET /zip-extractions (13,680 requests) accounted for 31.0% of all traffic on the entire backend. Neither feature was even running for most of those hours; two React components (UrlImport and ZipPreview) had mounted a 4-second polling timer unconditionally whenever a folder was open. Add eight more periodic pollers—pending uploads, folder access, assistant tasks, saved reminders, notifications, handoff counts, admin alerts, and file processing—and 49,026 of 88,286 requests (55.5%) were polling loops. During quiet overnight hours (00:00–03:00 UTC), pollers climbed to 78%–81% of every request hitting Cloudflare.
That is the signature of agent-written software: an agent asked to implement one feature optimizes for local correctness, never for the sum of ten mounted components or a 5 GB production file. Here are the seven traps we hit and what cleared each one.
Trap 1: Proxying bulk bytes through your app server
When an agent adds file uploads to a Worker API, the path of least resistance is obvious: authenticate the session on PUT /api/organizations/:org/file-uploads/:id/parts/:part, check folder permissions in D1, and forward the body into R2. It reuses existing auth middleware, needs no bucket CORS rules, and passes every unit test.
In production, it puts your Worker—and your database—in the middle of every byte. Smol split a 5 GB recording into ~500 chunks of 10 MiB. Each chunk hit the Worker, ran up to 10 D1 queries (in production telemetry, including session and upload-row verification), copied the body through Worker memory and CPU, and waited on R2. Over 24 hours, PUT /file-uploads/.../parts/:part logged 7,410 Worker requests.
The diagram below compares that proxied upload path against the split control-plane/data-plane flow we shipped across PRs #495, #496 (R2 CORS rules), #497, and #499:
Before vs. after on the upload data plane across Web, macOS (Rust), and iOS (Swift). Shipped in PRs #495, #496, #497, #499, and #501.
We kept the control plane on the Worker (live membership checks, upload creation, short-lived presigned R2 part URLs, and completion) and pushed the data plane straight to R2. Files over 64 MiB now use 32 MiB parts (~150 parts instead of ~500 for 5 GB). POST /file-uploads bundles the first batch of presigned URLs (initialParts) directly into the creation response so the first chunks start without an extra round trip, and clients stream 4–6 parts concurrently straight to R2—falling back to a streaming pass-through Worker route (FixedLengthStream) only if CORS or a corporate proxy blocks the direct PUT.
Never let bulk media bytes ride through an edge Worker just because auth already lives there. Sign short-lived object-storage URLs on the control plane and let clients talk directly to R2.
Trap 2: Death by a thousand "just poll it" timers
Every time an agent builds an async status widget—a zip extractor, a URL importer, a transcription job, a pet assistant, an admin alert badge—it writes the same tidy useEffect: fetch on mount, then setInterval every 4 to 60 seconds. Each timer looks reasonable in code review. Ten of them mounted inside one workspace create a background storm.
Across Smol's web app and native iOS client, we found more than a dozen independent timers firing whether or not any work existed:
- Zero-work fast pollers:
UrlImport(GET /file-imports) andZipPreview(GET /zip-extractions) polled every 4 seconds with zero active jobs;UploadRecovery(GET /file-uploads) polled every 15 seconds with zero pending uploads;ProcessingPanel(GET .../processing) polled every 4 seconds even after processing finished. - Duplicate timers on the same endpoint:
AssistantPet,AssistantView, andAssistantChatall polled assistant state independently every 15 seconds while idle. - Unconditional background timers: The saved-reminders store (
later.ts) hitGET /api/savedevery 60 seconds just so reminder toasts would fire on the minute, even though checking due times is pure local math on cached items.MailDesktoppolledGET /sync/pullevery 60 seconds even when the user wasn't looking at Mail.DesktopNotificationspolledGET /notificationsevery 15 seconds while the tab was visible—even though it only displays a browser notification when the tab is hidden.
In PRs #497, #499, and #501, we switched active-job views (UrlImport, ZipPreview, ProcessingPanel, UploadRecovery, Assistant*, and iOS FolderPendingUploads) to poll only while work is in flight and stop completely when idle. For later.ts, we split the local 60-second checkDue() toast check (zero network calls) from the /api/saved sync (mount, tab return after 60s, mutations, and a 10-minute fallback). For off-screen watchers (MailDesktop, AuditAlertNotice, DesktopNotifications), we relaxed intervals to 1–5 minutes.
Poll only during an active state transition, stop when idle, and never make a network call just to tick a local clock.
Trap 3: Hidden serial waterfalls behind clean auth helpers
Agents favor tidy, self-contained authorization helpers: ensureOrganizationMember(), ensureDocumentAccess(), authorizedVersion(), syncedFolderIds(). Each helper is safe on its own. Composing two of them in one route quietly builds a serial database waterfall.
In api_route_stats, several hot routes peaked at 10 to 22 D1 calls per request. (Smol stores D1 call counts in half-power-of-two histogram buckets, so a reported bucket edge of 15 or 22 is an upper bound at most ~41% above the true peak—still far too many sequential round trips for one read):
GET /files/:file/versions/:version/media(peak bucket 22 D1 calls): Ran five independent version, preview, thumbnail, subtitle, and transcript queries one after another instead of concurrently.GET /files/:document/versions/:version/processing&GET /files/:document(peak buckets 15 & 10 D1 calls): Loaded job, transcript, summary, version, and sidecar rows serially after auth.GET /sync/pull(12,138 reqs/24h, peak bucket 15 D1 calls): Calledmember()—which queriedorganizationAccess()—and then calledcoveredFolders()→syncedFolderIds(), which queriedorganizationAccess()a second time serially on every single sync pull and push.GET /documents/:doc/versions/:version/assets/:kind(2,268 reqs/24h) &/files/:file/versions/:version/assets/:kind(peak bucket 15 D1 calls): Checked access and then ran a separate serialSELECT ... FROM versions JOIN documentsbefore touching R2—even infile-media.ts, whereaccess()had already fetched the version row's storage keys and MIME type.
Passing already-verified context (access, versionRow) down into helpers removes the duplicate lookups outright. Where two reads are genuinely independent—such as verifying document access and loading version metadata—we overlap them with inOrder(), a small Promise.all wrapper that always surfaces the auth error first so a 403 never leaks a 404.
Trap 4: Pre-flight work tuned to 1 MB test fixtures
Agents test against tiny synthetic fixtures—a 1 KB text file or a 2 MB blob. Algorithms that finish in 2 milliseconds in Vitest stall for tens of seconds on a 5 GB podcast recording.
Two pre-flight and scheduling cliffs showed up immediately on multi-gigabyte media:
- Full-file SHA-256 hashing before byte 1 moves: Both the web uploader and the iOS Swift client hashed the entire file up front to build a resume fingerprint, freezing a 5 GB upload before anything hit the wire.
- Strict FIFO batch queues: Dropping a 5 GB video and three 20 KB PDFs into a channel parked the PDFs behind the video until all 5 GB finished.
For files larger than 16 MiB, both web and iOS now compute a bounded sampled fingerprint (three 256 KiB slices—start, middle, end—plus file size and name) in milliseconds. UploadScheduler prioritizes small parts ahead of queued 32 MiB parts so lightweight files land in seconds while giant recordings stream in parallel.
Trap 5: Perceived-speed gaps and the stale-tab deploy tail
Two details made Smol feel slower than its raw throughput—and one of them showed up directly in the production graphs after we deployed our fixes.
First, upload progress was nearly invisible: chunk-only updates left a 32 MiB part stuck at 0% for half a minute, dropping a second batch of files was rejected while the first batch ran, and uploading files stayed out of the folder list until completion. We wired live byte-level xhr.upload and URLSession progress with MB/s and ETA, queued overlapping drops non-blockingly, and rendered inline optimistic upload rows right at the top of the folder view.
Second—and this was the real surprise of the night—deploying a frontend fix does not stop already-open browser tabs from hammering your backend.
The two-panel chart below shows both our serial D1 hotspots (left) and the exact hourly request curve across all 24 full UTC hours of December 1 (right), including what happened after PR #495 (19:31 UTC) and PR #497 (20:00 UTC) deployed:
Left: peak D1 call buckets before parallelization/deduplication. Right: 24 full UTC hours on 2026-12-01 (api_route_stats). Partial hour 12-02 00:00 UTC is excluded so every bar shares a 60-minute denominator.
The hourly shape tells two stories at once. During the quiet overnight window (00:00–03:00 UTC), pollers drove 78%–81% of traffic until tabs slept at 04:00–06:00 UTC; during the morning workday spike (09:00 UTC, 11,264 requests), real user actions temporarily pushed pollers down to 27%. Then look at 20:00–23:00 UTC, hours after PR #497 deleted the 4-second file-imports and zip-extractions pollers: total poller volume stayed at 2,316–2,997 requests per hour—with those two deleted 4-second routes alone still taking ~867 requests per hour each—and Worker-proxied PUT /parts/:part still logged 4,462 requests across 19:00–23:59 UTC (peaking at 1,334 in the 22:00 UTC hour) from un-reloaded browser tabs and native clients awaiting release.
We explicitly rejected silent auto-reloads—yanking a tab out from under someone mid-draft or mid-upload breaks trust. Instead, PR #501 emits X-Smol-Version (the deployed commit SHA) on every /api/* response, checks /api/health when a user returns to a tab hidden for 10+ minutes, and shows a compact Update ready · Refresh pill in the top bar so people reload on their own schedule.
Trap 6: Eager top-level imports in the root shell
Whenever an agent adds a new modal or settings panel, it writes a normal top-level import in App.tsx—one line shorter than React.lazy(), and completely invisible until cold load time bloats.
Inspecting the Vite build showed Smol's main App chunk at 734 kB (minified JS) because secondary dialogs—WorkspaceSettings (81 kB alone), SearchModal, GoogleDocumentImport, ProcessingCenter, and NewChannelDialog—were statically bundled into initial boot.
One intentional exception mattered: we kept SettingsPage and FileInspector in the main chunk per an existing deploy-resilience comment (so Settings still opens even if a new deploy replaces lazy chunk hashes underneath an older tab). Lazy-loading the other five secondary modals trimmed App-*.js from 734 kB to 609 kB (192 kB gzipped; -125 kB minified) with zero behavior change.
Trap 7: Cross-platform drift
Once PRs #495 and #497 shipped, web users had concurrent direct-to-R2 32 MiB uploads, sampled fingerprints, and calm idle polling. Meanwhile, the native clients were still living on v1:
- macOS desktop (Tauri / Rust
cloud.rs): still sent 10 MiB chunks serially through the Worker, and its utility loop woke the main thread unnecessarily while idle. - iOS native (Swift
FileActions.swift): still hashed multi-GB videos in full before uploading, proxied every part sequentially through the Worker, and ran tightTask.sleeploops on idle views (FolderPendingUploads,PersonalAssistantView,ClipReviewView,FolderWorkView).
Multi-client repos drift like this whenever prompts scope to "fix web uploads." PR #499 ported 4-way concurrent direct-to-R2 uploads, sampled fingerprints, byte-level progress, and idle-aware polling to both Rust and Swift so native clients stop lagging behind—and stop keeping Worker-proxied upload traffic alive.
What is measured vs. what is still rolling out
Every fix below is merged and test-verified, though live production numbers depend on client rollout lag:
| Trap | Primary evidence (measured) | Shipped fix (PRs #495–#501) | Proof state today |
|---|---|---|---|
| 1. Proxied data plane | 7,410 Worker PUT /parts reqs/24h; ~500 × 10 MiB parts for 5 GB |
Direct-to-R2 presigned 32 MiB parts + R2 CORS (PR #496) + streaming Worker fallback | Live on Worker + R2 CORS applied; integration tests green; awaiting full client rollover |
| 2. Unconditional pollers | 49,026 of 88,286 reqs/24h (55.5%); 78%–81% in idle hours | Active-only polling on 10+ web/iOS views; local later.ts clock; 1–5 min background backoff |
Deployed on web; unit/integration tests green; stale tabs still draining |
| 3. Serial D1 waterfalls | Peak buckets of 22 calls (/media), 15 (/sync/pull, /assets, /processing), 10 (/files/:doc) |
Reused member() access in sync.ts; inOrder() + prefetched version rows; Promise.all on media/processing |
Deployed live; 8 API Vitest suites + cloudflare-integration passing |
| 4. Linear pre-flight work | Full-file SHA-256 + FIFO blocked 20 KB PDFs behind 5 GB video | 3×256 KiB sampled fingerprint (>16 MiB); shortest-job-first UploadScheduler |
Deployed on web, merged for iOS; recovery-integration (33/33) & XCTest passing |
| 5. Perceived speed & stale tabs | Post-deploy stale clients fired 2.3k–3.0k pollers/hr (~867/hr each on dead 4s routes) & 4,462 Worker parts (19:00–23:59Z) |
Byte-level MB/s + ETA; non-blocking drop queue; inline upload rows; X-Smol-Version + Update ready · Refresh pill |
Deployed live in PR #501; verified by unit tests & request-timing.test.ts |
| 6. Eager root bundle | Main App chunk at 734 kB minified |
Lazy-loaded 5 secondary modals (WorkspaceSettings 81 kB, SearchModal, etc.) |
Measured in Vite production build: 734 kB → 609 kB (192 kB gzipped; -125 kB) |
| 7. Cross-platform drift | Mac Rust & iOS Swift still on serial Worker uploads & tight idle timers | 4-way concurrent direct-to-R2 + calm polling in Rust (cloud.rs) & Swift (FileActions.swift) |
Merged in PR #499; 137/137 Rust tests, iOS XCTests & macOS CI green; awaiting next desktop/TestFlight release |
The next unresolved check
Merged code and green CI are not the final measurement. Two production checks remain over the next 24–48 hours:
- Stale-client drain: Watching
GET /file-imports,GET /zip-extractions, andPUT /file-uploads/.../parts/:partfall toward zero inapi_route_statsas open tabs clickUpdate ready · Refreshand the next signed macOS and iOS builds roll out. - End-to-end 5 GB upload wall time: Re-timing a real 5 GB podcast upload from Singapore and US West once Cloudflare's R2 Local Uploads (which lands chunks at the nearest edge region instead of crossing the Pacific per part) and fresh client builds are live, and checking whether the next bottleneck shifts to post-upload transcoding or media Range playback.
Coding agents make vertical feature velocity cheap. That shifts the engineer's job toward the cross-cutting invariants no single feature PR can see: keep bulk bytes off your app server, cap background timers, count your database round trips, test with 5 GB files, split your root bundle, and never leave native clients behind on v1.
