# ? Simulating Database Latency in Docker

This guide explains how to **simulate network latency between a database server and a web server** in a **Docker environment**. This setup helps debug issues that may arise in production when the database and web server are on **separate physical machines**.

## ? Prerequisites

### **Modify `docker-compose.yml`**
To allow **network emulation (`tc netem`)**, you must add the following **one-liner change** in `docker-compose.yml`:

```yaml
services:
  db:
    image: mysql:5.7.34
    platform: linux/amd64  # Required for compatibility on Mac M1/M2
    environment:
      MYSQL_ROOT_PASSWORD: root
    networks:
      mynetwork:
        ipv4_address: 192.168.1.2
    cap_add:
      - NET_ADMIN  # ? This is the only required change
```

Now, restart your project with:

```bash
make down && make up
```

---

## ? 1. Install `iproute2` in the `db` Container

To ensure `tc` is available inside the container, run:

```bash
make db_latency_install
```

This installs `iproute2` inside the `db` container **automatically**.

---

## ? 2. Add Network Latency

To **simulate a 10ms latency**:

```bash
make db_latency LATENCY=10
```

To **modify the latency (e.g., change to 5ms)**:

```bash
make db_latency LATENCY=5
```

---

## ? 3. Remove Network Latency

To remove all latency settings and restore normal speed:

```bash
make db_latency LATENCY=stop
```

Verify the removal:

```bash
docker compose exec -u root db tc -s qdisc show dev eth0
```

If nothing appears, the latency is successfully removed ?.

---

## ? 4. Restart the `db` Container (if needed)

If issues persist, restart the database container:

```bash
make down && make up
```

---

## ? **Summary of Commands**

| Action | Command |
|--------|---------|
| Install `iproute2` | `make db_latency_install` |
| Add latency (10ms) | `make db_latency LATENCY=10` |
| Modify latency (5ms) | `make db_latency LATENCY=5` |
| Remove latency | `make db_latency LATENCY=stop` |
| Check `tc` rules | `docker compose exec -u root db tc -s qdisc show dev eth0` |
| Restart project | `make down && make up` |
