5h4d0w.net

The Cat's den

Broken_WD_RED

Lately I have been playing around with Open Broadcaster Software while using nginx as a RTMP server in order to share games and videos with my friends, as well as my day-to-day amateur sysadmin fun, in a somewhat more private fashion than using a public platform like Twitch or YouTube.

When streaming to nginx from OBS, I noticed on the server that video fragments are written to the disk in order to build the streaming playlist. And when you're streaming 24/7, it adds up quite fast, especially for 1080p content at 60 FPS. At a rate of ~2.5 GB per hour, we're looking at almost 1.8 TB (!!) of data written to the disk every month, which is about twice the capacity of the drive. That will definitely cause the premature death of my SSD, or at least increase substantially its wear level.

A lot of small data chunks continuously written to disk, but only stored for a few seconds ? Sounds like a perfect job for a ramdisk.

Creating the ramdisk

Warning : By design, any file stored in a tmpfs filesystem does not survive a reboot !

Create your mount point mkdir -p /mnt/ramdisk/nginx

Declare your ramdisk in /etc/fstab by adding the following line

tmpfs /mnt/ramdisk/nginx tmpfs rw,size=32M 0 0

Mount the ramdisk with mount -a

Configuring nginx

In your nginx config file, declare recursive_error_pages on; inside the http {} block.

The recursive error pages is the trick that will allow us to serve static pages from the hard drive, as well as dynamic video content from the ramdisk.

Edit the locations in the server {} block

location / {
    root /var/www/html/;
    error_page 404 = @ramdisk;
}

location @ramdisk {
    root /mnt/ramdisk/nginx/;
}

Basically, we're instructing nginx to serve content from the hard disk by default. If no content is found (404), try to serve the content from the ramdisk.

Restart nginx and you should be good to go !

Complete nginx config file example

http {
    recursive_error_pages on;
    server {
        listen 80;
        server_name example.tld;
        location / {
            root /var/www/html/;
            error_page 404 = @ramdisk;
        }
        location @ramdisk {
            root /mnt/ramdisk/nginx/;
        }
    }
}