DEV Community

ZoomApps
ZoomApps

Posted on

Video surveillance storage math: bitrate, retention and RAID for NVR servers

Storage for a camera system usually gets sized with a vendor calculator and a guess. The guess survives until someone asks for footage from day 28 and the archive turns out to hold 19 days. The arithmetic is simple. What goes wrong is the inputs: configured bitrate instead of measured, terabytes mixed with tebibytes, recorded substreams nobody counted, and a RAID level chosen for capacity with no thought about a two-day rebuild under constant write load.

This post goes through the whole chain for a 64-camera example: measuring bitrate, converting it to terabytes, picking a layout, recording and deleting files. The script output below comes from actually running the script. Camera bitrates are illustrative, so replace them with your own.

One number to remember

A continuous 1 Mbps stream produces:

1,000,000 bits/s × 86,400 s ÷ 8 = 10.8 GB per day
Enter fullscreen mode Exit fullscreen mode

So a 4 Mbps camera writes 43.2 GB per day, or about 1.3 TB in 30 days. This is decimal GB, the same unit drive makers use. Operating systems often report TiB: a 16 TB drive shows up as 14.55 TiB, which is about 9% "missing" space. Do all the math in decimal and convert only when comparing with df -h. Use df -H to avoid the conversion altogether.

Measure the bitrate, do not read it from the menu

The number in the camera web interface is a target or a cap, depending on the rate control mode:

  • CBR keeps the stream near the configured value. Storage is predictable, but a busy scene gets worse picture quality.
  • VBR varies with the scene. The configured value is normally a ceiling, and the average can be far below it or close to it.
  • Smart codec modes stretch the keyframe interval and starve static background. Savings are large in an empty corridor and small at a busy intersection.

Night matters too. When the sensor raises gain, noise looks like motion to the encoder, and a quiet parking lot can produce more data at 3 a.m. than at noon.

Measure one representative camera of each type for ten minutes, by day and by night:

URL='rtsp://user:pass@10.0.20.11/stream1'
BYTES=$(ffmpeg -v error -rtsp_transport tcp -i "$URL" \
  -map 0:v -c copy -t 600 -f matroska - | wc -c)
awk -v b="$BYTES" 'BEGIN { printf "%.2f Mbps\n", b * 8 / 600 / 1e6 }'
Enter fullscreen mode Exit fullscreen mode

This copies the stream without decoding, so it costs almost no CPU. If the camera drops halfway, the result is silently too low, so check that the command really ran for about 600 seconds.

While you are there, check codec, frame rate and resolution. The camera often disagrees with the project document:

ffprobe -v error -rtsp_transport tcp -select_streams v:0 \
  -show_entries stream=codec_name,width,height,avg_frame_rate \
  -of default=noprint_wrappers=1 "$URL"
Enter fullscreen mode Exit fullscreen mode

A calculator you can keep in the repo

Group cameras by type and retention, then let a script do the sums:

from dataclasses import dataclass
import math

@dataclass
class Group:
    name: str
    count: int
    main_mbps: float      # measured average, not the configured cap
    sub_mbps: float = 0.0 # 0 if the substream is not recorded
    duty: float = 1.0     # 1.0 = continuous
    days: int = 30

GROUPS = [
    Group("indoor 1080p", 40, 2.0, 0.5),
    Group("outdoor 4MP",  16, 4.0, 0.5),
    Group("gates 4K",      8, 8.0, 0.5, days=60),
]
OVERHEAD = 1.03   # container, indexes, metadata
GROWTH   = 1.15   # night noise, rain, a few new cameras
FILL     = 0.90   # keep 10% of the filesystem free

def tb_per_day(mbps):
    return mbps * 1e6 * 86400 / 8 / 1e12

ingest = need = 0.0
for g in GROUPS:
    mbps = g.count * (g.main_mbps + g.sub_mbps) * g.duty
    tb = tb_per_day(mbps) * g.days * OVERHEAD
    ingest += mbps
    need += tb
    print(f"{g.name:14} {mbps:6.0f} Mbps {tb:7.1f} TB for {g.days} days")

usable = need * GROWTH / FILL
print(f"ingest {ingest:.0f} Mbps = {ingest/8:.0f} MB/s")
print(f"archive {need:.1f} TB, usable to buy {usable:.1f} TB")
for size in (12, 16, 20):
    n = math.ceil(usable / size)
    print(f"{size} TB drives: RAID 6 = {n + 2}, RAID 10 = {2 * n}")
