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:
- Authorization in Java. The client requests
/videos/42, the service checks permission and returns a short-lived signed URL (or uses nginx'sX-Accel-Redirectheader to redirect to an internal location: nginx serves the bytes, not Java). - Serving at the edge. nginx with
sendfile onserves from the page cache straight to the socket. One catch: with TLS, plainsendfiledoesn't work, because encryption happens in user space. On Linux, kTLS partly removes this limitation. - Range and cache. The video player requests in chunks with
Range: bytes=...;ETag,Last-ModifiedandAccept-Rangesmust be correct, otherwise the CDN cache doesn't work and every request goes to the origin. - 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.
- 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.
Sign up to mark studied questions and save your progress.