# sFlow - Network Traffic Monitoring

> Configuring sFlow in VyOS - packet sampling, flow export to a collector, traffic monitoring, and network performance analysis

Source: https://opennix.org/en/docs/vyos/system/vyos-sflow/


## Overview

sFlow (Sampled Flow) is an industry-standard network traffic monitoring technology based on statistical packet sampling. Unlike NetFlow, which analyzes every flow, sFlow samples random packets, which places a lower load on the router while preserving statistical accuracy.

### Key sFlow Features

**How it works:**
- Statistical packet sampling (for example, 1 out of 1000)
- Sending packet samples to a collector
- Interface counter polling
- IPv4 and IPv6 support
- Real-time export

**Advantages of sFlow:**
- Low CPU and memory load on the router
- Scalability for high-speed links
- Detailed information about packet contents
- Standardized data format (RFC 3967)
- Support for multi-vendor environments

**Use cases:**
- Network performance monitoring
- Traffic and application behavior analysis
- Detection of DDoS attacks and anomalies
- Link capacity planning
- Network troubleshooting
- Bandwidth usage accounting

### sFlow vs NetFlow

| Characteristic | sFlow | NetFlow |
|---------------|-------|---------|
| Collection method | Statistical packet sampling | Analysis of all flows |
| CPU load | Low | Medium/High |
| Memory usage | Minimal | Significant |
| Scalability | Excellent for 10G+ | Limited at high speeds |
| Granularity | Packet samples + counters | Aggregated flows |
| Export latency | Real time | Delay until flow ends |
| Standardization | RFC 3967, open standard | Cisco proprietary, IPFIX (standard) |
| L2 support | Yes | Limited |

### sFlow Architecture

```
┌─────────────────────────────────────────────────────────┐
│                     VyOS Router                         │
│                                                         │
│  ┌────────────┐    ┌──────────────┐   ┌─────────────┐ │
│  │ Interface  │───>│ sFlow Agent  │──>│ sFlow       │ │
│  │ eth0       │    │              │   │ Exporter    │ │
│  └────────────┘    │ - Sampling   │   └──────┬──────┘ │
│                    │ - Polling    │          │         │
│  ┌────────────┐    │              │          │         │
│  │ Interface  │───>│              │          │         │
│  │ eth1       │    └──────────────┘          │         │
│  └────────────┘                              │         │
│                                               │ UDP 6343│
└───────────────────────────────────────────────┼─────────┘
                                                │
                                                v
                                    ┌───────────────────┐
                                    │ sFlow Collector   │
                                    │                   │
                                    │ - sFlowTrend      │
                                    │ - ntopng          │
                                    │ - Prometheus      │
                                    └───────────────────┘
```

### sFlow Components

1. **sFlow Agent** - a software agent on the router that performs sampling and export
2. **Sampling** - the statistical packet sampling mechanism
3. **Counter Polling** - periodic collection of interface statistics
4. **sFlow Collector** - a server that receives and analyzes sFlow data
5. **Analyzer** - a tool for visualizing and analyzing the data

## Implementation in VyOS

VyOS uses **hsflowd** (Host sFlow Daemon) to implement sFlow functionality. It is a lightweight and efficient agent that supports the sFlow version 5 standard.

**Supported capabilities:**
- sFlow agent configuration
- Selecting interfaces to monitor
- Configuring the sampling rate
- Configuring the counter polling interval
- Support for multiple collectors
- IPv4 and IPv6 collectors
- Dropped packet monitoring (drop monitor)
- Egress traffic sampling

## Basic Configuration

### Minimal Setup

To get sFlow working, you must configure at least three parameters:

```bash
# Адрес агента sFlow (источник экспорта)
set system sflow agent-address '192.168.1.1'

# Интерфейс для мониторинга
set system sflow interface 'eth0'

# Коллектор sFlow
set system sflow server 192.168.100.10 port 6343

# Применить конфигурацию
commit
save
```

### Full Configuration with Parameters

```bash
# Настройка агента sFlow
set system sflow agent-address '10.0.0.1'
set system sflow agent-interface 'eth0'

# Интерфейсы для мониторинга
set system sflow interface 'eth0'
set system sflow interface 'eth1'
set system sflow interface 'eth2'

# Параметры выборки
set system sflow sampling-rate '2000'
set system sflow polling '20'

# Коллекторы sFlow
set system sflow server 10.100.1.5 port 6343
set system sflow server 10.100.1.6 port 6343

# Дополнительные параметры
set system sflow drop-monitor-limit '100'
set system sflow enable-egress

# Применить конфигурацию
commit
save
```

