Emre Şahin

Inseneripäevik

Real-time voice for connected devices

Architecture patterns for a voice AI backend serving connected devices: session layer, gRPC to AI services, async work, latency budgets and back-pressure.

Emre Şahin ·

A voice interaction with a connected device feels simple from the outside. Someone speaks, the device answers. Behind that is a chain of steps (capture, upload, speech-to-text, a language model, text-to-speech, download, playback), and each step is owned by a different component with its own failure modes. The user only experiences the sum of them.

This is not a description of any particular product. It is the set of patterns I reach for when designing this kind of backend, and the trade-offs I think are worth deciding on purpose rather than discovering in production.

Split the system by time scale

The most useful first cut is not by feature but by how fast each part has to respond:

device ──WebSocket──▶ session layer (.NET) ──gRPC──▶ AI audio services (Python)
                          │                              │
                          ├── Redis: presence, routing, short-lived state
                          └── RabbitMQ ──▶ workers: logging, analytics, notifications
                                         Hangfire: scheduled and retryable jobs
  • Interactive path, in seconds. Session layer and AI services. Everything here is on the user's clock.
  • Asynchronous path, seconds to minutes. Logging, analytics, content processing, notifications. Nobody is waiting for these to finish.
  • Scheduled path, minutes to days. Routines, reminders, clean-up, reconciliation.

The rule that follows is simple and worth enforcing in review: nothing on the interactive path waits on something from the slower paths. If writing an audit log or updating a statistic is in the request path, it becomes part of your latency, and part of your outage when that dependency is slow.

The session layer owns connections, not intelligence

Devices hold long-lived WebSocket connections. The session layer's job is narrow: authenticate the device, frame messages, buffer audio for the current utterance, route responses back, and handle reconnects. It should not contain business logic or model calls of its own.

A few patterns that hold up well:

  • Connection registry in Redis. When a device connects, record which instance holds its socket. Any instance can then deliver a message to any device by publishing to that instance's channel, without sticky sessions at the load balancer.
  • Connection identity, not just device identity. Devices reconnect, sometimes before the old socket is noticed as dead. If clean-up removes "the connection for device X", a stale disconnect can tear down the new one. Give each connection its own id and only remove a registry entry if the id matches.
  • Offline delivery as an explicit path. If a message targets a device that is not connected, put it in a store-and-forward queue and flush it on reconnect. Do not let "device offline" turn into a dropped message.
  • Accept the affinity you create. Buffering an utterance in memory on the instance holding the socket is fast and simple, but it ties that utterance to that instance. That is fine as long as it is a known decision: a reconnect mid-utterance restarts the utterance, and scaling in has to drain connections first.

gRPC to the AI services, and what it costs

The audio and model work tends to live in Python, because that is where the libraries are. The session layer talks to it over gRPC. That gives a typed contract, HTTP/2 multiplexing, and a clean boundary between two languages and two teams.

Two practices make that boundary hold:

  • One canonical proto. Keep the contract in one repository and copy it into the other with a sync script that has a --check mode in CI. Two hand-edited copies of a contract will diverge, and you will only find out at runtime.
  • Decide unary versus streaming deliberately. Unary calls with whole audio payloads are easy to build, test and retry, and they are a reasonable place to start. They also mean nothing downstream starts until the whole utterance has arrived, and payloads encoded as strings carry noticeable overhead. Streaming lets speech recognition start while the user is still talking and lets playback start before the full response has been synthesised. It is the larger latency win, and it costs more complexity in cancellation, partial failures and testing.

My default is to start unary with a clear contract, measure where the time goes, and move the slowest stage to streaming first, not everything at once.

Latency is a budget, not a hope

The single most useful artefact for this kind of system is a latency budget written down per stage. The exact numbers depend on product and hardware, so I will not invent them here. The structure matters more:

Stage Owner What eats the budget
Capture and upload device, network chunk size, network quality
Speech-to-text AI service, provider model, audio length, cold start
Language model AI service, provider prompt size, output length
Text-to-speech AI service, provider voice, output length
Download and playback session layer, device encoding, buffering

Two things follow from writing it down. First, every stage gets a timeout that is derived from the budget rather than from a library default. Second, cold starts become a visible line item. If an AI service scales to zero to save money, the first interaction after an idle period pays for it, and that should be a product decision, not a surprise.

Distributed tracing is what keeps the budget honest. With OpenTelemetry spans across the WebSocket handler, each gRPC call and the provider calls, "it felt slow" turns into "speech-to-text took most of the budget on this request". Prometheus metrics per stage, with percentiles rather than averages, show whether that was a one-off or a trend.

Back-pressure at every boundary

Interactive systems fail badly when they accept more work than they can finish. The user waits, retries, and the retry makes things worse. The patterns I apply:

  • One in-flight utterance per device. A new utterance cancels or rejects the previous one. Never queue speech behind speech.
  • Bounded buffers. Per-connection audio buffers have a size limit. Exceeding it ends the utterance with a clear error rather than growing memory until the instance dies.
  • Cancellation that propagates. If the device disconnects, the gRPC call and the provider request should be cancelled, not left to finish for nobody.
  • Shed load at the edge. When AI services are saturated, a fast "try again in a moment" is better than a slow timeout. The gateway can rate-limit per device before the request reaches anything expensive.
  • Async work is allowed to lag. Queues on the asynchronous path absorb bursts. Monitor their depth and age, and alert on age, not just size.

Observability that respects the data

Voice systems handle sensitive content. Logging every message at full fidelity is tempting during development and dangerous in production. I prefer structured logs of commands and metadata, with an explicit allow-list of message types that are logged and the ability to turn noisy types off at runtime. Log shipping goes over the message bus so it never blocks the interactive path. Audio and transcripts, if they are kept at all, follow a separate retention policy.

Summary

  • Split by time scale, and keep slow work off the interactive path.
  • Keep the session layer thin: connections, routing, buffering, reconnects.
  • One canonical contract between languages, checked in CI.
  • Write the latency budget down per stage and derive timeouts from it.
  • Put back-pressure at every boundary, and make cancellation flow end to end.

None of this is exotic. The difficulty is applying it consistently, because each shortcut looks harmless on its own and only shows up as latency once enough of them have accumulated.