Enter fullscreen mode Exit fullscreen mode

Output:

indoor 1080p      100 Mbps    33.4 TB for 30 days
outdoor 4MP        72 Mbps    24.0 TB for 30 days
gates 4K           68 Mbps    45.4 TB for 60 days
ingest 240 Mbps = 30 MB/s
archive 102.8 TB, usable to buy 131.3 TB
12 TB drives: RAID 6 = 13, RAID 10 = 22
16 TB drives: RAID 6 = 11, RAID 10 = 18
20 TB drives: RAID 6 = 9, RAID 10 = 14
Enter fullscreen mode Exit fullscreen mode

Three things stand out.

Retention drives the cost more than resolution. Eight gate cameras take 44% of the archive because they keep 60 days. Asking which cameras really need the long period is the cheapest optimization available.

Substreams are not free. Recording a 0.5 Mbps substream from 64 cameras adds 32 Mbps, about 13% of ingest. It is worth it if operators scrub through low-resolution video, and wasted otherwise.

Margin is over a fifth of the purchase. Going from 102.8 TB to 131.3 TB looks like padding, but a filesystem at 99% fragments badly, and a camera swapped for a higher resolution model eats the growth allowance in one afternoon.

Motion recording: be careful with duty

Setting duty=0.3 cuts the estimate by 70%. Reality rarely follows. Outdoor cameras trigger on rain, headlights, insects and moving branches, and the duty cycle of one camera can triple between seasons. If you do use motion recording, size from a measured week per camera. A safer variant is recording the substream continuously and the main stream on events: you always have something to look at, and only the expensive part is variable.

Throughput is easy, the access pattern is not

30 MB/s is nothing for sequential disk writes. A single drive can do it. But 64 cameras with two streams each produce 128 files growing at the same time. If each stream is flushed in small pieces, the disks see scattered writes instead of a sequential stream, and parity RAID makes it worse.

On RAID 6, a write smaller than a full stripe becomes read-modify-write: read old data and both parity blocks, then write all three back. That is six disk operations per logical write. With full-stripe writes there is no read step at all.

Fixes that work:

  • Buffer several megabytes per stream in the recorder before flushing. A full stripe in the array below is 2.25 MB.
  • Align the filesystem with the stripe.
  • Give md RAID a larger stripe cache.
  • Keep database and index files on a separate SSD mirror, never on the video array.
# 11 drives in RAID 6 (9 data) plus a hot spare
mdadm --create /dev/md0 --level=6 --raid-devices=11 \
  --spare-devices=1 --chunk=256K --bitmap=internal /dev/sd[b-m]

# stripe cache: 8192 pages × 4 KiB × 11 drives ≈ 352 MiB of RAM
echo 8192 > /sys/block/md0/md/stripe_cache_size

mkfs.xfs -d su=256k,sw=9 /dev/md0
mount -o noatime,logbsize=256k /dev/md0 /rec
Enter fullscreen mode Exit fullscreen mode

Verify device names before running this: /dev/sd[b-m] matches 12 disks here and may match something else on your machine. The stripe_cache_size setting does not survive a reboot, so put it in a udev rule.

Reads are part of the load too. Exporting an incident from eight cameras, or analytics replaying the archive, competes with recording. Test playback while all cameras are recording, not on an idle array.

RAID level: decide by rebuild

Recording never stops, so a rebuild always competes with writes. A 16 TB drive rebuilt at a steady 100 MB/s takes 44 hours. If the array is busy and the rebuild gets 40 MB/s, it takes 111 hours, more than four and a half days.

RAID 5 has no redundancy during that window, and every surviving drive must be read completely. A simple model with the unrecoverable read error rate from the datasheet, for 16 TB drives:

RAID 5 drives Data to read P(at least one URE) at 1e-15 at 1e-14
6 80 TB 47% 99.8%
8 112 TB 59% 99.99%
12 176 TB 76% >99.99%

The formula is 1 - exp(-bits_read × rate). Datasheet rates are upper bounds and real drives usually do better, so treat these as a pessimistic comparison rather than a forecast. The conclusion is stable anyway: with drives this size, RAID 5 bets the archive on a clean read of everything.