## Detailed Parameter Configuration

### Agent Configuration

#### Agent Address

The agent address specifies the IP address that will be used as the source in the exported sFlow datagrams:

```bash
set system sflow agent-address '192.168.1.1'
```

**Recommendations:**
- Use the IP address of the management interface
- The address must be reachable from the collector
- For source identification in a multi-router environment

#### Agent Interface

An alternative to specifying a fixed IP address is selecting an interface:

```bash
set system sflow agent-interface 'eth0'
```

The agent will use the primary IP address of the specified interface. This is useful with dynamic addressing.

### Selecting Interfaces to Monitor

Specify all interfaces whose traffic you want to monitor:

```bash
# Физические интерфейсы
set system sflow interface 'eth0'
set system sflow interface 'eth1'
set system sflow interface 'eth2'
set system sflow interface 'eth3'

# VLAN интерфейсы
set system sflow interface 'eth0.100'
set system sflow interface 'eth0.200'

# Bond интерфейсы
set system sflow interface 'bond0'

# Туннельные интерфейсы
set system sflow interface 'tun0'
set system sflow interface 'wg0'
```

**Important:**
- Each interface is added with a separate command
- You can monitor physical, VLAN, bond, and tunnel interfaces
- The interface must be active (up)

### Sampling Rate

The sampling rate determines which packet out of every N is selected for analysis:

```bash
set system sflow sampling-rate '1000'
```

**Default value:** 1000 (every thousandth packet)

**Recommendations for choosing the sampling rate:**

| Link speed | Recommended sampling rate | Rationale |
|----------------|----------------------------|-------------|
| 100 Mbps | 500-1000 | Low speed, accuracy can be increased |
| 1 Gbps | 1000-2000 | Standard value |
| 10 Gbps | 5000-10000 | High load, lower the rate |
| 40 Gbps | 20000-40000 | Very high speed |
| 100 Gbps | 50000-100000 | Maximum optimization |

**Balancing accuracy and performance:**

```bash
# Высокая точность, повышенная нагрузка (малый трафик)
set system sflow sampling-rate '500'

# Стандартная точность (обычный случай)
set system sflow sampling-rate '1000'

# Оптимизация для высокоскоростных каналов
set system sflow sampling-rate '5000'

# Минимальная нагрузка (очень высокий трафик)
set system sflow sampling-rate '10000'
```

**Calculation formula:**
```
Sampling Rate = Interface Speed (Mbps) / Desired Samples per Second
```

Example: for a 1 Gbps link and a target of 1000 samples/sec:
```
Sampling Rate = 1000 Mbps / 1 Mbps/sample = 1000
```

### Polling Interval

The polling interval determines how often interface counters are collected (in seconds):

```bash
set system sflow polling '30'
```

**Default value:** 30 seconds

**Recommendations:**

```bash
# Частый опрос для детального мониторинга
set system sflow polling '10'

# Стандартный интервал
set system sflow polling '30'

# Редкий опрос для снижения нагрузки
set system sflow polling '60'
```

**What the interface counters include:**
- Inbound/outbound traffic bytes
- Inbound/outbound traffic packets
- Errors and dropped packets
- Broadcast and multicast packets
- Interface state

**Choosing the interval:**
- **10-20 seconds:** Active monitoring, fast problem detection
- **30 seconds:** Standard value, a balance of accuracy and load
- **60+ seconds:** Long-term trend monitoring, minimal load

### Collector Configuration

#### Adding a Collector

```bash
set system sflow server <IP-address> port <port>
```

**Standard sFlow port:** 6343 (UDP)

**Examples:**

```bash
# IPv4 коллектор
set system sflow server 192.168.100.10 port 6343

# IPv6 коллектор
set system sflow server 2001:db8::100 port 6343

# Альтернативный порт
set system sflow server 10.0.0.100 port 9999
```

#### Multiple Collectors

sFlow supports exporting data to multiple collectors simultaneously:

```bash
# Основной коллектор (производственный мониторинг)
set system sflow server 10.100.1.5 port 6343

# Резервный коллектор
set system sflow server 10.100.1.6 port 6343

# Коллектор для анализа безопасности
set system sflow server 10.200.1.10 port 6343

# Тестовый коллектор
set system sflow server 192.168.1.100 port 6343
```

**Use cases for multiple collectors:**
- Monitoring redundancy
- Separation by function (monitoring, security, billing)
- Integration with different systems
- Testing without disrupting the primary monitoring

