DEV Community

Tayyab Hafiz
Tayyab Hafiz

Posted on

Rolling deploys without dropping live calls, running a Twilio Media Streams service on AKS

This article was drafted with AI help and reviewed by the author.

Most ASP.NET Core services on Kubernetes handle short requests. A rolling deploy replaces pods, a few in-flight requests finish during the grace period, and nobody notices.

A service that handles Twilio bidirectional Media Streams is different. Each phone call holds one WebSocket open for its whole length, carrying audio in both directions. If the pod handling that socket goes away, the caller's conversation with your agent goes with it.

This post covers what to change when that service runs on AKS. It looks at what Twilio does when the socket closes, how to drain pods, how to recover a call that does get cut, and how to keep the audio loop fast. Twilio behavior is taken from its TwiML and Media Streams reference, and Kubernetes behavior from the upstream pod lifecycle page, both read on 27 November 2026. Durations and names used below are fictional.

What Twilio does when your socket closes

Twilio's docs spell this out for bidirectional streams started with Connect and Stream:

  • The stream ends when the call ends or when your server closes the WebSocket.
  • If your server closes it and the Connect verb has an action URL, Twilio requests that URL.
  • Without an action URL, Twilio carries on with whatever TwiML follows Connect. If nothing follows, the call ends.

So a pod restart without planning means a hang-up. A pod restart with an action URL means Twilio comes back to you and asks what to do next. That second path is the safety net, covered below.

Drain instead of kill

When Kubernetes terminates a pod, it sends SIGTERM, and the pod gets a grace period before it is killed. The default grace period is 30 seconds. Calls run for minutes.

The plan has three parts.

1. Stop taking new calls. On SIGTERM, flip readiness to false. Kubernetes stops routing new connections to a terminating pod, and your own readiness check makes that explicit. New Twilio connections go to other pods. Existing sockets stay open.

2. Let existing calls finish. Keep the process alive while it still has active streams. Track a simple count of open media sockets. When it hits zero, exit.

3. Set the limits to match. Raise the pod's termination grace period to cover a long call plus margin. The ASP.NET Core generic host has its own shutdown timeout, so raise that too, or the host will stop before Kubernetes would have.

An example of picking the numbers. Say your call records show most calls end within 8 minutes and a few run to 14. A grace period of 15 minutes covers nearly all of them. The few longer calls fall back to the recovery path. Pick your own numbers from your own call durations, not from this example.

The trade-off is slower rollouts. A deployment with a 15 minute drain takes longer to finish. Tune maxSurge in the rollout strategy so new pods come up before old ones drain, and capacity doesn't dip.

Other things that evict pods

Deploys aren't the only cause. On AKS also watch for:

  • Node image and Kubernetes upgrades. Nodes are cordoned and drained. A PodDisruptionBudget limits how many media pods go at once. Check how long your upgrade settings wait for a drain.
  • Cluster autoscaler scale-down. The autoscaler can evict pods from underused nodes. Kubernetes' cluster autoscaler respects an annotation that marks a pod as not safe to evict. Consider it for media pods, and keep a minimum node count for the pool.
  • Spot nodes. Spot evictions give little notice. Keep the media service off spot pools.

The recovery path: the Connect action URL

Some calls will still get cut. A node fails, or a call outlasts the grace period. The action URL turns that into a short pause instead of a hang-up.

How it fits together, with example values:

  1. The first TwiML response starts the bidirectional stream and sets an action URL on the Connect verb, for example the path /calls/stream-ended.
  2. While the call runs, the media service saves the conversation state to Redis after every turn. The key is the call SID. The value holds the transcript so far, the last intent, and any IDs the agent has collected.
  3. The pod shuts down and closes the socket.
  4. Twilio requests the action URL for that call.
  5. The handler reads the Redis entry for the call SID. If the conversation is still in progress, it answers with fresh TwiML that opens a new stream, with the call SID passed as a stream parameter.
  6. A healthy pod accepts the new socket, loads the state from Redis, and the agent says something like "Sorry, I lost you for a second. You were asking about Thursday."

A sample state entry, invented for illustration:

  • key: conversation for CA90d1
  • turns so far: 6
  • last intent: reschedule appointment
  • collected: customer ID 44120, current slot Thursday 10:00
  • status: in progress
  • saved: 4 seconds before the socket closed

Two rules keep this safe. The handler must check that the call is really still in progress, because the action URL also fires when your server closes the socket deliberately at the end of a conversation. And the Redis entry needs a TTL so finished calls don't pile up.

Keep the audio loop warm

