networking · intermediate · ~15 min

Choose the right keep-alive interval

Defensive choice of TCP keep-alive interval.

Challenge

You're building a service that maintains long-lived TCP connections through NATs. Given the expected NAT timeout (in seconds), pick the keep-alive interval that keeps the connection alive without hammering the network.

Implement int suggest_keepalive_interval(int nat_timeout_s) returning the interval in seconds. The rule:

  • If nat_timeout_s <= 60, return 30 (refresh every 30s on aggressive NATs).
  • If nat_timeout_s <= 600, return nat_timeout_s / 2.
  • Otherwise return 300 (cap at 5 minutes — saves bandwidth on long timeouts).

Special cases: if nat_timeout_s <= 0, return -1 (invalid input).

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

NAT timeout in seconds.

Output format

Interval in seconds (or -1).

Constraints

Pure arithmetic; no syscalls.

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.