Skip to content
S. Contreras
Get in touch
Writing

1 min read Media

Encoding to a budget, not to a setting

Discord rejects uploads over the server tier limit, and one overlay job can produce a 200 KB still or a 40 MB video. The fix was to treat the limit as a budget and negotiate quality downward.

A fixed encoder setting is a bet that every input looks alike. In a bot that accepts “any image, GIF or video a user can point at”, that bet loses twice: small inputs get encoded far below what the budget allows, and large ones fail outright after the work is already done.

The limit is a number you can read

Discord exposes the guild’s premium tier, and the tier maps to an upload ceiling of 10 MB, 50 MB or 100 MB. That turns an unpredictable failure into a known budget before the first frame is encoded.

Negotiate downward, in fixed steps

The encoder runs a ladder. Attempt one uses the best profile; if the output overshoots the ceiling, the next profile drops FPS, scale and color count for GIFs, or raises CRF for MP4s. Four steps in total, and the first result that fits is the one that ships.

Fixed steps matter more than clever search. A binary search on quality would mean more encodes for a marginally better result, and encoding is the expensive part. Each attempt costs real seconds of ffmpeg time.

Bound everything that touches the network

Every fetch carries a 15-second timeout; every ffmpeg process a 45-second one. Without them, one hostile input (a URL that trickles bytes, a video that expands pathologically) occupies the worker indefinitely. With them, that input fails alone and the next job proceeds.

The general shape: read the constraint from the platform, spend the budget in known steps, and put a ceiling on every operation that can block.