Skip to content
Plazoleta
· Raúl López

Three reasonable optimizations that made things worse

At LoverCast we built an incremental JSON parser, a video prefetcher and a cache prewarm. All three made sense on paper and all three lost when measured. Why the bottleneck we imagined wasn't the one that was there.

There's a kind of optimization that doesn't fail because it was badly executed. It fails because it's solving the problem of a system that looks like yours but isn't yours. The code is clean, the idea is defensible, and the result is worse than having done nothing.

At LoverCast it happened to us three times, in two places that have nothing to do with each other: the web app that loads the catalogue and the Android TV player. All three are written up in the project's decision documents, with their measurement, and all three ended up reverted or rebuilt.

The parser that chunks a JSON

A supplier's IPTV catalogue can be enormous. On the web, a single "All" category reaches 37,597 items, and the obvious bottleneck was loading it: a fetch, a res.json() and a synchronous JSON.parse of the whole blob that froze the main thread. Measured, the cold block was about 1.6 seconds.

The idea we came up with is one of those that explain themselves: if the array is coming over the network, don't wait to have it whole. Parse it as it comes in, emit batches of items and let the screen fill up gradually. It's what any interface with good taste does with a long list.

We implemented it. And we reverted it. The ADR puts it like this:

It didn't help: the relay delivers the body buffered (all at once), so a synchronous parser walks the whole blob just like JSON.parse and, on top of that, a parser in JS is slower than native JSON.parse. Chunking only helps if the transport arrives chunked over time.

There are two errors stacked in that sentence. The first is a mental-model one: we assumed the bytes arrived spaced out in time, and they didn't arrive like that. Between the web app and the provider there's a relay (a Cloudflare worker) that returns the body already complete. From the client's point of view, the "streaming" was a single chunk. An incremental parser over a single chunk has nothing to emit: it just does the same work as the native parser, in JavaScript, more slowly.

The second error is one of measurement. Parsing in JS against the browser's native parser isn't a comparison you win with an elegant idea. You win it, or lose it, with a stopwatch.

What did work was duller: moving the whole JSON.parse into a Web Worker and returning the array to the main thread in batches of 2,000 items, with repaints grouped to one per frame. Parsing leaves the UI thread, and every batch that crosses is small. The measured block dropped from about 1.6 s to about 0.84 s.

And it's worth reading the honest part of the same document, because it isn't zero. The parsed objects have to cross to the main thread by structured clone, and the browser drains them in a burst. For a normal category, of hundreds or a few thousand items, you don't notice. In the 37,000 case it only happens on first start, because after that there's a cache. The only way to get to zero was described and discarded: keep the array inside the worker and send only the visible window. It's an architecture change that wasn't considered justified.

The prefetcher that fights the player

The second case comes from the Android TV player. Users reported two things: that it took a while to start playing a film, and that the player's grey bar, the one showing what's been downloaded ahead, was short and didn't move much.

For the grey bar the solution seemed textbook. If the player stops at a 48 MB buffer, download ahead to disk yourself, contiguously, and the bar grows. We wrote a loop with Media3's CacheWriter that downloaded ahead of the playback point and paused during buffering so as not to steal bandwidth from the player itself.

Measured, it did what it promised: the grey bar moved ahead to about 106 seconds. But the decision document records what was happening underneath:

The prefetch collides with the player at the buffer boundary (both write the same region, they fight over the cache lock) and re-downloads the same stretch over and over, losing ~50% of the throughput.

There were two things the mental model didn't include. One, the player and the prefetcher aren't two independent processes: they write to the same cache and get in each other's way exactly at the point where it matters most. Two, the IPTV server gave only about 1.76 times the playback bitrate, that is, a real free bandwidth of 0.76 times. With so little headroom, wasting half the throughput isn't a detail. And on top of that, range opens on that server are expensive: ~8 seconds to an arbitrary offset.

The alternative we chose was the one that looked unambitious: raising the player's own RAM buffer, from 48 to 96 MB. That way the player gets further ahead with no concurrency, no lock contention and without downloading anything twice. And there was another wrong mental model there, which the ADR also records: a first attempt to raise it further caused an OutOfMemoryError at two minutes, because the limit wasn't the Shield's physical RAM (3 GB) but the Java heap per app (192 MB). The 96 MB stayed as the validated ceiling, and going beyond it required a separate decision about largeHeap.

The prewarm that caused the slow start

There's one more finding in the same buffering document, and it's the most uncomfortable one. The slow start of a film, about 8 seconds, was caused by the prewarm: opening the detail page pre-cached the first megabytes of the film and the Cues at the end of the .mkv so that play would be instant.

The measurement table is blunt:

Prewarm configuration First frame
Header (2 MB) + tail (4 MB) 8,201 / 8,463 ms
Cache nearly full, partial file 8,541 ms
No bytes cached, only resolving the URL 3,168 / 3,193 ms

Pre-caching left a gap in the cache between what was preloaded and the rest. On pressing play, the player read the header from disk, reached the gap and opened a range connection to that offset, exactly the operation that server serves very slowly. A single continuous connection from byte 0 has no gaps and starts in about 3 seconds. The prewarm that did work in advance was the cause of the problem it meant to solve, and the current version only resolves the URL and doesn't write a byte.

What they have in common

All three cases assumed the extra work improved something. In none of them was the idea bad in the abstract: parsing incrementally, downloading ahead and prewarming are things that work in other systems. What failed was a premise about this particular system.

Optimization Implicit premise What was actually there
Incremental parser The bytes arrive spread out over time The relay delivers the whole body at once
Prefetcher Downloading ahead doesn't get in the player's way The two fight over the same region of the cache
Byte prewarm The warmer it is, the faster the play A gap in the cache forces a slow range open

What uncovered them wasn't thinking better but measuring before signing the optimization off, and writing the negative result down. They're three entries in decision documents with the measurement next to them. That's why they can be quoted here with figures and not with "I think I remember it didn't work".

What it costs not to do it

This way of working isn't free. Implementing an idea, measuring it and reverting it is wasted work, and someone then has to write the paragraph explaining why. We accept it because the alternative is worse: the incremental parser, had it stayed, would have been more complex and slower code than the native one, with the look of an improvement.

Nor was everything solved. The prewarm no longer speeds up anything except resolving the URL, and the server still tops out around 27-29 Mbps, so a film with a very high bitrate stutters even with an enormous buffer: the buffer gives headroom, not throughput. Measuring tells you which optimizations are surplus. It doesn't give you the ones you're missing.

What we take away

Before optimizing a bottleneck, check that it is one. "JSON.parse is slow" was true; "so we have to chunk it as it arrives" depended on a fact about the transport that nobody had looked at.

An optimization that adds an actor also adds contention. The prefetcher wasn't slow: it was competing with the player for the same resource. Before you put two things writing to the same place, the question is which of the two wins when they coincide.

Doing work in advance can be the cause of the slowness. A prewarm is a head start, and a head start that leaves gaps forces you to pay for random access exactly when the user is waiting.

The negative result gets written down. The day someone proposes streaming-parsing the JSON again, the ADR answers with a sentence and a measurement. Without it, the experiment would have to be repeated.

If you have an optimization that "obviously" has to help and you haven't measured it against the real system, write to me: it's usually an afternoon, and sometimes the afternoon saves weeks.

Got a similar problem?

Tell us about it. You'll be talking straight to whoever writes the code.