### Additional Parameters

#### Dropped Packet Monitoring (Drop Monitor)

Tracking packets dropped by the Linux kernel:

```bash
set system sflow drop-monitor-limit '100'
```

This parameter sets the maximum number of tracked packet drop points. It is useful for diagnosing performance and configuration issues.

**Reasons packets are dropped:**
- Buffer overflow
- No route
- Firewall rules
- Forwarding errors
- MTU exceeded

#### Egress Traffic Sampling

By default, sFlow samples only inbound traffic. To enable outbound traffic sampling:

```bash
set system sflow enable-egress
```

**Use cases:**
- Full traffic accounting (ingress + egress)
- Flow symmetry analysis
- Egress QoS monitoring
- Detecting anomalies in outbound traffic

**Warning:** This doubles the number of exported samples for transit traffic.

## Configuration Examples

### Example 1: Basic Monitoring of an Office Router

**Scenario:** An office VyOS router with a 100 Mbps link, exporting sFlow to an internal monitoring server.

```bash
configure

# Агент sFlow на интерфейсе управления
set system sflow agent-address '192.168.1.1'

# Мониторинг WAN интерфейса
set system sflow interface 'eth0'

# Мониторинг LAN интерфейса
set system sflow interface 'eth1'

# Частая выборка для небольшого трафика
set system sflow sampling-rate '500'

# Стандартный интервал опроса
set system sflow polling '30'

# Коллектор на сервере мониторинга
set system sflow server 192.168.1.100 port 6343

commit
save
exit
```

### Example 2: Data Center with High-Speed Links

**Scenario:** VyOS as a data center edge router with 10 Gbps links, exporting to a cluster of collectors.

```bash
configure

# Агент на loopback интерфейсе для стабильности
set interfaces loopback lo address '10.255.255.1/32'
set system sflow agent-address '10.255.255.1'

# Мониторинг всех uplink интерфейсов
set system sflow interface 'eth0'
set system sflow interface 'eth1'
set system sflow interface 'eth2'
set system sflow interface 'eth3'

# Оптимизированная частота для 10G
set system sflow sampling-rate '8000'

# Редкий опрос для снижения нагрузки
set system sflow polling '60'

# Основной коллектор
set system sflow server 10.100.1.5 port 6343

# Резервный коллектор
set system sflow server 10.100.1.6 port 6343

# Мониторинг потерь
set system sflow drop-monitor-limit '100'

# Двусторонняя выборка
set system sflow enable-egress

commit
save
exit
```

### Example 3: Multi-Tenant Provider

**Scenario:** VyOS for a service provider with tenant isolation via VLANs and detailed traffic accounting.

```bash
configure

# Агент на управляющем интерфейсе
set system sflow agent-address '10.0.0.1'

# Мониторинг транковых портов
set system sflow interface 'eth0'
set system sflow interface 'eth1'

# Мониторинг VLAN интерфейсов клиентов
set system sflow interface 'eth0.100'
set system sflow interface 'eth0.101'
set system sflow interface 'eth0.102'
set system sflow interface 'eth0.200'
set system sflow interface 'eth0.201'

# Высокая точность для биллинга
set system sflow sampling-rate '1000'

# Частый опрос для точной статистики
set system sflow polling '20'

# Коллектор биллинговой системы
set system sflow server 10.200.1.10 port 6343

# Коллектор мониторинга
set system sflow server 10.100.1.5 port 6343

# Коллектор анализа безопасности
set system sflow server 10.150.1.20 port 6343

commit
save
exit
```

### Example 4: VPN Concentrator with Tunnels

**Scenario:** VyOS as a VPN concentrator with many IPsec and WireGuard tunnels, monitoring encrypted traffic.

```bash
configure

# Агент на loopback
set interfaces loopback lo address '172.16.255.1/32'
set system sflow agent-address '172.16.255.1'

# Мониторинг физических интерфейсов
set system sflow interface 'eth0'
set system sflow interface 'eth1'

# Мониторинг IPsec туннелей
set system sflow interface 'vti0'
set system sflow interface 'vti1'
set system sflow interface 'vti2'

# Мониторинг WireGuard
set system sflow interface 'wg0'
set system sflow interface 'wg1'

# Стандартная выборка
set system sflow sampling-rate '2000'

# Частый опрос для VPN метрик
set system sflow polling '15'

# Коллектор мониторинга VPN
set system sflow server 10.100.1.15 port 6343

# Включение egress для полного учета
set system sflow enable-egress

commit
save
exit
```

