# TorrServer Cache & Settings Tuning

## Settings File Location

TorrServer MatriX.142 stores settings in `{path}/settings.json` when `StoreSettingsInJson: true` (the default). The `--path` flag defaults to current directory; our instance uses `--path /home/rurouni/torrserver-data`.

```json
{
  "BitTorr": {
    "CacheSize": 1073741824,
    "ConnectionsLimit": 500,
    "PreloadCache": 5,
    "ReaderReadAhead": 95,
    "ResponsiveMode": true,
    "UseDisk": false,
    "RemoveCacheOnDrop": true,
    "StoreSettingsInJson": true
  }
}
```

Full settings are at `/home/rurouni/torrserver-data/settings.json`.

## How TorrServer Reads Settings

1. TorrServer starts → reads `settings.json` if `StoreSettingsInJson: true`
2. Calls `SetBTSets()` → validates and clamps values, persists to internal DB
3. On settings change, drops all active torrents, disconnects BTServer, reconnects
4. **To apply new settings**: edit `settings.json`, kill TorrServer, restart
5. No need to delete `config.db` — JSON is authoritative

## Critical Settings for Streaming

### CacheSize (default: 64MB)
Total amount of torrent data held in memory or on disk. Formula: `Cache.capacity` field.

- **Default**: 64MB (`67108864`) — way too small for 2-16GB video files
- **Recommended**: 1GB (`1073741824`) for smooth streaming
- **Validation**: If 0, falls back to `info.PieceLength * 4` (~16MB)
- **Eviction**: When `filled > capacity`, oldest-accessed pieces outside active reader ranges are evicted

### PreloadCache (default: 90 — THE BUFFERING CULPRIT)
Percentage of CacheSize to preload BEFORE serving any video data.

**The math** (from `apihelper.go`):
```go
cache := float32(sets.BTsets.CacheSize)   // 1GB = 1,073,741,824
preload := float32(sets.BTsets.PreloadCache) // 5%
size := int64((cache / 100.0) * preload)     // ~50MB
torr.Preload(index, size)                    // Preload 50MB then start playing
```

With PreloadCache=90 and CacheSize=4GB:
- `(4,294,967,296 / 100.0) * 90 = 3,865,470,566` (3.6GB)
- TorrServer tries to download 3.6GB before serving any bytes
- For a 2.72GB YIFY file: **entire file downloads before playback starts**
- User sees "Starting stream... Fetching subtitles... Buffering..." for 30-60s

With PreloadCache=5 and CacheSize=1GB:
- `(1,073,741,824 / 100.0) * 5 = 53,687,091` (~50MB)
- TorrServer buffers 50MB (~10-15 seconds of 1080p) then starts playing
- First video appears in 1-3 seconds

**Recommended**: `PreloadCache: 5` for instant playback

### ReaderReadAHead (default: 95)
Percentage (5-100) controlling how the cache window splits between data behind and ahead of current read position.

```go
prc      = ReaderReadAHead          // 95
share    = Cache.capacity / readers // capacity split across active readers
beginOffset = r.offset - share * (100 - prc) / 100  // 5% behind
endOffset   = r.offset + share * prc / 100          // 95% ahead
```

95% ahead means 95% of cache is used for forward read-ahead. Fine for streaming.

### UseDisk (default: false)
- `false` → RAM cache (`MemPiece` — `[]byte` slices). Faster, no I/O bottleneck.
- `true` → Disk cache (`DiskPiece` — files at `TorrentsSavePath/<hash>/<piece-id>`). Slower but persists across restarts.
- **Recommended**: `false` when streaming from a server with abundant RAM

### ResponsiveMode (default: true)
When enabled, TorrServer prioritizes playback responsiveness over download speed. Keep enabled.

### ConnectionsLimit (default: 200)
Max simultaneous peer connections. **Recommended**: `500` for faster swarm join.

## How to Change Settings & Apply

```bash
# 1. Edit settings
vim /home/rurouni/torrserver-data/settings.json

# 2. Kill TorrServer
kill $(pgrep torrserver)

# 3. Restart
/usr/local/bin/torrserver --port 8090 --ip 0.0.0.0 \
  --path /home/rurouni/torrserver-data --dontkill &

# 4. Verify settings took effect
cat /home/rurouni/torrserver-data/settings.json | \
  python3 -m json.tool | grep -E "CacheSize|PreloadCache|UseDisk"
```

## Optimal Settings for Smooth Streaming

| Setting | Default | Optimal | Why |
|---------|---------|---------|-----|
| CacheSize | 64MB | 1GB | Enough for smooth buffering of 1080p-4K |
| PreloadCache | 90% | 5% | Instant playback instead of 30-60s preload |
| UseDisk | false | false | RAM is faster on 32GB server |
| ConnectionsLimit | 200 | 500 | Faster peer swarm join |
| ReaderReadAhead | 95 | 95 | Default is fine — aggressive forward-read |
| ResponsiveMode | true | true | Keep — prioritizes playback |
| RemoveCacheOnDrop | false | true | Cleanup stale torrent cache |

## CLI Flags (for reference)

TorrServer MatriX.142 CLI:
```
--port PORT, -p PORT      web server port (default 8090)
--ip IP, -i IP            web server addr (default empty)
--path PATH, -d PATH      database and config dir path
--dontkill, -k            don't kill server on signal
```

Cache-specific settings are NOT available as CLI flags — only via `settings.json`. The CLI only exposes basic networking and auth flags.

## Source

This is based on the TorrServer DeepWiki cache/storage internals (February 2026) and hands-on testing with MatriX.142 (July 2026). The full DeepWiki is at:
https://deepwiki.com/YouROK/TorrServer/5.5-cache-and-storage-configuration

Key source files:
- `server/settings/btsets.go` — BTSets struct with defaults
- `server/torr/apihelper.go` — SetSettings(), Preload() function
- `server/torr/storage/torrstor/cache.go` — Cache capacity and eviction
- `server/torr/storage/torrstor/reader.go` — ReaderReadAHead window calc
