calricon.
VoIP & Telecom

The Kamailio TCP Connection Lifetime Trap: Why Idle Sockets Strand

Nov 11, 2026/7 min read/Verified Production Playbook

calricon / field note

Discover why Kamailio drops in-dialog carrier BYE requests on

Nov 11, 2026/VoIP & Telecom
343
Advertisement

The Kamailio TCP Connection Lifetime Trap: Why Idle Sockets Strand Carrier BYEs

In modern enterprise telecommunications and Session Border Controller (SBC) platforms, deploying SIP over reliable transport protocols (TCP and TLS) is standard practice for Microsoft Teams Direct Routing, cloud PBX interconnects, and mobile softphone clients. Because media streams flow out-of-band directly between endpoints or media relays, the signaling channel typically remains silent once call setup completes. However, telecommunications engineers operating Kamailio frequently encounter a severe billing and session management defect: on long-duration calls exceeding several minutes, when either party hangs up, the active session is never torn down on the opposing leg. Upstream carrier switches leave the trunk channel active for hours, billing enterprise accounts for ghost calls. Inbound SIP BYE packets arrive at Kamailio but fail transmission, generating socket connection errors in proxy logs. The root cause is premature TCP connection eviction driven by misconfigured idle connection lifetimes and unmaintained network address translation (NAT) state tables.



Problem Diagnosis & Root Cause Architecture

Under RFC 3261, a client operating over TCP establishes a persistent connection to the SIP proxy from an ephemeral local source port (e.g., client at 198.51.100.55 port 42189 connecting to Kamailio at 203.0.113.10 port 5060). Kamailio indexes this connection within its internal TCP connection hash table. The operational breakdown develops through a sequence of transport-layer timeouts:




  • Idle Connection Table Purging: While human speech flows continuously via Real-time Transport Protocol (RTP), the SIP signaling socket carries no traffic during conversational periods. In default Kamailio environments, tcp_connection_lifetime defaults to 120 or 300 seconds. When no signaling packets traverse the socket within this window, Kamailio's internal timer process silently drops the socket descriptor from its active connection table.

  • Intermediate NAT Stateful Expiration: Cloud firewalls, AWS NAT Gateways, and enterprise edge routers enforce idle state timeouts (typically 350 seconds for TCP). If the voice platform sends no keepalive frames across the signaling path, the NAT gateway deletes the translation entry, stranding the connection without transmitting a TCP FIN or RST packet.

  • Inbound BYE Routing Failure: When the caller hangs up, the PSTN carrier sends a SIP BYE to Kamailio. Kamailio inspects the Route header or Contact URI to forward the request downstream. Because the original established TCP socket has been purged, Kamailio attempts to open a NEW outbound TCP connection to the destination address specified in the Contact header (e.g., 198.51.100.55:42189).

  • Firewall Rejection and Ghost Session Accumulation: Because the client resides behind a stateful NAT firewall, unsolicited incoming TCP SYN packets to ephemeral ports are instantly dropped by the remote firewall (returning ECONNREFUSED or ETIMEDOUT). Kamailio discards the BYE message. The downstream PBX or carrier billing switch continues to treat the call as active, stranding channels indefinitely.




"Long-duration SIP dialogs over connection-oriented transports require synchronized socket persistence. When signaling sockets remain idle without bidirectional application-layer keepalives, firewalls and proxies purge connection states, rendering in-dialog BYE requests undeliverable and stranding active billing trunks."


Why Standard Implementations Fail

Relying on Default Core TCP Lifetimes

Many system administrators configure basic TCP listeners using parameters such as enable_tcp=yes and tcp_children=8, leaving tcp_connection_lifetime unconfigured. The default 120-second timeout guarantees that any voice call lasting longer than two minutes will lose its signaling socket. When an in-dialog re-INVITE, UPDATE, or BYE arrives, the proxy fails to deliver the packet.



Assuming OS TCP Keepalives Maintain NAT Pinholes

Enabling kernel-level keepalives (tcp_keepalive=1) without application-layer keepalive signaling is frequently insufficient. Many cloud provider NAT routers and stateful mobile carrier firewalls inspect packet payload depth. Zero-length TCP keepalive probes are often dismissed by intermediate security middleboxes, allowing the NAT pinhole to close prematurely while the local host still considers the socket open.



Omitting Contact Alias Tracking on Asymmetric Routes

When softphones register from behind NAT, standard routing scripts record the private Contact URI. If the proxy fails to invoke add_contact_alias() or handle_rport() during initial registration and transaction processing, Kamailio cannot correlate subsequent in-dialog requests with the physical connection identifier, forcing it to attempt invalid outbound connection attempts to unroutable private addresses.