### Example 5: Yandex Cloud - Exporting sFlow to a Monitoring System

**Scenario:** VyOS in Yandex Cloud acting as a NAT gateway, exporting sFlow to a virtual machine running a collector to monitor per-tenant traffic consumption.

```bash
configure

# Агент на внутреннем интерфейсе
set system sflow agent-address '10.128.0.10'

# Мониторинг внешнего интерфейса (к интернету)
set system sflow interface 'eth0'

# Мониторинг внутренних интерфейсов (подсети в VPC)
set system sflow interface 'eth1'
set system sflow interface 'eth2'

# Оптимизация для облачной среды (1 Gbps каналы)
set system sflow sampling-rate '2000'
set system sflow polling '30'

# Коллектор на отдельной ВМ в той же VPC
set system sflow server 10.128.0.100 port 6343

# Резервный коллектор в другой зоне доступности
set system sflow server 10.129.0.100 port 6343

# Мониторинг отброшенных пакетов
set system sflow drop-monitor-limit '50'

commit
save
exit
```

**Additional collector setup in Yandex Cloud:**

On a virtual machine running Ubuntu 22.04:

```bash
# Установка sFlowTrend (коммерческий коллектор с бесплатной версией)
# или ntopng, или Prometheus с sFlow экспортером

# Для ntopng:
sudo apt update
sudo apt install ntopng

# Настройка ntopng для приема sFlow
sudo nano /etc/ntopng/ntopng.conf
# Добавить:
# -i=sflow:6343
# --http-port=3000

sudo systemctl enable ntopng
sudo systemctl start ntopng

# Настройка Security Group для разрешения UDP 6343
# В веб-консоли Yandex Cloud: VPC -> Security Groups
# Входящий трафик: UDP, порт 6343, источник - CIDR VyOS подсети
# Входящий трафик: TCP, порт 3000, источник - ваш IP (для веб-интерфейса)
```

### Example 6: VK Cloud - Multi-Interface Monitoring

**Scenario:** VyOS in VK Cloud as an edge router for a microservices architecture, exporting sFlow to sFlowTrend to analyze inter-service traffic.

```bash
configure

# Агент на loopback для независимости от интерфейсов
set interfaces loopback lo address '172.31.255.1/32'
set system sflow agent-address '172.31.255.1'

# Мониторинг интерфейса к интернету
set system sflow interface 'eth0'

# Мониторинг интерфейсов к микросервисам
set system sflow interface 'eth1.100'  # Frontend subnet
set system sflow interface 'eth1.200'  # Backend subnet
set system sflow interface 'eth1.300'  # Database subnet
set system sflow interface 'eth1.400'  # Cache subnet

# Мониторинг интерфейса к системам хранения
set system sflow interface 'eth2'

# Высокая точность для анализа микросервисов
set system sflow sampling-rate '1500'

# Частый опрос для быстрого обнаружения проблем
set system sflow polling '20'

# Коллектор sFlowTrend в той же VPC
set system sflow server 172.31.10.50 port 6343

# Мониторинг входящего и исходящего трафика
set system sflow enable-egress

# Отслеживание потерь для диагностики
set system sflow drop-monitor-limit '100'

commit
save
exit
```

**Setting up sFlowTrend in VK Cloud:**

```bash
# На виртуальной машине Ubuntu 22.04
# sFlowTrend доступен как Docker контейнер

# Установка Docker
sudo apt update
sudo apt install docker.io docker-compose
sudo systemctl enable docker
sudo systemctl start docker

# Запуск sFlowTrend
sudo docker run -d \
  --name sflowtrend \
  -p 6343:6343/udp \
  -p 8087:8087 \
  --restart=always \
  sflow/sflowtrend:latest

# Проверка
sudo docker logs sflowtrend

# Доступ к веб-интерфейсу: http://<VM-IP>:8087
```

## Verifying the Configuration

### Viewing the sFlow Configuration

```bash
show configuration commands | grep sflow
```

Output:
```
set system sflow agent-address '192.168.1.1'
set system sflow interface 'eth0'
set system sflow interface 'eth1'
set system sflow polling '30'
set system sflow sampling-rate '1000'
set system sflow server 192.168.100.10 port '6343'
```

### Checking sFlow Agent Operation

```bash
show system sflow
```

