A deep dive into VoxForge — building a self-hosted voice AI platform, wrestling with streaming pipelines, interruption handling, session consistency, and the many ways distributed systems can ruin your afternoon.

The demo was easy. Everything after that wasn't.

Building a voice AI demo sounds deceptively simple.

You take some audio, send it to a speech-to-text service, pass the transcript to an LLM, send the response to a text-to-speech provider, and play the audio back.

Congratulations. You have a voice assistant.

You also have approximately 47 problems waiting to introduce themselves.

What happens when the user starts speaking while the assistant is talking? What if the LLM is still generating a response when the user interrupts? What if Redis forgets something PostgreSQL remembers? What if the TTS provider breaks? What happens when a user reconnects halfway through a conversation?

And, perhaps most importantly, how do you stop your voice assistant from confidently talking over someone like that one person in every meeting?

These questions are what led me to build VoxForge.

VoxForge is aimed at being an open-source, self-hosted voice AI infrastructure platform. The goal is to provide the building blocks needed to run voice agents without treating the entire application as one giant API call with a microphone attached.

This article walks through the architecture, the engineering decisions, and some of the problems that make real-time voice systems considerably more interesting than the familiar Speech → LLM → Speech diagram suggests.

1. First, let's stop thinking of voice AI as a three-step pipeline

The classic voice architecture looks something like this:

Audio → Speech-to-Text → LLM → Text-to-Speech → Audio

Beautiful. Clean. Fits perfectly in a presentation.

Unfortunately, real users don't behave like diagrams.

They interrupt. They pause. They change their minds. They disconnect. They ask follow-up questions. Sometimes they say absolutely nothing for ten seconds and then expect the assistant to know what happened.

A production-oriented voice system needs to handle several things simultaneously:

The key architectural decision was to avoid making these responsibilities inseparable.

VoxForge uses a modular architecture with a shared voice pipeline behind multiple transport adapters.

At a high level:

CLIENT
                    |
          +---------+---------+
          |                   |
       WebSocket            LiveKit
          |                   |
          +---------+---------+
                    |
             Voice Gateway
                    |
           VoicePipelineService
                    |
       +------------+------------+
       |            |            |
      STT      Conversation     TTS
                   Engine
                    |
              Agent Runtime
                    |
          +---------+---------+
          |         |         |
         LLM       Tools      RAG
          |         |         |
          +---------+---------+
                    |
             Session Manager
                    |
             PostgreSQL
                    |
                  Redis

The important idea is that WebSocket and LiveKit are different ways of getting audio into the system. They shouldn't each need their own implementation of the entire voice pipeline.

One pipeline. Multiple ways to talk to it.

This also makes it easier to test the core execution flow without having to bring an entire WebRTC stack to every test.

Small architectural decisions like this save a surprising amount of pain later.

2. The audio transport layer: where the fun begins

VoxForge supports WebSocket-based audio streaming and LiveKit as a WebRTC transport.

For the WebSocket path, the client streams binary PCM audio:

The gateway handles incoming audio frames and forwards them into the voice pipeline.

There are also control messages for operations such as:

Why separate control messages from audio?

Because audio is data, while interruption is an instruction.

You don't want an important control operation to get lost in a pile of audio frames. Nor do you want the system to treat every incoming message as if it were another piece of speech.

Backpressure: because the internet is not your intern

Audio arrives continuously. Downstream services don't necessarily process it at the same speed.

If incoming frames accumulate faster than they can be consumed, queues grow. Memory usage increases. Latency gets worse.

Eventually, your supposedly real-time assistant starts responding to something the user said several seconds ago.

Not ideal.

VoxForge uses bounded queues for audio ingestion. The WebSocket and LiveKit paths use a 256-frame queue, with the oldest frame dropped when the queue exceeds capacity.

This is a deliberate trade-off: under overload, preserving real-time responsiveness can matter more than retaining every frame.

Of course, dropping audio isn't free. It can affect transcription quality. But allowing an unbounded queue to grow indefinitely is not a particularly brilliant alternative either.

The broader lesson: real-time systems need explicit overload behaviour.

Hope is not a backpressure strategy.

3. VoicePipelineService: the traffic controller

The central component of the architecture is VoicePipelineService.

It coordinates the actual voice interaction:

  1. Receive audio from the transport.
  2. Forward audio to the streaming STT provider.
  3. Receive partial and final transcripts.
  4. Start conversation processing when a final transcript arrives.
  5. Stream generated text back to the client.
  6. Send generated speech through TTS.
  7. Persist the resulting conversation data and metrics.
  8. Handle interruption and session lifecycle events.

