Blob: references/performance-and-resources.md
Performance and resources
Give each cost a frequency, a location, and a useful result. Connection setup, packet processing, a remote read, and background fanout have different effects even when all consume CPU or time. The useful optimization depends on which work the product repeats and which constraint it approaches.
Price the operation where it happens
ESP32 radio firmware compared the chip's native cryptography stack, with and without hardware acceleration, against RustCrypto. On the tested ESP32-S3, P-256 key generation took about 116 ms through native hardware, 92 ms through native software, and 72 ms through RustCrypto. Hardware was slower for that primitive. Rachel still considered one native backend worthwhile if the additional connection setup time was small enough to remove algorithm-specific branches. The comparison was a cost of roughly 24 or 44 ms depending on which alternative it replaced, paid mainly when establishing a connection.
Packet encryption had a different tradeoff because it repeats throughout playback. For 240-byte inputs, native hardware AES-GCM took about 170 microseconds with reused contexts, against 550 microseconds for RustCrypto. Fresh native contexts took about 224 microseconds and still improved the repeated operation while avoiding retained native handles. Startup profiling exposed another distinction: substantial time went into P-384 signature verification even though key exchange was configured for P-256. Selecting an algorithm for key exchange did not describe all cryptographic work on the startup path.
Separate primitive timing from application timing, and setup cost from steady-state cost. A modest delay once per connection can purchase simpler ownership. The same delay per packet could be untenable. Measure the code path and usage pattern that the decision actually affects.
A queue spends memory and latency
Composer receives live media through several protocols and schedules it onto a composition timeline. An RTMPS video frame could arrive roughly 450 ms ahead of its presentation time. A short queue that discards its oldest buffer when full can discard the very frame the compositor will need next. Being the oldest queued arrival does not make a future presentation timestamp obsolete.
The application used different queue policies for different paths. Some raw-video queues favored freshness by dropping old work. The RTMPS scene queue retained frames and backpressured at its limits:
pub(crate) const QUEUE: &str =
"queue max-size-buffers=8 max-size-bytes=0 max-size-time=250000000 leaky=downstream";
pub(crate) const RTMPS_SCENE_QUEUE: &str =
"queue max-size-buffers=64 max-size-bytes=201326592 max-size-time=1000000000";Here leaky=downstream drops old buffers rather than blocking the producer. The RTMPS queue omits that policy and bounds retained work by buffer count, bytes, and time. One second of 1080p60 I420 video was budgeted at about 178 MiB, making enough room for the presentation lead a material memory decision. Multiple such inputs multiply that cost.
A larger queue can absorb a burst or presentation lead. It cannot increase sustained service capacity. If arrival remains faster than consumption, the queue eventually reaches its limit. At that point, blocking, dropping, or rejecting work each expresses a different product choice; upstream live sources may be unable to wait.
Ask which queued work still has value when consumed. That determines whether freshness or continuity should dominate.
Remote requests, bytes, and memory are separate costs
Vaskel's thumbnail extractor reads uploaded video from R2 object storage to find a usable keyframe and its decoding metadata. Signature detection and demuxing made many small nearby range requests. Some MP4s also required a visit to metadata near the tail and a return to the beginning. Each remote GET has a cost independent of the bytes returned, so reducing fetched bytes alone could leave an expensive request pattern. Rachel connected this pattern to an existing Git pack reader and proposed reading useful ranges in larger chunks.
A local comparison over 15 video samples retained identical extracted keyframe bytes, decoder configuration, and display metadata:
| Reader | Mean GETs | Mean fetched bytes |
|---|---|---|
| Exact reads | 9.4 | 118 KiB |
| Mediabunny filesystem preset | 3.1 | 274 KiB |
| Mediabunny network preset | 2.7 | 535 KiB |
| Two 32 KiB buffers | 2.2 | 143 KiB |
Mediabunny was the demuxing library. Its presets reduced request count but fetched considerably more data for this extraction task. Two request-local buffers kept the beginning available while the reader visited metadata elsewhere, avoiding a third fetch when it returned. Large known ranges remained direct reads. Small returned slices were copied so the demuxer's own cache could not retain an entire backing buffer after the range reader evicted it:
if (cached)
return cached.bytes.slice(start - cached.start, end - cached.start);The copy spends some allocation and CPU to bound what a retained slice can keep alive. The two windows retain at most 64 KiB of read-ahead data; demuxer caches, direct reads, and decoder allocations still have their own memory costs. Expanded fetches count toward the reader's byte limits, and object version, ETag, and size checks remain in place. Optimizing the fetch shape does not relax the requirement to read a consistent object within the extraction budget.
The useful result was fewer remote operations at a modest extra byte cost. The buffer sizes belonged to that seek pattern. A largely sequential reader, a different mix of container formats, or a tighter byte budget could change the choice; a library preset's name does not settle it.
The older storage service b made the complementary change for uploads. It had copied incoming data to a temporary file, sought back, then copied it into the file backend. Because the destination already accepted a stream, io.Copy(writer, file) could write directly and eliminate the staging round trip. A consumer needing seeking or complete validation before publication might still justify staging. Buffering earns its place through the work it avoids or the contract it serves.
Select before expensive work expands
Dermail's mail listing needed a page assembled from selected folders. A broad range ordered by saved time followed by account and folder filtering examined mail that could never appear in that page. The replacement queried each requested folder through a compound folderSavedOn index, retained a continuation position for each folder, then merged the selected results. The API carried more cursor information so storage could select less irrelevant work before the merge. This is different from making reads cheaper by accepting older replicas: the access path changed without requiring that freshness tradeoff.
Vaskel's message owner stores messages and a local full-text index that can contain several rooms' messages. A common-term search originally processed more matches than the requested page needed. The revised query first finds the chosen room's oldest and newest nondeleted message creation sequences. These “live endpoints” bound the room's surviving message rows. The full-text index uses message creation sequences as row IDs, so it can traverse matching rows newest first within that interval and look up messages until LIMIT has enough eligible results. Room filtering and authorization remain in the owning transaction.
Those bounds narrow the search without making the interval exclusive to the room. Messages created in other rooms between its first and last live message can still fall inside it and must be filtered out. A sparse old room and a busy recent room can therefore have very different costs even when both return the same page size.
Finding the endpoints then became a hidden setup cost. Deleted messages were retained as tombstones; an index containing that history could scan many dead rows merely to establish that a room had no live messages. In a fixture with 10,000 tombstones, removing the explicit messages_live_history index selection caused 20,001 row reads for that boundary lookup. Refreshed planner statistics let the planner choose the live index in sampled fixtures, but the adopted query retained the explicit access path and used successful maintenance for opportunistic PRAGMA optimize. The decision concerned this schema and its retained-history workload, not a general preference to override every query planner.
Follow the whole access path. A query returning ten rows can examine far more than ten rows, and making the middle of the query faster can leave an expensive setup step intact.
Exercise the population that does the work
Vaskel sends encrypted browser push notifications to enrolled devices. Its tests needed distinct cohorts: nobody with a push subscription, some accounts enrolled, enrolled accounts with notifications muted, and everyone enrolled. These populations exercise different stages, from early refusal to authorization, presentation, encryption, and provider delivery. Improving the no-device path did little for overload when recipients actually needed delivery. Rachel also asked for a provider stub with roughly 150 ms latency, so the comparison would include waiting for external delivery instead of an instant no-op.
A later change kept content authorization with the message owner and moved preview rendering to the notification owner, which prepares the notification's presentation. The message owner selected the minimum authorized content needed by that mode. Generic notifications carried no preview text and did no Markdown rendering; preview modes rendered in the component responsible for showing it. This reduced work on the Send path while preserving the boundary that decides what content the recipient may see. Adding delivery concurrency alone would not remove that work from the message owner.
In one local comparison at 30 Sends per second for 180 seconds, with 64 enrolled accounts and eight rooms, the preview change reduced Send p95 from about 3.9 seconds to 1.36 seconds and failures from 131 of 5,400 requests to one. That was a substantial improvement with a remaining error, not a zero-error capacity result. Draining queued notifications continued for about 66 seconds after HTTP load stopped. Measure background completion as well as request latency: successful request admission and completed delivery describe different stages, and a fast front door can still accumulate unfinished work.
Preserve useful behavior while optimizing. If disabling cursor blink does not improve GPU use, restore the blink. If audio concealment improves playback, keep the loss counter: it still describes the incoming transport. See investigation and evidence for choosing comparisons that isolate these effects.