The output provides information about the state of the sFlow agent:
```
Agent Address: 192.168.1.1
Agent Interface: eth0
Polling Interval: 30
Sampling Rate: 1000
Drop Monitor Limit: not configured
Egress: disabled

Collectors:
  192.168.100.10:6343

Monitored Interfaces:
  eth0
  eth1
```

### Checking the hsflowd Process

```bash
show process hsflowd
```

Or through the Linux operational mode:

```bash
run show processes | grep hsflow
```

```bash
ps aux | grep hsflowd
```

Expected output:
```
root      1234  0.0  0.1  12345  6789 ?        Ss   10:30   0:00 /usr/sbin/hsflowd
```

### Monitoring sFlow Logs

The hsflowd logs are found in the system logs:

```bash
show log | match sflow
```

Or directly:

```bash
journalctl -u hsflowd -f
```

Example logs at startup:

```
hsflowd[1234]: agent address set to 192.168.1.1
hsflowd[1234]: monitoring interface eth0
hsflowd[1234]: monitoring interface eth1
hsflowd[1234]: collector 192.168.100.10:6343 configured
hsflowd[1234]: sampling rate: 1000
hsflowd[1234]: polling interval: 30s
```

### Verifying sFlow Packet Transmission

Checking network activity on the collector port:

```bash
sudo tcpdump -i any udp port 6343 -n
```

Output (if export is working):
```
10:35:01.123456 IP 192.168.1.1.54321 > 192.168.100.10.6343: UDP, length 1400
10:35:02.234567 IP 192.168.1.1.54321 > 192.168.100.10.6343: UDP, length 1400
10:35:03.345678 IP 192.168.1.1.54321 > 192.168.100.10.6343: UDP, length 1400
```

### Testing Collector Reachability

```bash
ping 192.168.100.10
```

```bash
traceroute 192.168.100.10
```

Checking UDP port reachability (from the VyOS machine):

```bash
nc -u -v 192.168.100.10 6343
```

### Interface Statistics

Checking the counters that sFlow exports:

```bash
show interfaces ethernet eth0
```

```bash
show interfaces statistics
```

Important fields:
- RX packets/bytes (inbound traffic)
- TX packets/bytes (outbound traffic)
- RX errors (receive errors)
- TX errors (transmit errors)
- RX dropped (dropped on receive)
- TX dropped (dropped on transmit)

## Monitoring and Analysis

### Popular sFlow Collectors and Analyzers

**Open source solutions:**

1. **sFlowTrend**
   - Free collector and analyzer
   - Web interface for visualization
   - Alert support
   - URL: https://inmon.com/products/sFlowTrend.php

2. **ntopng**
   - Powerful network traffic analyzer
   - Support for sFlow, NetFlow, IPFIX
   - Detailed application analytics
   - URL: https://www.ntop.org/products/traffic-analysis/ntop/

3. **pmacct (Promiscuous mode IP Accounting)**
   - Collector for billing and accounting
   - Export to MySQL, PostgreSQL, MongoDB
   - Integration with Kafka
   - URL: http://www.pmacct.net/

4. **ElastiFlow**
   - Collector for Elasticsearch + Kibana
   - Ready-made dashboards
   - Scalable architecture
   - URL: https://github.com/robcowart/elastiflow

**Commercial solutions:**

1. **Kentik**
   - SaaS platform for traffic analysis
   - DDoS detection
   - Cloud integration

2. **Plixer Scrutinizer**
   - Enterprise solution
   - Advanced analytics
   - Compliance reporting

3. **SolarWinds NetFlow Traffic Analyzer**
   - Integration with the SolarWinds ecosystem
   - Application performance analysis

### Setting Up a Basic Collector on Linux

Example of installing ntopng on Ubuntu 22.04:

```bash
# Добавление репозитория ntop
sudo apt-get install software-properties-common wget
sudo add-apt-repository universe
wget -qO - https://packages.ntop.org/apt-stable/22.04/all/apt-ntop-stable.deb.gpg.key | sudo apt-key add -
sudo add-apt-repository "deb https://packages.ntop.org/apt-stable/22.04/all/ x64/"

# Установка ntopng
sudo apt-get update
sudo apt-get install ntopng

# Настройка для приема sFlow
sudo nano /etc/ntopng/ntopng.conf

# Добавить строки:
-i=sflow:6343
--http-port=3000
--community

# Запуск
sudo systemctl enable ntopng
sudo systemctl start ntopng

# Проверка
sudo systemctl status ntopng

# Доступ к веб-интерфейсу: http://<server-ip>:3000
# Логин по умолчанию: admin / admin
```

### Prometheus and Grafana Integration