One important detail: transcription doesn't have to stop just because the assistant is generating a response.

The STT connection remains active while a turn is being processed. This allows the system to detect when the user starts speaking again.

That matters because a voice assistant shouldn't behave like a command-line program that refuses to listen until it has finished printing.

The pipeline coordinates several asynchronous activities, which makes cancellation, state transitions, and resource cleanup particularly important.

A failed task shouldn't leave a WebSocket hanging around forever. A cancelled generation shouldn't continue consuming provider resources. A completed turn shouldn't accidentally overwrite the state of the next one.

The pipeline is not just connecting APIs. It is coordinating the lifecycle of a conversation.

4. Conversation orchestration: one brain, multiple ways to think

Once STT produces a final transcript, the conversation engine takes over.

VoxForge uses a ResponseGenerator abstraction to separate conversation execution from the rest of the voice pipeline.

This is useful because not every voice agent needs the same level of intelligence.

Some agents need a straightforward LLM response.

Others need to plan, call tools, inspect results, and decide what to do next.

For the simpler path, the conversation engine maintains session history and streams responses using the OpenAI Chat Completions API.

For more involved workflows, VoxForge supports a LangGraph-based orchestration path.

The multi-agent workflow is structured around:

Planner
   |
Safety
   |
Executor
   |
Critic
   |
Coordinator

The idea is to separate responsibilities rather than stuffing every decision into one enormous prompt.

The planner determines what needs to happen. The safety layer checks the proposed execution. The executor performs the work. The critic evaluates the result. The coordinator manages the overall flow.

Does every chatbot need five agents to answer "What time is it?"

Absolutely not.

Sometimes a simple function call is enough. The architecture should support complexity when it is justified, not introduce complexity as a personality trait.

5. Tool execution: giving the assistant hands

An LLM that can only generate text is useful.

An LLM that can interact with external systems can do considerably more.

VoxForge supports built-in tools and Model Context Protocol (MCP) integrations.

MCP provides a standard way to connect external tools and resources to an agent. Instead of hardcoding every possible integration into the conversation engine, the runtime can discover available tools and make them available to the agent.

The general flow looks like this:

User Request
     |
Agent / Planner
     |
Tool Discovery
     |
Tool Selection
     |
Tool Execution
     |
Result Returned
     |
Agent Continues

This separation matters.

The conversation engine should not need to know the implementation details of every external service. It should understand the tool interface and let the runtime handle execution.

There are still important engineering concerns here:

Giving an LLM tools is a little like giving a toddler access to a company credit card. You need permissions, boundaries, validation, and a way to recover when things go sideways.

6. RAG: making sure the assistant doesn't confidently invent company policy

Voice agents are often expected to answer questions about company-specific information.

A general-purpose LLM doesn't automatically know your internal documentation, product catalogues, or operational procedures.

That's where retrieval-augmented generation comes in.

VoxForge includes a knowledge ingestion and retrieval workflow built around PostgreSQL and pgvector.

At a high level:

Documents
    |
Ingestion
    |
Parsing & Chunking
    |
Embeddings
    |
PostgreSQL + pgvector
    |
Similarity Retrieval
    |
Context Assembly
    |
LLM Response

The ingestion pipeline prepares documents, splits them into chunks, generates embeddings, and stores them for retrieval.

When a user asks a question, the system retrieves relevant context and supplies it to the model.

The objective isn't simply to retrieve something vaguely related.

It's to retrieve useful evidence that can ground the response.

This is particularly important for voice applications. A hallucinated answer in a text chatbot is annoying. A voice assistant confidently giving someone the wrong operational instruction can be considerably worse.

VoxForge also supports citation grounding so that answers can be connected to their retrieved sources.

Retrieval quality, chunking strategy, document versioning, and context selection are all areas where seemingly small decisions can have a significant effect on the final response.

RAG is not a magic "make the LLM know things" button. Sadly.

7. Barge-in: teaching the assistant when to shut up

This is one of my favourite problems in voice infrastructure.

Imagine this:

You ask an assistant for directions.

It starts responding.

After two seconds, you realise you gave it the wrong destination.

You say, "Wait, no. I meant the airport."

A good voice assistant should stop talking immediately and listen.

