Mount Royal viewpoint by day
Montreal, QC
All projects

A real-time microservice to stream AI answers word by word

On this page

Waiting several seconds in front of a frozen screen feels long. Watching text write itself before your eyes, much less so. To integrate the OpenAI API into a survey platform, I built a real-time microservice that displays AI answers as they are being generated.

Context

I was working for a startup based in France, that builds a workplace well-being survey platform. The arrival of large language models (LLMs) in the mainstream opened up new possibilities. The technical team wanted to use them to help customers make the most of their survey results:

  • summarizing free-text comments, sometimes too many to read them all;
  • identifying trends in the results;
  • suggesting action plans based on those findings.

The problem

An LLM does not deliver its answer in one block: it generates it word by word, over several seconds. Waiting for the generation to finish before showing everything at once leaves users in front of a screen that does not move, with no idea whether anything is happening.

For the text to appear at the pace it is produced, the server and the browser needed a connection that stays open. Nothing in the existing architecture was designed for that: it called for a custom microservice, built from scratch.

The solution

A real-time microservice with Socket.io

I built and deployed a microservice that handles real-time data streams. It sits between the browser and the OpenAI API:

  1. the browser opens a Socket.io connection with the microservice and sends its request;
  2. the microservice calls the OpenAI API in streaming mode;
  3. each chunk of text it receives is relayed to the browser immediately;
  4. the React interface displays the chunks as they arrive.
Browser (React)
     ↑↓  Socket.io
Microservice
     ↑↓  stream
OpenAI API

Why a separate service

Isolating this feature in its own service has several advantages:

  • the long-lived real-time connections put no load on the main API;
  • the OpenAI API key stays on the server, never exposed to the browser;
  • the service can evolve (new model, new use cases) without touching the rest of the platform.

Results

  • AI answers appear word by word, in real time: users can see right away that the platform is working for them.
  • A foundation for the platform's AI features: this integration made it possible to tackle needs such as text summarization or file conversion.

Takeaways

  • Perception matters as much as speed. Generation is no faster, but waiting feels completely different when the text appears as it is written.
  • Real time is an architecture decision. Long-lived connections, reconnections, scaling: constraints that are easier to handle in a dedicated service.