To export sFlow metrics to Prometheus, use sflow_exporter:

```bash
# Установка Go (если еще не установлен)
wget https://go.dev/dl/go1.21.0.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.21.0.linux-amd64.tar.gz
export PATH=$PATH:/usr/local/go/bin

# Клонирование и сборка sflow_exporter
git clone https://github.com/czerwonk/sflow_exporter.git
cd sflow_exporter
go build

# Запуск
./sflow_exporter -sflow.listen-address=:6343 -web.listen-address=:9090

# Конфигурация Prometheus (prometheus.yml)
scrape_configs:
  - job_name: 'sflow'
    static_configs:
      - targets: ['localhost:9090']
```

### Analyzing sFlow Data

**Key metrics to monitor:**

1. **Bandwidth utilization**
   - Inbound/outbound bps
   - Top sources/destinations by volume
   - Usage trends

2. **Application performance**
   - Top applications by traffic
   - Port and protocol distribution
   - Flow-level latency

3. **Security**
   - Anomaly detection (traffic spikes)
   - Top sources/destinations by PPS (packet scan detection)
   - Packet size distribution (DDoS indicators)

4. **Quality of service**
   - Dropped packets (drop monitor)
   - Interface errors
   - Buffering and delays

**Queries for analysis:**

In ntopng or other analyzers:

- Top Talkers (top sources by traffic)
- Flow Analysis (analysis of flows by 5-tuple)
- Protocol Distribution
- Port Analysis (analysis of used ports)
- Autonomous System Analysis (AS-level traffic)
- Geolocation Analysis (geographic distribution)

## Troubleshooting

### sFlow Data Is Not Reaching the Collector

**Check 1: The sFlow agent is running**

```bash
ps aux | grep hsflowd
```

If the process is not running:

```bash
sudo systemctl status hsflowd
sudo systemctl restart hsflowd
```

**Check 2: The configuration is applied**

```bash
show configuration commands | grep sflow
```

Make sure the configuration includes:
- An agent address or agent interface
- At least one interface to monitor
- At least one collector server

**Check 3: Network reachability of the collector**

```bash
ping <collector-ip>
traceroute <collector-ip>
```

Checking the UDP port:

```bash
nc -u -v <collector-ip> 6343
```

**Check 4: Firewall on VyOS**

Make sure outbound UDP traffic to port 6343 is not blocked:

```bash
show firewall
```

If there are rules for outbound traffic, add an allow rule:

```bash
set firewall name WAN_OUT rule 100 action accept
set firewall name WAN_OUT rule 100 protocol udp
set firewall name WAN_OUT rule 100 destination port 6343
commit
```

**Check 5: Firewall on the collector**

On the collector server:

```bash
# Linux firewall
sudo ufw status
sudo ufw allow 6343/udp

# iptables
sudo iptables -I INPUT -p udp --dport 6343 -j ACCEPT
```

**Check 6: The collector is listening on the correct port**

On the collector server:

```bash
sudo netstat -ulnp | grep 6343
```

Expected output:
```
udp    0    0 0.0.0.0:6343    0.0.0.0:*    12345/ntopng
```

If the port is not being listened on, check the collector configuration.

### High CPU Load from hsflowd

**Cause:** A sampling rate that is too aggressive for the traffic volume.

**Solution:** Increase the sampling rate (reduce the sampling frequency):

```bash
# Было
set system sflow sampling-rate '500'

# Стало
set system sflow sampling-rate '5000'
commit
```

**Monitoring CPU load:**

```bash
show system cpu
```

```bash
top
```

The hsflowd process should consume < 5% CPU under normal conditions.

### Loss of sFlow Packets in Transit

**Symptoms:** The collector shows gaps in the data and incomplete statistics.

**Cause:** A limitation on link bandwidth or UDP buffers.

**Diagnostics:**

On VyOS:
```bash
show interfaces statistics
# Проверить TX dropped на интерфейсе, отправляющем sFlow
```

On the collector:
```bash
netstat -su | grep "packet receive errors"
```

**Solution 1:** Increase the sampling rate (fewer export packets):

```bash
set system sflow sampling-rate '10000'
commit
```

**Solution 2:** Increase the UDP buffers on the collector:

```bash
# Linux
sudo sysctl -w net.core.rmem_max=134217728
sudo sysctl -w net.core.rmem_default=134217728
```

**Solution 3:** Use multiple collectors with load balancing.

### Incorrect Agent Address in the Exported Data

**Problem:** The collector shows the wrong source IP address.