A bad one will continue reading its beautifully generated answer while you attempt to negotiate with it.

This behaviour is called barge-in.

Implementing it properly is not just a matter of stopping audio playback.

There are multiple things happening at once:

Stopping one component doesn't automatically stop the others.

VoxForge uses an interruption flow that propagates the interrupt signal through the system.

User Starts Speaking
        |
    Client Detects
        |
    Gateway Receives
        |
 Redis Interrupt Flag
        |
   Cancel Generation
        |
    Stop TTS Output
        |
 Persist Partial Response
        |
  Session → LISTENING
        |
   Acknowledge Client

The interrupt signal is recorded in Redis, and the LLM and TTS execution paths cooperatively stop their work.

The system also persists the partial assistant response where appropriate and returns the session to the listening state.

The interesting part is that interruption is really a coordination problem.

You have to make sure that old work doesn't continue interfering with new work.

This is why cancellation needs to be propagated, not merely requested.

A user shouldn't have to wait for an AI to finish its monologue before being allowed to correct it.

8. Session consistency: PostgreSQL and Redis are not twins

Voice applications are stateful.

A conversation has a session ID, messages, sequence information, lifecycle state, and potentially an ongoing operation.

VoxForge uses two different storage systems for different responsibilities:

PostgreSQLRedisPersistent sessionsEphemeral session stateMessagesCurrent phaseDurable metadataSequence informationSession statusInterrupt flagsHistorical recordsHeartbeats

PostgreSQL is the durable source of truth.

Redis stores ephemeral operational state that needs to be accessed quickly.

This sounds straightforward until you remember that these are two independent systems.

They do not share a magical transaction that makes every operation atomic.

Consider session creation:

  1. Insert the session into PostgreSQL.
  2. Write the initial state into Redis.
  3. If the Redis operation fails, mark the session as failed and raise a SessionStateError.

Session termination follows a slightly different strategy.

  1. Mark the session completed in PostgreSQL.
  2. Attempt to delete the Redis state.
  3. If Redis cleanup fails, log the failure and emit a metric.

The durable operation should not fail merely because ephemeral cleanup had a problem.

This is an important distinction.

The system doesn't pretend that a distributed transaction exists when it doesn't. Instead, it uses compensating actions and reconciliation.

If Redis state is missing during a resume, activation, or handoff operation, the session manager can rebuild ephemeral state using PostgreSQL metadata and session status.

There is a limitation worth acknowledging: reconciliation can restore durable session information, but in-flight details such as the latest sequence or interrupt state may be lost unless the client supplies its last known sequence.

This is not a fully distributed transaction system. It is a deliberate approach to handling consistency between durable and ephemeral state.

And honestly, being explicit about what can go wrong is more useful than drawing two database icons connected by a happy green arrow.

9. Streaming TTS: don't make the user wait for the entire essay

A naive implementation waits for the LLM to finish generating the complete response before sending anything to TTS.

That works.

It also makes the interaction feel unnecessarily slow.

VoxForge streams LLM output and uses sentence-boundary buffering before sending text to the TTS provider.

Why sentence boundaries?

Sending every individual token to TTS is impractical. Sending the entire response at once defeats the purpose of streaming.

Sentence-level buffering provides a useful compromise.

LLM Token Stream
       |
Text Buffer
       |
Sentence Boundary
       |
TTS Request
       |
Audio Chunks
       |
Client Playback

The TTS path uses Cartesia and produces 24 kHz signed 16-bit little-endian PCM audio.

The pipeline can stream generated text to the client while speech synthesis is happening.

This creates a more responsive experience without requiring the entire response to be generated before playback begins.

There is a trade-off, of course.

Shorter buffers can improve responsiveness but may create more frequent synthesis requests. Larger buffers can improve batching but increase perceived latency.

As usual, there is no free lunch. Only different ways to pay for it.

10. Observability: because "it sounded weird" is not a debugging strategy

Voice applications have a particularly annoying debugging problem.

When a normal API request fails, you can often inspect the request, response, status code, and logs.

When a voice interaction goes wrong, the problem could be anywhere:

A single request duration doesn't tell you much.

VoxForge instruments the voice pipeline using OpenTelemetry and Prometheus.

The system tracks important stages of a conversation, including:

The tracing model includes spans such as:

voice.session
    |
    +-- stt.transcribe
    |
    +-- llm.generate
    |
    +-- tts.synthesize