Practical defaults:

  • RAID 6 for one array up to about 12 drives.
  • RAID 60, or several independent RAID 6 groups with cameras split between them, above that. Independent groups limit the damage: losing one group loses some cameras, not all of them.
  • RAID 10 if heavy playback and analytics reads matter more than cost. For our example it means 18 drives instead of 11.

RAID also does not protect against theft of the server, fire, or an administrator deleting the wrong directory. Footage that must be kept should be copied elsewhere on the day of the incident.

Check the workload rating

Drive datasheets list a workload rating in TB per year, and many manufacturers count reads as well as writes. Our 30 MB/s is about 946 TB of video per year. Spread over nine data drives with ideal full-stripe writes, that is roughly 105 TB per drive. If most writes degrade to read-modify-write, each logical byte costs three written and three read, and the same load becomes about 516 TB per drive. A drive rated for 180 TB per year is fine in the first case and far out of spec in the second.

Also avoid SMR drives in parity arrays. Sustained writes exhaust their cache area, and rebuilds can slow to the point where the controller drops the drive.

Recording: small files that survive a crash

If you build the recorder yourself, ffmpeg with stream copy handles the basic case:

ffmpeg -nostdin -v warning -rtsp_transport tcp -timeout 10000000 \
  -i "$URL" -map 0:v -c copy \
  -f segment -segment_time 300 -segment_atclocktime 1 \
  -reset_timestamps 1 -strftime 1 \
  "/rec/gates/cam07/%Y%m%d-%H%M%S.mkv"
Enter fullscreen mode Exit fullscreen mode

Details worth knowing:

  • MKV over plain MP4. A regular MP4 writes its index at the end, so a power cut leaves an unplayable file. An interrupted MKV is still playable.
  • Segments split on keyframes. With a 10-second keyframe interval, a 300-second segment can run up to 10 seconds over.
  • -timeout is in microseconds for RTSP. Without it, a hung camera can leave the process alive and recording nothing.
  • Run it under systemd with Restart=always, and write %%Y%%m%%d in the unit file, since a single % is a systemd specifier.
  • Alert on file age. A running process proves nothing. Check that the newest file for every camera is recent.

Deleting on schedule, not in panic

Retention needs two rules: a normal one by age and an emergency one by free space. The second should be noisy, because if it fires, your sizing is wrong.

#!/usr/bin/env bash
set -euo pipefail
mountpoint -q /rec || { echo "/rec is not mounted" >&2; exit 1; }

# days × 1440 minutes
find /rec/indoor /rec/outdoor -type f -name '*.mkv' -mmin +43200 -delete
find /rec/gates               -type f -name '*.mkv' -mmin +86400 -delete

used=$(df --output=pcent /rec | tail -1 | tr -dc '0-9')
if (( used > 92 )); then
  logger -p user.crit "NVR: /rec at ${used}%, retention at risk"
fi
Enter fullscreen mode Exit fullscreen mode

This version only alerts. If you add emergency deletion, remove the oldest files across all groups, log how many days of archive remain, and exclude directories with footage on legal hold. The mountpoint check is there for a reason: without it, a failed mount means the recorder fills the root filesystem while the script reports that all is well.

Track one metric above all: the age of the oldest file per camera. It answers "how many days do we have" directly, and a falling value warns you weeks before anyone needs the footage.

Do not forget the network and analytics

240 Mbps fits in a gigabit link, but leave room for playback and for a second copy of each stream if analytics pulls directly from the cameras. Put cameras in their own VLAN, record over TCP, and sync all clocks with NTP, because footage with a drifting timestamp is weak evidence.

Analytics is a separate budget. The recorder copies compressed packets. A detector has to decode them: a 1080p stream at 15 fps is about 31 million pixels per second, and 40 such cameras are over 1.2 billion. Run that on the recording machine's CPU and packet loss follows. Hardware decoding, preferably on a separate server, keeps the two loads apart.

Checklist

  1. Measure bitrate per camera type, day and night.
  2. Agree on retention per group, in writing.
  3. Compute in decimal TB, add growth and free space.
  4. RAID 6 or better, hot spare, CMR drives, workload rating checked.
  5. Pull a drive during acceptance testing and time the rebuild under full recording.
  6. Monitor oldest file age, newest file age, array state and SMART.

When detection, visitor counting or plate recognition has to run on top of the recordings, the compute side depends on stream count, resolution and frame rate, so have that list ready. We describe how we size servers for camera analytics on a separate page, including what to expect from existing cameras.

Top comments (0)