**Solution:** Explicitly specify the agent address:

```bash
set system sflow agent-address '10.0.0.1'
commit
```

Or use a loopback:

```bash
set interfaces loopback lo address '10.255.255.1/32'
set system sflow agent-address '10.255.255.1'
commit
```

### Interfaces Are Not Exporting Data

**Check:** The interface must be in the up state:

```bash
show interfaces
```

**Solution:** Make sure the interface is active and correctly configured:

```bash
set interfaces ethernet eth0 description 'WAN'
set interfaces ethernet eth0 address 'dhcp'
commit
```

Then add it to sFlow:

```bash
set system sflow interface 'eth0'
commit
```

### The Collector Does Not Recognize Traffic from VyOS

**Problem:** The sFlow protocol version or data format.

**Diagnostics:** Check the collector logs for parsing errors.

**Solution:** VyOS uses sFlow version 5 (standard). Make sure the collector supports sFlow v5.

Checking the hsflowd version:

```bash
hsflowd -v
```

### Data for Some Protocols Is Missing

**Cause:** Sampling is a statistical method; some low-volume protocols may not appear in the sample.

**Solution:** Lower the sampling rate to increase accuracy:

```bash
set system sflow sampling-rate '500'
commit
```

**Alternative:** Use NetFlow/IPFIX for detailed analysis of all flows (additional load).

## Best Practices

### Planning an sFlow Deployment

1. **Defining monitoring goals**
   - Network performance
   - Billing and accounting
   - Security and attack detection
   - Troubleshooting

2. **Selecting interfaces**
   - Critical uplink/downlink interfaces
   - Interfaces to servers/data centers
   - Network entry/exit points

3. **Calculating the sampling rate**
   - Balance of accuracy and performance
   - Accounting for link speeds
   - Granularity requirements

4. **Collector architecture**
   - Redundancy (multiple collectors)
   - Scalability (clustering)
   - Data storage (retention policy)

### Performance Optimization

**Recommendations for VyOS:**

1. **Adaptive sampling rate**
   - 100 Mbps: 500-1000
   - 1 Gbps: 1000-2000
   - 10 Gbps: 5000-10000
   - 40+ Gbps: 20000-50000

2. **Polling interval**
   - Active monitoring: 10-20 seconds
   - Standard: 30 seconds
   - Long-term trends: 60+ seconds

3. **Limiting egress sampling**
   - Enable only when necessary
   - Account for the doubling of export volume

4. **Using loopback for the agent address**
   - Independence from the state of physical interfaces
   - A single device identifier

### Security

**Protecting collectors:**

1. **Isolating the monitoring network**
   - A dedicated VLAN for sFlow traffic
   - Restricting access to collectors

2. **Authentication and encryption**
   - sFlow does not support built-in encryption
   - Use VPN tunnels to transmit over untrusted networks
   - Restrict access to the collector with a firewall

3. **Source validation**
   - Configure the collector to accept only from known IP addresses
   - Monitor abnormal volumes of sFlow traffic

**Example of a VPN tunnel for sFlow over the internet:**

```bash
# На VyOS (sFlow exporter)
configure

# WireGuard туннель к удаленному коллектору
set interfaces wireguard wg10 address '10.99.0.1/30'
set interfaces wireguard wg10 private-key <key>
set interfaces wireguard wg10 peer remote-collector pubkey <pubkey>
set interfaces wireguard wg10 peer remote-collector endpoint 'collector.example.com:51820'
set interfaces wireguard wg10 peer remote-collector allowed-ips '10.99.0.0/30'

# sFlow через туннель
set system sflow agent-address '192.168.1.1'
set system sflow interface 'eth0'
set system sflow server 10.99.0.2 port 6343

commit
save
```

### Monitoring sFlow Itself

**Metrics to track:**

1. **Availability of the hsflowd process**
   - Alerting when the process crashes

2. **Network reachability of the collector**
   - Monitoring with pings
   - Checking the UDP port

3. **Volume of exported data**
   - Monitoring TX on the source interface
   - Tracking RX on the collector

4. **Packet loss**
   - Dropped packets on VyOS
   - UDP receive errors on the collector

**Example of monitoring via a script:**