This gives us a way to understand where time is being spent instead of staring at a single latency number and hoping it explains itself.

VoxForge also persists turn-level information so that conversations can be inspected and replayed.

That matters because debugging a voice agent shouldn't require recreating the exact sequence of events from memory.

A session replay is much more useful than someone reporting:

"Yeah, it was working yesterday. Today it just sounds... different."

11. Evaluation: a working demo is not proof of a good agent

A voice agent can successfully complete a conversation and still be terrible.

It might take too long to respond. It might call the wrong tool. It might fail to complete the user's task. It might generate an answer that sounds fluent but is factually incorrect.

So what does "working" actually mean?

VoxForge includes a per-turn evaluation engine that assesses conversations across dimensions such as:

The evaluation system uses heuristic and threshold-based scoring to classify results into statuses such as passed, warning, and failed.

The current implementation is a useful foundation for measuring agent behaviour.

It is important to distinguish this from a fully autonomous quality evaluator or a proven deployment gate. More advanced evaluation — including LLM-as-judge hallucination detection, speech-quality scoring, golden datasets, and CI regression gates — remains an area for further development.

The larger principle is simple:

You cannot improve what you cannot measure.

And you definitely cannot call something production-ready just because it worked three times during a demo.

12. Human handoff: sometimes the best AI response is "let me get someone"

Not every problem should be solved by an LLM.

Sometimes the agent reaches a point where it needs human assistance.

VoxForge includes a human handoff capability so that a conversation can be escalated instead of forcing the model to improvise its way through an unsupported situation.

This is particularly important in enterprise workflows.

A voice agent should know when it has reached the limits of its authority, context, or capabilities.

The objective isn't to eliminate humans from every workflow.

It's to make the interaction useful enough that humans can spend their time on the problems that actually need them.

13. Why a modular monolith instead of microservices?

Because I enjoy engineering. I don't particularly enjoy debugging distributed networking problems that I invented myself.

VoxForge is organised as a modular application with clear boundaries between responsibilities.

That provides separation between:

But these boundaries don't automatically require separate deployments.

A modular monolith offers a useful balance:

Microservices are useful when organisational or scaling requirements justify them.

They are not a mandatory achievement badge for backend engineers.

I would rather have a well-structured system with clear boundaries than twelve services communicating through a distributed network of YAML files and prayers.

14. Deployment and operational foundations

VoxForge is designed to be self-hosted.

The deployment setup includes:

The project also includes mock providers for local development, allowing developers to explore the core workflows without configuring every external API key immediately.

This matters because onboarding shouldn't begin with a scavenger hunt for six provider credentials.

The goal is to make the platform approachable to developers who want to run, inspect, and extend their own voice infrastructure.

15. Some engineering decisions and their trade-offs

A few decisions are worth summarising.

DecisionWhyTrade-offShared VoicePipelineServiceConsistent behaviour across transportsRequires careful transport abstractionBounded audio queuesProtects the system from unbounded backlogAudio frames may be dropped under overloadPostgreSQL + RedisDurable records with fast ephemeral stateRequires reconciliationCooperative cancellationStops obsolete LLM and TTS workEvery execution path must respect cancellationSentence-based TTS bufferingBalances streaming responsiveness and batchingBuffering affects first-audio latencyModular monolithClear boundaries without distributed overheadRequires discipline around module boundariesPer-turn evaluationMakes quality and performance inspectableCurrent heuristic scoring has limitations

There isn't one universally correct architecture.

Every decision is a trade-off between latency, reliability, complexity, cost, and maintainability.

The important part is understanding which trade-off you're making.

16. What's next?

VoxForge is an evolving project, and there is plenty more to improve.

Some of the areas I want to push further include:

The interesting work is not just getting a model to speak.

It's making sure the entire system behaves predictably when networks fail, providers slow down, users interrupt, and state gets out of sync.

That's where infrastructure engineering starts getting interesting.

Final thoughts

Building VoxForge has been a useful reminder that AI engineering is not just about models and prompts.

A voice agent is a distributed system with audio attached.

It has concurrency, state management, external dependencies, failure modes, latency budgets, and all the other wonderful things that make backend engineering exciting.

The LLM is only one component.

The engineering challenge is everything around it.

And if there's one thing I've learned from building this, it's that making an AI talk is easy.

Making it listen, stop talking, remember what happened, recover when things fail, and explain what went wrong?

That's the actual project.

Explore VoxForge

Built, broken, debugged, and built again.