Multi-brand in-app AI chat backend and quality judge

Client system Published Oct 7, 2026 Reviewed Nov 21, 2026

A queue-backed chat backend powering in-app AI assistants across several subscription apps: batching message bursts, handling mid-reply interruptions, pacing multi-part delivery and auditing every thread with an LLM judge.

At a glance

Problem
A consumer subscription business running multiple apps wanted an in-app AI assistant customized per brand without duplicating backend infrastructure for every app team.
Constraint
Real mobile users send rapid bursts and keep typing mid-reply, while each brand needed isolated API keys, product knowledge and support contacts on one shared deployment.
System built
A Fastify and BullMQ service using Redis batch windows to collapse bursts, scheduled Postgres rows for multi-part webhook delivery, API-key tenant isolation, and an automated 4-hour LLM judge pipeline.
Outcome
A no-code prototype became a production backend in two weeks and scaled across multiple brands from one deployment. Hard-rule breaches reached the team's chat channel every four hours.

Overview

A consumer subscription company operates several apps under separate brands and wanted an always-on chat assistant inside each one, grounded in what that brand offers.

The first proof of concept went live in May 2025 as an n8n workflow pairing an agent node with Postgres chat memory. Within a week I rewrote it as a dedicated service, first in Node.js and then in TypeScript with Fastify, Drizzle on Postgres and BullMQ on Redis. That TypeScript backend reached production in early June 2025.

Client apps integrate over a small REST surface: create a chat, post a message, fetch messages. Replies run through OpenAI or Anthropic via the Vercel AI SDK, selectable per chat. Every model response must fit { messages: string[] }, turning one answer into natural short bubbles instead of a wall of text. Transient network failures, rate limits, 5xx errors and malformed responses retry up to 5 times with exponential backoff and jitter capped at 30 seconds; all other failures fail fast.

Alongside the API, I built an internal dashboard displaying full conversations, brand configurations, engagement charts and an error queue of every thread flagged by the quality judge.

Bursts, batch windows and interruptions

Mobile users rarely compose one complete paragraph. They fire off three or four short messages in seconds. A naive request-response handler answers each one independently, spamming overlapping and contradictory replies.

An initial fix buffered bursts in process memory, then moved into Redis days later so pending bursts survived restarts. Each chat uses a batch window: the first incoming message schedules a delayed BullMQ job and sets a window TTL key. Subsequent messages arriving inside that window fold into the same job, refreshing its delay. When the timer fires, a worker sends the full burst alongside recent history in one model call.

The trickier edge case was a user sending another message while the previous multi-part reply was still trickling out. Without interruption handling, remaining parts of the stale answer kept arriving after the user's new question, and fast bursts still caused duplicate replies.

The solution treats any new user message as an explicit interruption. Before opening a new batch, the service deletes any not-yet-visible assistant rows, cancels their queued webhook jobs, removes pending batch jobs and clears the window key. The incoming burst receives a 1-second window so the updated answer feels responsive. A short per-chat Redis lock guards window bookkeeping against simultaneous requests, closing the duplicate-reply bug.

Delivery as data

A three-part reply writes three rows into the messages table, each stamped with a scheduled_for time spaced by text length plus a short pause. Every read endpoint filters out rows scheduled in the future. The worker commits all rows first, then enqueues one delivery webhook per part.

Treating the database as the delivery source of truth pays off twice. If the client app's webhook endpoint is down, the job still succeeds because the messages are safely persisted and appear on the next chat fetch; failed callbacks attempt a status event without failing the pipeline. Interruption also becomes trivial: canceling undelivered bubbles is a single DELETE on future-dated rows, with nothing to retract from the client.

Model inference and webhook delivery live on separate queues with independent retry budgets, so retrying a flaky webhook never triggers a duplicate LLM call.

One service, several brands

In July 2025 the backend became multi-tenant. Every brand lives as a project row holding its API keys, support email, product summary, subscription terms and knowledge base. Incoming bearer tokens resolve the tenant automatically and scope every chat and message query to it.

Each system prompt assembles from four layers: the chat's base prompt, a shared rules template populated with brand metadata and knowledge, flattened Key: value lines from per-user onboarding JSON, and the current date. Onboarding a new brand requires a database row and an API key, with zero code changes.

A judge that reads every conversation

To catch bad outputs after launch, I built an offline auditing loop in n8n.

Auditing operates on threads: distinct bursts of activity inside long-lived chats. A single Postgres gaps-and-islands window query segments threads whenever an hour or more passes between messages.

WITH ordered AS (
  SELECT chat_id, message_type, created_at,
         lag(created_at) OVER (PARTITION BY chat_id ORDER BY created_at) AS prev_ts
  FROM messages
),
marked AS (
  SELECT *, CASE WHEN prev_ts IS NULL
                   OR created_at - prev_ts >= interval '1 hour'
                 THEN 1 ELSE 0 END AS is_new_thread
  FROM ordered
)
SELECT chat_id,
       sum(is_new_thread) OVER (PARTITION BY chat_id ORDER BY created_at
                                ROWS UNBOUNDED PRECEDING) AS thread_no,
       created_at
FROM marked;

Simplified: the production query then aggregates start, end, duration and message counts per thread.

That same thread table powers dashboard engagement metrics: activity by hour and weekday, session duration distributions and retention.

Every 4 hours, a job selects unreviewed threads from the past 3 days, serializes each as escaped XML and sends it to an LLM judge returning a 13-field JSON verdict. The judge scores topics, sentiment, rule warnings, hard rule errors, jailbreak attempts, out-of-scope asks, requests needing human support, and empty or refusal replies. System messages are stripped before review. Any thread with a hard rule error posts straight to the team's chat channel with a deep link into the admin console.

Prompt rules evolved continuously from those alerts, banning phone numbers and replacing specific product names with verifiable criteria. In early 2026 an older English-only rule was replaced so the assistant responds in the user's own language.

Limitations

  • In the TypeScript deployment, the HTTP API, AI worker and webhook worker share one Node.js process, so an unhandled crash hits all three. A subsequent Go rewrite separated them into independent services.
  • Chats bind to one model provider with no automatic failover during provider outages.
  • Webhook delivery stops after 3 attempts with no dead-letter queue; missed callbacks rely on client polling.
  • Workers pass up to 300 recent messages per turn with no summarization, raising latency and token spend in long threads.
  • Live moderation uses keyword patterns that only extend the batch window; substantive safety enforcement remains inside the prompt.
  • Per-chat Redis locks are advisory: a competing request waits 100 ms and continues, leaving heavy bursts able to race the window.
  • Quality judging runs post-delivery with no pre-release golden dataset, meaning prompt edits are evaluated only after touching live users.

Related case studies

Bring one real problem

One hour, €80. You leave with a written plan for what belongs in AI, what belongs in code, and what a first release takes, whether we work together or not.