Building in public
Paying for answers we already had
A week of hunting waste in Buddy kept turning up the same mistake: the system paying, over and over, for answers it already had.
Someone texted Buddy and waited up to 21 seconds for a reply.
Meanwhile the database said every query it ran took under 40 milliseconds on average.
Both were true. That gap, between how fast each piece was and how slow the whole thing felt, turned out to be the story of my week.
Quick context if you're new here. I'm building Buddy, a personal AI assistant you can text or use from a desktop app. I build it solo, with a crew of AI coding agents working in parallel. It runs on Cloudflare Workers and Durable Objects, with Postgres behind Hyperdrive. This week I pointed the agents at one question: where are we wasting time and money?
I expected to find slow code. Mostly I didn't. What we kept finding was the system paying, over and over, for an answer it already had. It asked questions whose answer never changed. It rewrote values that were already there. It stayed awake for nobody. It ran a slow rehearsal of a check the platform already does for free.
Here's what we found, what we changed, and the one lesson I'd keep from each.
Ten trips to the counter
Before Buddy answers a message, it runs a quick check we call admission. What does this person's plan allow right now? What's left of their allowance? What is Buddy allowed to do this turn?
That check sent ten database statements, one after another, on one connection. Each one is a full round trip from the Durable Object to the database pool and back.
This is the part that's easy to miss. The database was fast. Each statement averaged under 40 ms on the server. But a round trip isn't just server time. It's the whole journey there and back, and during that person's slow stretch, a single trip cost 1.6 to 3.7 seconds. Pay that ten times in a row and a fast database gives you an admission step of up to 17.6 seconds. That's not a database problem. That's a me problem.
This wasn't a one-off. Across seven days of prod turns, admission ran a median 4.2 seconds slower than a sibling step that does one connect and one statement, and 10 seconds slower at the 90th percentile.
We ruled out the usual suspects first. It wasn't Cloudflare's six-connection limit, which only counts connections while they're opening, and these were already open. It wasn't slow queries either. The database's own stats showed every statement fast.
The fix was to run the same SQL the owning code already had, as one statement. The steps that need a lock, like reconciling a plan or claiming a warning, now run only when that one snapshot says they're needed. Admission pays for the trip once instead of ten times.
One honest loose end: we still don't know why a single trip sometimes takes over three seconds. We don't log per-statement timing yet, so that one stays open. It's on the list. The list is long.
Lesson: latency is round trips times distance. Count your trips, not just your query time. Ten fast queries in a row add up to one slow feature.
The turns that weren't messages
Two days later, the same person asked Buddy to help find a song. They typed only words. Buddy answered with a menu, then kept telling them their attachments had come through blank.
There were no attachments. Five of the six deliveries Buddy got in that exchange weren't messages at all. They were read receipts from their phone. Buddy was replying to being left on read.
Our texting provider forwards a read receipt as an inbound message event, with a type our parser didn't know. So it fell through to "unknown content" and was admitted as a turn. Buddy was told "the person sent unsupported content," and did the reasonable thing with that: it asked about the attachment.
Then we went back to the slow stretch from the last section. 10 of the 13 turns in that window were read receipts too. Each one went through admission and a model call, for a message nobody wrote. I was paying a model to respond to read receipts.
The fix is small. Read and typing signals are recognized before content parsing, answered with a 200, and counted in a log. They never reach Buddy. (Whether Buddy should ever use a read receipt is an open product question. Today it just doesn't pay for one.)
Lesson: the cheapest turn is the one that never starts. Decide at the front door what counts as work. Anything your provider can send that isn't a message should never reach the expensive path.
Questions with only one answer
Once you start looking for "paying for an answer you already have," you see it everywhere. Here are four from this week.
A database asking whether its own tables exist. Every time a conversation object woke up, its code asked SQLite whether its tables existed, about 30 times a wake. SQLite keeps no index on table names, so each of those questions read the entire schema, about 470 rows. On an old thread's cold turn, 14,160 of the 22,417 rows read were that one question, asked over and over.
Now the schema is read once per object's lifetime, and every later "does this exist?" is answered from memory. It's one wrapper underneath every caller, ours and the SDK's, so a probe somebody adds next month is covered too.
A safety ceiling that never said no. Every turn read an operator "launch ceiling," a policy that could switch capabilities off in an emergency. It looked like leftover code to me, but I wanted proof before killing it. My words to the agent: "it seems like an arbitrary limitation that got gutted and has left over code rot but I'd want that proven first."
The proof came back clean. The policy hadn't changed since it was first seeded. All 33 capabilities were permitted, and there were no overrides and no cohorts. Logs and analytics showed zero refusals, and the "withheld by launch policy" count was 0 across 441 prod turns. Every turn still paid to read it: 122 ms at the median and 1,573 ms at worst. Its one visible effect had been harm, a fail-closed bug that once dropped two tools for eight days. About 3,260 lines across 16 files are gone and thank God for that.
A coordinator asked before every fetch. When Buddy reads a public website, it tries to be polite: if a site says "please wait," we wait. To make that work, every read asked a central coordinator first. Over seven days, 220 prod reads each waited on that call, and not one was told to pause. The coordinator's calls took 43 ms at the median and 550 ms at p99.
Now each isolate remembers "no pause known" for 30 seconds. A pause it sees itself is honored right away, and one recorded elsewhere shows up within 30 seconds. The coordinator is still the single record, and scheduled checks, which really do need coordinating across accounts, still go through it.
An alarm rewritten with the same time. A Durable Object can set an alarm to wake itself later. The SDK we use re-sets that alarm after every job it queues or cancels, every time, whether the time changed or not. When we metered one turn table by table, 78 of its 90 alarm writes set the exact time that was already set. We patched it to read the current alarm first and skip the write if nothing changed. A six-step turn went from 872 rows written to 793.
Lesson: if a check has never said no, measure what asking costs. Keep the common answer close to where it's needed. And read before you write, because a write that changes nothing still costs a write.
75 calls to read one list
Our releases started failing in a way that looked like bad luck. Cloudflare allows 1,200 API requests per five minutes, and releases kept losing Workers to rate-limit errors. We deployed 8 at a time, then 4, then 2, and it still happened.
My ask to the agent was "go to the root and make the code use fewer Cloudflare API calls in general." The debug logs plus a counted audit showed where the requests went. Before it deploys, the release audits each Worker's live setup, including which queues it consumes. It got that by reading the consumers of every one of the account's 70 queues, one queue at a time. That's 75 requests for every Worker it audited, and the queue list already had the answer.
Now the audit reads consumers off the queue list and secrets off the active version: 4 requests per Worker instead of 75. Compared live, every consumer and every secret name matched the old way. The shared Cloudflare reader also waits out a nearly spent window and honors Retry-After, instead of finding out by failing.
Lesson: when you hit a rate limit, count your own calls before you add retries. The fix for "too many requests" is usually fewer requests.
Paying for an empty room
Durable Objects bill for duration: the wall-clock time an object is active in memory, not the CPU it uses. That makes "awake but doing nothing" the expensive state.
Right at the start of the week I asked why we were being charged for Durable Object requests. The request charges turned out to be loops we'd already fixed. The real cost was duration. One scheduled watch woke up and stayed active for 72 to 78 seconds of wall time, on about half a second of CPU. Over 24 hours, the account Skills object was active for 5,061 seconds and used 1 second of CPU. One second of work, 84 minutes on the clock.
The cause was a rule in our own code. (It's always a rule in our own code.) Our Postgres helper never closed a healthy client, because "Hyperdrive cleans up at the end of the invocation." That's true for a stateless request. A Durable Object keeps its client open until it hibernates or gets evicted, and an open outbound connection is one of the things that stops it from hibernating. So every event that touched Postgres left the object sitting idle and billed, until Cloudflare evicted it after about 70 seconds. A second cause made it worse: each connected MCP client held an open event stream until the integration was removed.
Now every Postgres client closes as soon as its operation settles, and MCP clients close after 60 idle seconds. For scale, here's the projection that made me care: about $1,700 a month in duration at 1,000 users like the ones we measured. It's a projection, not a bill, but it was headed the wrong way.
The same pattern showed up somewhere I didn't expect: the browser view. When Buddy hands you its browser to watch or take over, an open tab renewed the browser's lease every two minutes, for up to an hour, whether anyone was looking or not. I asked for a timeout for the person, not for Buddy. Now five minutes without your own tap, key or scroll pauses the view, one tap resumes it, and the browser can go back to sleep.
Lesson: on duration billing, idle but connected is the expensive state. Close what you open, and make sure your system can notice when nobody is there.
Eight seconds to wake up a browser
Buddy has his own browser, and you can tap in to watch it or take over. On a brand-new browser home, the video server's first start (Neko, the open-source streamer we use) took 8.4 seconds. Its second start took a quarter of a second.
The difference was a cache nobody had built. The machine template had no plugin registry for the user the video server runs as, so the first start in every new home scanned all 267 media plugins. Every home ran the same scan to reach the same answer. Now the template builds that registry once. It also starts Chrome and the video server once at build time and snapshots the warm machine, memory and page cache included. Two smaller costs went too: a login session we didn't need (up to 622 ms), and a public-IP lookup on every start that an empty setting had never actually turned off (about 210 ms).
Across five fresh homes, the video server's first start went from 2,980 ms to 187 ms at the median, and from 6,544 ms to 341 ms at worst. Chrome got ready in 2.5 seconds instead of 5.6.
Then I asked for the picture to show up at least 70% faster. Two fixed waits were left, both inside the video server: a 2-second wait before it would use the relay connection, and up to 2 seconds waiting for a keyframe, because it ignored the viewer asking for one. We patched both. Page open to first frame on a warm takeover went from 5.11 seconds to 1.55. That's 70%, exactly what I asked for, which I'm going to pretend was planned.
Lesson: if every fresh machine does the same expensive work, do it once at build time and ship the result.
The 19-minute job that set the pace
Our checks run on cloud sandboxes, on 8 vCPU / 8 GB machines. An agent ran the full check suite on the same commit at three sizes:
- 8 vCPU: 1,104 seconds, $0.63
- 4 vCPU: 1,126 seconds, $0.41
- 2 vCPU: 1,112 seconds, $0.29
- 4 vCPU with 4 GB of RAM: failed, because ESLint was killed for running out of memory
We cut the CPUs by three quarters and the run took the same time. Why? One task set the length of every run: a Worker startup profile that took about 1,103 seconds. Everything else finished in its shadow. Memory was the real floor, not CPU. ESLint alone peaks at 6.8 GB.
So check moved to 4 vCPU. The estimate is about $138 saved every two weeks, but that's one trial per size, so treat it as an estimate. My sign-off on going smaller, typo preserved for posterity: "approgved on the small machine where it works."
That leaves the obvious question: what was the 19-minute job for? It profiled each Worker's startup to predict whether Cloudflare would accept the upload. It held a sandbox for about 19 minutes a run, $72.73 over two weeks, at 3% CPU. And Cloudflare already refuses a too-slow startup at upload. My instruction was: "once verified kill this in our scripts especially if it fails during deploy anyway."
The agent verified it first. It uploaded a deliberately slow-starting Worker to a throwaway project, and both of our upload paths refused it and created no version. A normal Worker went through fine. Only then was the profile deleted. The cheap, useful part, the bundle-size ratchet, moved into the lint step that already builds every Worker, at no extra cost.
The trade-off is written into the PR: nothing in our pipeline measures startup time anymore. A regression that adds no bytes gets caught only by Cloudflare at upload, and near the limit that verdict is close to a coin flip. I'll take that over 19 minutes on every run.
With that job gone, the clock moved to the next thing, and it was a dumb one. Every check sandbox copied every package out of the template's store instead of hard-linking it. That setting dated back to the first template, with no recorded reason. Hard links failed on the first try, because the store was baked as root, so the store now belongs to the sandbox user before install. Install went from 101 to 119 seconds down to 14 to 15. The median check run went from 512 seconds to 387.
Lesson: before you buy hardware, find what sets the wall clock. And don't slowly rehearse a check your platform already runs for free. Prove that it runs, then delete your copy.
A summary of a summary of a summary
Long conversations get compacted: older messages are summarized so the context stays small. Ours had a bug in its shape. Each compaction summarized only the messages that had just aged out, then glued that summary onto the previous one. So every compaction added a layer, and nothing was ever rewritten.
One prod thread's summary had twelve layers and 67,000 characters. Resolved work was still listed as pending. Stale "next step" lines lived forever. Buddy's own disproven claims were kept as fact, and at some point the summary had recorded a pet as the person's daughter. Seven of 49 summarizer calls we measured hit the output cap.
Now the earlier summary goes into the request and comes back rewritten as one. Code drops next-step lines, and any fact about a person that isn't backed by that person's own words. A summary that's already stacked gets rewritten once, at the end of a turn.
Lesson: anything that only ever appends grows forever. If it's meant to be a summary, it has to be allowed to forget.
The fix that saved one row
This is my favorite one, because the fix never shipped.
After a turn, Buddy's usage records get delivered by a background drain that wakes the object up. A read-only scan estimated those wakes at about 165 rows written per turn. That's roughly $50 a month at 1,000 users. Prod logs confirmed the wakes were real: 4.2 per turn.
An agent built the fix. Then it did the part that matters, measuring the same real turn before and after. Rows written per turn went from 277 to 276. One row. One.
Why was the estimate off by 164 rows? The "39 rows per wake" figure came from a wake on an evicted object, so it counted all the startup work a cold object does. These wakes land on an object that's already awake, either mid-turn or a second after the reply. On a warm object, delivering in a wake costs about the same as delivering in the foreground. The real saving was about $0.18 a month at 1,000 users, not $50.
So we dropped the code. Shipping it would have added a new timer to the path that handles money, all for four fewer alarm calls per turn. What shipped instead was one dated line in the docs that own that code, plus a short research note. Now the next agent doesn't burn an afternoon chasing the same 165 rows.
Lesson: measure the path you're actually changing. A number taken from a cold start isn't a number for a warm one. And "we measured it, it's not worth it" is a real result. Write it down where the next person will look.
"What's the measured gain?"
The other half of honest measurement is asking for it.
One lane was moving some Durable Object classes out of Buddy's main Worker into a shared one. A 30-day look at the bill had already shown that these classes weren't where the money was. The whole Durable Object bill came to about $21 for the month, nearly all of it rows written by conversation objects. The case for the move was code size: about 846 KiB out of a roughly 9.3 MiB startup bundle, which is what gets uploads refused.
After the first two moves, the update I got said the size budget had been lowered. So I asked:
"My ask was to validate that efficiency increased. So far the pilot and move 2 free 11 KiB and 21 KiB of a 9.3 MiB entry. What's the measured gain, and what exactly will the dev trial measure to prove the moves are worth it?"
The agent's answer, word for word:
"The efficiency gain so far is too small to matter. I should have said that plainly instead of reporting the lowered budget as progress."
Honestly, respect. I'd rather hear that than a dressed-up win. 32 KiB is about 0.3% of the bundle, worth roughly 1 ms of startup. Memory doesn't move the bill either: Cloudflare bills an active Durable Object for 128 MB, whatever it actually uses.
But answering the question properly turned up something real. Every paid model call waits on a dispatch pacer first. A pacer call is one storage read and one write, with 0.7 ms of CPU. Yet in prod those calls took 65 ms at the median, 348 ms at p90 and about a second at p99, for less than a millisecond of actual work. The best guess, not yet verified, is that the pacers share isolates with busy conversation objects and wait behind them. So the dev trial now measures that tail directly, instead of counting kilobytes.
Looking closer at the pacer surfaced a second problem: our own fixed caps on calls in flight, shared by every account. Six accounts sending photo batches at the same moment could fill one provider's lane, and two heavy users could fill another. As I put it to the agent, "scaling limits are one of the most likely points to get a service/design killed." The fix drops the product-wide caps. Each account keeps its fair share, the provider's own rate-limit response is the backstop, and every call that gives up waiting is logged with its reason.
Lesson: report the gain, not the activity. A lowered budget isn't progress. A measured before and after is. And when you push for the real number, you often find the real problem sitting right next to it.
When efficient means spending more
Not every efficiency fix is a cut.
When Buddy replies, it decides which of your memories apply right now. A reranker orders your memories, and the top 8 get judged against the message, all inside a deadline. If the reranker was slow, a fallback judged your 8 newest memories instead. That was fast, simple and, as prod showed, quietly wrong. In the replies since that code shipped, the reranker missed its head start on 11 of 48. At least 5 memories it had ranked in its top 8 were never judged.
The fix was to ask twice. Every reply now sends the same request to two reranker models at once, and whichever answers first sets the order. On the bench, the first of the two answered with a p99 of 324 ms, against 1,058 ms for one model alone. Only 1 of 342 pairs had both over 600 ms. If neither answers in time, nothing gets judged and the reply logs why, rather than judging arbitrary memories.
We tested it end to end on two labeled sets, 106 requests in all. The right memory was used 95 times with the hedge, about the same as when one reranker answers on time (96). The newest-8 fallback managed between 21 and 60. A free keyword search (BM25) got 89. A pricier reranker got 100, but it admitted almost twice as many wrong memories (20 against 11), at 78 times the cost. The hedge adds about $0.000026 per reply. I think I'll survive.
The caveats matter here. The test labels were written by an agent and are still provisional. The bench rarely saw both models slow at once, but that was measured from a laptop. In prod, slow calls might share a cause and slow down together. Each reply now logs which model won, so a week of prod data will tell us whether the hedge holds.
Lesson: a fallback that's fast but wrong isn't a fallback. For tail latency, a second request is often cheaper than a smarter one.
What I'd steal from this week
If you skimmed straight to here, this is the list:
- Count round trips, not just query time.
- Decide at the front door what counts as work.
- If a check has never said no, measure what asking costs, and keep the common answer close.
- Read before you write. A write that changes nothing still costs a write.
- On duration billing, close what you open. Idle but connected is the expensive state.
- Find what sets the wall clock before you buy hardware.
- Don't rehearse a check your platform already runs. Prove it runs, then delete yours.
- Measure the path you're changing, warm and not cold. Projections can be off by a lot.
- Report the gain, not the activity.
- A fast wrong fallback isn't a fallback.
- Hit a rate limit? Count your own calls before you add retries.
- If every fresh machine does the same expensive work, do it once at build time.
- Anything that only appends grows forever. Summaries have to be allowed to forget.
Some things are still open, because building in public includes the unfinished parts. The biggest single writer in a turn is still Buddy's own activity log, about 45% of the rows. The fixes for it change recovery timing or the schema, so they're proposals waiting on my call, not quiet patches. We don't know yet why one database round trip sometimes takes three seconds. The pacer's slow tail has a guess for a cause, not a proof. And the reranker hedge needs a week of prod data before I trust it.
None of this was clever. Almost every fix was some version of "stop asking" or "ask once." The hard part was getting honest numbers, and being willing to drop a fix when the numbers said no. And admitting that most of the waste was stuff we wrote ourselves.
I'm building Buddy at vxbe.space, mostly like this. I'll keep posting what we find.