Validated Step-by-Step Resolution Playbook

Step 1: Diagnose Dropped TCP Connections and Failed BYE Delivery

Inspect Kamailio system logs and active TCP connection states to verify whether call teardown failures result from socket evictions and failed re-connection attempts:



# Check Kamailio logs for TCP send failures during BYE routing
grep -E "tcpconn_send.*failed|msg_send: tcp_send failed" /var/log/kamailio.log | sed 15q

# Inspect active TCP connection table and verify socket lifetimes
kamcmd tcp.list

# Check operating system TCP connection states on port 5060
ss -t -a -p -n | grep :5060


Step 2: Calibrate Core TCP Connection Lifetimes and Kernel Parameters

Update kamailio.cfg to extend the global TCP connection lifetime beyond typical maximum call durations (e.g., 3605 seconds for 1-hour calls) and tune TCP socket keepalive probes:



# /etc/kamailio/kamailio.cfg
# Global TCP engine configuration for carrier-grade stability

enable_tcp = yes
tcp_children = 16

# Set idle TCP connection lifetime to 1 hour plus grace period (in seconds)
tcp_connection_lifetime = 3605

# Enable TCP keepalive probes on underlying sockets
tcp_keepalive = yes
tcp_keepidle = 30
tcp_keepintvl = 10
tcp_keepcnt = 3

# Configure asynchronous TCP send queue to prevent worker blocking
tcp_async = yes
tcp_connect_timeout = 3
tcp_send_timeout = 5
tcp_conn_wq_max = 65536


Step 3: Enable Bidirectional CRLF Ping Keepalives via Nathelper

Configure the nathelper module to transmit lightweight 2-byte CRLF (Carriage Return / Line Feed) keepalives through active TCP sockets every 30 seconds. This prevents intermediate cloud NAT gateways from evicting idle translations:



# /etc/kamailio/kamailio.cfg
# Nathelper module configuration for persistent signaling pinholes

loadmodule "nathelper.so"

# Send periodic keepalives every 30 seconds
modparam("nathelper", "natping_interval", 30)

# Ping only clients detected behind NAT
modparam("nathelper", "ping_nated_only", 1)

# Transmit raw 4-byte CRLFCRLF sequences over UDP/TCP
modparam("nathelper", "natping_processes", 3)
modparam("nathelper", "natping_crlf", 1)


Step 4: Implement Contact Alias Tracking for In-Dialog Routing

Ensure that initial registrations and inbound transactions attach an alias matching the active TCP connection. This guarantees that subsequent in-dialog BYE requests are dispatched across the existing open socket rather than triggering new outbound connection attempts:



# Routing script logic: preserving connection aliases
route[REQINIT] {
# Detect NAT and force symmetric routing
if (nat_uac_test("19")) {
force_rport();
if (is_method("REGISTER")) {
fix_nated_register();
} else {
fix_nated_contact();
}
}
}

route[SIPOUT] {
if (is_method("INVITE")) {
# Bind the active TCP connection identifier to the Record-Route header
record_route_preset("203.0.113.10:5060;transport=tcp;alias");
}

# Handle in-dialog requests using alias correlation
if (has_totag()) {
if (loose_route()) {
# Route in-dialog request through established TCP alias socket
handle_rport();
t_relay();
exit;
}
}
}


Step 5: Verify Long-Duration Call Teardown and Signaling Persistence

Simulate an extended 10-minute SIP call over TCP using SIPp. Verify that the signaling socket remains established throughout the idle conversational period and that the terminal BYE delivers without packet loss:



# Run 10-minute call scenario over TCP using SIPp
sipp -sn uac -t t1 -r 1 -m 1 -d 600000 https://www.google.com/url?q=https://www.google.com/url?q%3Dhttp://203.0.113.10:5060%26source%3Dgmail%26ust%3D1794513060580000%26sa%3DE&source=gmail&ust=1794516376245000&sa=E

# Inspect active TCP connection lifetime in Kamailio during the call
kamcmd tcp.list | grep -E "timeout|state|address"

# Monitor live SIP signaling to confirm immediate 200 OK response to the BYE
sngrep -d eth0 -c port 5060

Advertisement
Engineering Advisory 48-Hour Audit Turnaround

Experiencing this issue in your production systems?

Calricon conducts senior-level VoIP, SIP trunking, Asterisk, and cloud infrastructure audits. We review your live configs, identify packet drops or contention bottlenecks, and provide exact remediation runbooks.