Simulating network latency on Linux

If you want to run test cases that are sensitive to network latency, it’s important to also test them under the effect of different latencies. For example you want to know what it means if you move an application currently running on the same server as the database to a different server. Or you are doing some small tests locally on your computer and want to know how they would behave in a real environment where client and server are on different machines, maybe even with long geographical distances between them.

I usually use the method described here when I want to run some tests on my laptop where I have an Oracle Database running in a Virtualbox VM.

Linux provides a kernel module called NetEm (Network Emulator). With NetEm you can add a delay to all packages leaving (outgoing) a certain network interface. You can do a lot more things with NetEm like duplicating, corrupting or reordering packages and more. Check the man page or the links at the end of this post to find out more about it.

NetEm is an enhancement of the Linux traffic control facilities and can therefore be controlled with tc.

Using the tc command line tool to add a delay

Add a delay of 10ms to eth1

tc qdisc add dev eth1 root netem delay 10ms

Change an already configured delay

tc qdisc change dev eth1 root netem delay 5ms

Show configuration of eth1

tc qdisc show dev eth1

Remove a configured delay

tc qdisc del dev eth1 root netem delay 4ms

Example

I’m just going to ping my virtual machine and add a delay after a couple of pings.

Ping my virtual machine from my local machine

ping oracle-database-183

Add delay of 10ms on eth1 on my virtual machine. This means the packages leaving eth1 (in this examples the answers to the ping) will be delayed by 10ms.

tc qdisc add dev eth1 root netem delay 10ms

Output of ping

PING oracle-database-183 (192.168.56.202): 56 data bytes
64 bytes from 192.168.56.202: icmp_seq=0 ttl=64 time=0.255 ms
64 bytes from 192.168.56.202: icmp_seq=1 ttl=64 time=0.376 ms
64 bytes from 192.168.56.202: icmp_seq=2 ttl=64 time=0.329 ms
64 bytes from 192.168.56.202: icmp_seq=3 ttl=64 time=0.336 ms
64 bytes from 192.168.56.202: icmp_seq=4 ttl=64 time=0.310 ms
64 bytes from 192.168.56.202: icmp_seq=5 ttl=64 time=10.870 ms
64 bytes from 192.168.56.202: icmp_seq=6 ttl=64 time=10.992 ms
64 bytes from 192.168.56.202: icmp_seq=7 ttl=64 time=10.910 ms
64 bytes from 192.168.56.202: icmp_seq=8 ttl=64 time=10.900 ms
64 bytes from 192.168.56.202: icmp_seq=9 ttl=64 time=10.790 ms

The output of ping clearly shows the effect of adding the delay with tc.

References