```bash
#!/bin/bash
# Скрипт проверки sFlow

# Проверка процесса
if ! pgrep hsflowd > /dev/null; then
    echo "CRITICAL: hsflowd not running"
    exit 2
fi

# Проверка доступности коллектора
if ! ping -c 1 192.168.100.10 > /dev/null 2>&1; then
    echo "CRITICAL: Collector unreachable"
    exit 2
fi

# Проверка конфигурации
INTERFACES=$(cli-shell-api showConfig system sflow interface | wc -l)
if [ "$INTERFACES" -eq 0 ]; then
    echo "WARNING: No interfaces configured"
    exit 1
fi

echo "OK: sFlow operational"
exit 0
```

### Documentation and Auditing

**Maintain documentation:**

1. **Inventory**
   - List of devices with sFlow
   - Agent addresses
   - Monitored interfaces

2. **Configurations**
   - Templates for different device types
   - Sampling rates for different speeds
   - List of collectors and their purpose

3. **Procedures**
   - Troubleshooting
   - Configuration updates
   - Adding new devices

4. **Auditing**
   - Regular review of configurations
   - Validation of export operation
   - Analysis of sampling rate effectiveness

### Integration with Monitoring Systems

**SNMP for state monitoring:**

```bash
set service snmp community public authorization ro
set service snmp community public network 192.168.100.0/24
commit
```

**Syslog for centralized logging:**

```bash
set system syslog host 192.168.100.20 facility all
set system syslog host 192.168.100.20 facility local7 level debug
commit
```

**API for automation:**

The VyOS API can be used to programmatically manage sFlow:

```bash
# Включение API
set service https api keys id automation key 'YOUR_API_KEY'
commit
```

Example of automatically adding interfaces via the API (Python):

```python
import requests

vyos_api = "https://192.168.1.1/configure"
api_key = "YOUR_API_KEY"
headers = {"Content-Type": "application/json"}

interfaces = ["eth0", "eth1", "eth2"]

for iface in interfaces:
    payload = {
        "key": api_key,
        "op": "set",
        "path": ["system", "sflow", "interface", iface]
    }
    response = requests.post(vyos_api, json=payload, headers=headers, verify=False)
    print(f"Added {iface}: {response.json()}")

# Commit
commit_payload = {
    "key": api_key,
    "op": "commit"
}
requests.post("https://192.168.1.1/config-file", json=commit_payload, headers=headers, verify=False)
```

## Additional Resources

### Official Documentation

- **VyOS sFlow Documentation:** https://docs.vyos.io/en/latest/configuration/system/sflow.html
- **sFlow.org (official website):** https://sflow.org/
- **sFlow RFC 3967:** https://tools.ietf.org/html/rfc3967
- **Host sFlow Daemon:** https://github.com/sflow/host-sflow

### Collectors and Analyzers

- **sFlowTrend:** https://inmon.com/products/sFlowTrend.php
- **ntopng:** https://www.ntop.org/
- **pmacct:** http://www.pmacct.net/
- **ElastiFlow:** https://github.com/robcowart/elastiflow
- **Grafana sFlow plugin:** https://grafana.com/grafana/plugins/

### Articles and Guides

- **Understanding sFlow:** https://sflow.org/sFlowOverview.pdf
- **sFlow vs NetFlow comparison:** https://sflow.org/sFlowVsNetFlow.html
- **Best practices for network monitoring:** https://sflow.org/best_practices.php

### Testing Tools

- **sflowtool:** A command-line utility for decoding sFlow (https://github.com/sflow/sflowtool)
  ```bash
  sudo apt install sflowtool
  sflowtool -p 6343
  ```

- **sflow-rt:** A real-time sFlow analyzer (https://sflow-rt.com/)

### Community

- **VyOS Community:** https://forum.vyos.io/
- **VyOS Slack:** https://slack.vyos.io/
- **sFlow Discussion Group:** https://groups.google.com/g/sflow

## Conclusion

sFlow is a powerful and efficient network traffic monitoring technology, especially well suited for high-speed links and cloud environments. Key advantages:

- **Scalability:** Suitable for links from 100 Mbps to 100+ Gbps
- **Low load:** Minimal impact on router performance
- **Granularity:** Packet samples + interface counters
- **Standardization:** An open standard with broad support
- **Flexibility:** Support for multiple collectors and a wide range of scenarios

With a properly configured sampling rate and polling interval, sFlow provides an optimal balance between monitoring accuracy and system resources. Integration with modern monitoring systems (ntopng, Grafana, Elasticsearch) makes it possible to build a full-fledged platform for network analysis, problem detection, and infrastructure growth planning.

For cloud providers (Yandex Cloud, VK Cloud) and service providers, sFlow is a critically important tool for traffic accounting, billing, ensuring SLAs, and security.

