Video in progress

The company wants to build a self-hosted service that serves large video and archive files. What architecture decisions do you make at the IO level?

I take serving the bytes off the Java application and hand it to a layer built for it: a CDN, or a reverse proxy that uses sendfile. The Java service deals only with authorization, metadata and signed links; Range requests, caching and TLS live at the edge.

📖 Answer

Streaming large static files through Java works, but it is expensive: every byte passes through the JVM, TLS encryption runs on the CPU, and slow clients hold threads and memory. nginx or a CDN does the same job much more cheaply.

The scheme I propose:

  1. Authorization in Java. The client requests /videos/42, the service checks permission and returns a short-lived signed URL (or uses nginx's X-Accel-Redirect header to redirect to an internal location: nginx serves the bytes, not Java).
  2. Serving at the edge. nginx with sendfile on serves from the page cache straight to the socket. One catch: with TLS, plain sendfile doesn't work, because encryption happens in user space. On Linux, kTLS partly removes this limitation.
  3. Range and cache. The video player requests in chunks with Range: bytes=...; ETag, Last-Modified and Accept-Ranges must be correct, otherwise the CDN cache doesn't work and every request goes to the origin.
  4. Format. Serving a long video as HLS/DASH segments rather than a single file: the cache works well, and switching quality and resuming get easier.
  5. The disk layer. Origin servers need enough RAM so that hot files stay in the page cache; the cold archive sits in cheap object storage. With many origins, distribute files by consistent hashing so each file lives in the cache of one or two servers.

The IO work left on the Java side: uploads, queueing for transcoding, checksums and metadata. These are asynchronous jobs, not on the user request path.

The basis for the decision is simple math: expected concurrent viewers × bitrate = egress traffic. 2000 viewers × 5 Mbit/s = 10 Gbit/s. Serving that from a single Java service is picking the wrong tool; compare the CDN price against the cost of your own origin using this number.