Drain and recovery protect calls. These choices protect response time.

  • No scale to zero for the media service. Keep a minimum replica count. A cold container on the first call of the morning shows up as silence.
  • Scale on active streams, not CPU. Audio relay is often light on CPU while still near its connection limit. Expose the open-socket count as a metric and drive the autoscaler from it, for example through KEDA or a custom metrics adapter.
  • Open provider connections early. When the stream's start message arrives, open the speech-to-text and text-to-speech connections immediately, before the caller finishes their first sentence.
  • Check the ingress. Whatever terminates the WebSocket, such as an ingress controller or Application Gateway, must allow upgrades and must not cut idle connections shorter than your longest silence. Check its timeouts against the length of a call.

Put the cluster near the media path

The stream's audio enters Twilio's network and then travels to your WebSocket endpoint. Every extra thousand kilometres between the two adds round-trip time to every turn.

For calls into a US number, an AKS cluster in an Azure region on the US east coast keeps that hop short. For a European number, a region in Ireland or Frankfurt is a better match. These are example pairings. Measure from your own cluster to the providers your agent uses before committing to a region, and keep the speech providers in the same region as the cluster where you can.

If you run more than one region, route each call to the cluster nearest where its media enters, not to one central cluster.

Limitations

  • Raising grace periods slows deploys, upgrades and scale-down. That is the cost of not dropping calls.
  • The recovery path works only if state is saved often. A crash mid-turn loses that turn.
  • A reconnected stream is a new WebSocket. Audio already buffered on the old one is gone, so the agent should repeat its last sentence or acknowledge the gap.
  • Twilio's docs say the only way to stop a bidirectional stream is to end the call or update it with new TwiML. Plan your reconnect around those two options.

Takeaways

  • A media stream lives as long as the call, so treat pod shutdown as a call-handling event.
  • On SIGTERM, stop taking new streams and let open ones finish within a grace period sized from real call lengths.
  • Protect media pods from autoscaler eviction and spot nodes, and use a PodDisruptionBudget.
  • Set a Connect action URL and save state per turn so a cut call can reconnect.
  • Keep minimum replicas, scale on open sockets, and place the cluster near where the audio enters.

Pod lifecycle is only one part of the delay picture. For the full chain, from edge choice to streaming every stage and tuning end-of-turn detection, see this practical guide to lower Twilio voice latency.

References

Top comments (4)

Collapse
 
userxnom profile image
Abdullah Naseer •

Tayyab, the reframe that makes this post is treating pod shutdown as a call-handling event, not an infra event — the SIGTERM readiness flip plus a grace period sized from real call durations, not a guessed 30 seconds, is the difference between a deploy and a hang-up. Scaling on open sockets instead of CPU is the other sharp call: audio relay is light on CPU while sitting near its connection limit, so CPU-based scaling would happily add pods nobody needs and miss the real bottleneck. One question on the recovery path: when the Connect action URL reconnects a call and the agent resumes from Redis state saved a few seconds before the cut, how do you stop the agent from repeating or skipping the turn that was in flight when the socket died — do you replay the last turn, or mark it as uncertain and ask the caller to confirm?

Collapse
 
tayyab_hafiz_dev_0 profile image
Tayyab Hafiz •

I think the real challenge in call recovery is maintaining conversational continuity, not simply restoring the connection.
A saved state doesn't necessarily mean the last turn was successfully completed. I'd approach this by tracking turn states explicitly; completed, pending, or uncertain, so recovery logic can avoid both duplicate responses and skipped interactions.
For an interrupted turn, blindly replaying it could confuse the caller, while silently skipping it could break the conversation.
I'm curious how you'd handle this in practice: would you prefer an idempotent turn-processing mechanism with explicit state tracking, or a confirmation-based recovery approach when the system cannot determine whether the last response was delivered?

Collapse
 
userxnom profile image
Abdullah Naseer •

You framed the trade-off exactly right, Tayyab — and I would take idempotent turn processing first, with confirmation as the fallback for the genuinely uncertain case. Give every turn a stable ID — call SID plus turn number — and record its lifecycle in Redis: received, processed, response delivered. Then a reconnected pod checks the ID before re-running the turn, so a side effect like a reschedule never applies twice. Confirmation only kicks in when the state itself is ambiguous, the turn was processed but the delivery flag never landed — then the agent briefly re-grounds the caller instead of guessing. Blind replay is the one I would rule out: a caller hearing the same confirmation twice loses trust faster than a caller asked one clarifying question. Have you hit a case in production where the Redis write and the socket close raced, so even the saved state was uncertain?

Thread Thread
 
tayyab_hafiz_dev_0 profile image
Tayyab Hafiz •

The distinction between processing a turn and successfully delivering its response is especially important here. I haven't confirmed a production race condition like this, but it's definitely a scenario worth designing for. Thanks for sharing this perspective!