# Server System Optimization

Run system optimization before deployment or benchmarking.

## Why Optimize The Server?

### TCP Port Limits

Each MQTT connection consumes a TCP port. Linux dynamic/private ports are usually in the range `49152-65535`, which provides only 16,384 ports by default. High-concurrency MQTT scenarios should expand the usable local port range and tune network queues.

### File Descriptor Limits

Global file descriptor limits can cause additional TCP connections to fail. Increase both global and service-level limits before high-connection tests.

## Memory Allocation

Edit `/etc/sysctl.conf`:

```sh
vi /etc/sysctl.conf
```

Add:

```shell
vm.overcommit_memory=1
```

<img src="../../../../cluster/v2/images/server-common/step1.png" style="border:1px solid #ccc;border-radius:6px;margin:8px 0;" loading="lazy" alt="System optimization memory allocation configuration" />

Apply:

```sh
sysctl -p
```

<img src="../../../../cluster/v2/images/server-common/step2.png" style="border:1px solid #ccc;border-radius:6px;margin:8px 0;" loading="lazy" alt="System optimization configuration applied" />

## Global File Descriptor Limit

```shell
sysctl -w fs.file-max=1048576
sysctl -w fs.nr_open=1048576
echo 1048576 > /proc/sys/fs/nr_open
```

<img src="../../../../cluster/v2/images/server-common/step3.png" style="border:1px solid #ccc;border-radius:6px;margin:8px 0;" loading="lazy" alt="Global file descriptor limit configuration" />

## Service File Descriptor Limit

Edit systemd configuration:

```sh
vi /etc/systemd/system.conf
```

Add:

```shell
DefaultLimitNOFILE=1048576
```

<img src="../../../../cluster/v2/images/server-common/step4.png" style="border:1px solid #ccc;border-radius:6px;margin:8px 0;" loading="lazy" alt="Service file descriptor limit configuration" />

## User File Descriptor Limit

Edit user limits:

```sh
vi /etc/security/limits.conf
```

Add:

```shell
*  soft nofile 1048576
*  hard nofile 1048576
```

<img src="../../../../cluster/v2/images/server-common/step5.png" style="border:1px solid #ccc;border-radius:6px;margin:8px 0;" loading="lazy" alt="User file descriptor limit configuration" />

## TCP Network Optimization

Increase concurrent connection queues:

```shell
sysctl -w net.core.somaxconn=32768
sysctl -w net.ipv4.tcp_max_syn_backlog=16384
sysctl -w net.core.netdev_max_backlog=16384
```

<img src="../../../../cluster/v2/images/server-common/step6.png" style="border:1px solid #ccc;border-radius:6px;margin:8px 0;" loading="lazy" alt="TCP network concurrent connection optimization configuration" />

Expand the local port range:

```shell
sysctl -w net.ipv4.ip_local_port_range='1024 65535'
```

<img src="../../../../cluster/v2/images/server-common/step7.png" style="border:1px solid #ccc;border-radius:6px;margin:8px 0;" loading="lazy" alt="Local port range configuration" />
