networking · intermediate · ~15 min

Choose the right keep-alive interval

Defensive choice of TCP keep-alive interval.

Challenge

A long-lived TCP connection through a NAT gets silently dropped once the NAT's idle timer expires, so a service sends periodic keep-alives. Given the NAT's idle timeout, pick a keep-alive interval that refreshes the mapping in time without flooding the network. This is pure arithmetic — no sockets.

Task

Implement int suggest_keepalive_interval(int nat_timeout_s) that returns the keep-alive interval in seconds, using these rules:

  • nat_timeout_s <= 60 -> return 30 (aggressive NAT: refresh every 30s).
  • nat_timeout_s <= 600 -> return nat_timeout_s / 2.
  • otherwise -> return 300 (cap at 5 minutes to save bandwidth).
  • nat_timeout_s <= 0 -> return -1 (invalid input).

Input

One int nat_timeout_s — the NAT's idle timeout in seconds.

Output

Returns the suggested interval in seconds, or -1 for invalid (non-positive) input.

Example

suggest_keepalive_interval(60)     ->   30
suggest_keepalive_interval(120)    ->   60
suggest_keepalive_interval(1800)   ->   300
suggest_keepalive_interval(0)      ->   -1

Edge cases

  • Non-positive input returns -1.
  • The boundaries 60 and 600 are inclusive (<=).

Why this matters

A long-lived connection without keep-alive will be silently dropped by NAT boxes after a few minutes. Picking the interval is the defensive-server skill nobody teaches.

Input format

One integer: the NAT idle timeout in seconds.

Output format

The suggested keep-alive interval in seconds, or -1 for non-positive input.

Constraints

Pure arithmetic; no syscalls. Boundaries 60 and 600 are inclusive.

Starter code

int suggest_keepalive_interval(int nat_timeout_s) { /* TODO */ (void)nat_timeout_s; return 0; }

Common mistakes

Returning the NAT timeout itself — too late by then.

Edge cases to handle

0 or negative input; exactly 60 (boundary); exactly 600 (boundary).

Complexity

O(1).

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.