Home / AI & GenAI

AI & GenAIHow-toAdvanced

Running LLM guardrails without doubling latency: parallel input checks, streamed output moderation and cancellation

Run input checks alongside generation, moderate streamed output in windows, cancel cleanly when a check fails, and choose fail-open or fail-closed per check.

Deepak Bhardwaj6 min read

Applies toPython 3.11+ asyncio, OpenAI Python SDK 1.x (AsyncOpenAI, works with Azure OpenAI and OpenAI-compatible servers); any HTTP guardrail service (Azure AI Content Safety, a self-hosted classifier)

A typical guardrail stack runs a prompt-injection classifier, a PII check and a topic check before the model, then a content check after. Run in sequence, that adds 300 to 900 ms before the first token and makes streaming pointless because the user waits for the full answer to be checked. You can cut most of that overhead by overlapping checks with generation, but only if you are precise about what is allowed to happen before a check returns.

The rule that makes parallelism safe

Speculative work is fine. Speculative side effects are not.

Work May start before input checks pass?
LLM generation into a server-side buffer Yes
Retrieval with the user's own permissions Yes
Streaming tokens to the user No (or only after a hold-back window, see below)
Tool calls that write anything No, never
Tool calls that read data the user can't already see No
Logging the prompt to long-term stores After PII redaction only

If an input check fails, you throw the buffered generation away and pay for some wasted tokens. That is the cost of the latency win, and it is usually small because most traffic passes.

Pattern 1: input checks in parallel with generation

import asyncio
from openai import AsyncOpenAI

client = AsyncOpenAI()  # or AsyncAzureOpenAI(...)

class Blocked(Exception): ...

async def check_injection(text):  # call your classifier; return True if safe
    ...
async def check_pii(text): ...
async def check_topic(text): ...

async def run_input_checks(text, timeout=1.5):
    checks = [check_injection(text), check_pii(text), check_topic(text)]
    results = await asyncio.wait_for(asyncio.gather(*checks), timeout)
    if not all(results):
        raise Blocked("input check failed")

async def generate_buffered(messages, queue):
    stream = await client.chat.completions.create(
        model="gpt-4o-mini", messages=messages, stream=True, max_tokens=800)
    try:
        async for chunk in stream:
            if chunk.choices and chunk.choices[0].delta.content:
                await queue.put(chunk.choices[0].delta.content)
    finally:
        await stream.close()          # release the HTTP connection on cancel
        await queue.put(None)

The orchestration: start both, hold output until the input checks return, then release the buffer and continue streaming.

async def answer(user_text, messages, send):
    queue: asyncio.Queue = asyncio.Queue()
    gen = asyncio.create_task(generate_buffered(messages, queue))
    try:
        await run_input_checks(user_text)
    except (Blocked, asyncio.TimeoutError):
        gen.cancel()
        await asyncio.gather(gen, return_exceptions=True)
        await send("I can't help with that request.")
        return
    while (tok := await queue.get()) is not None:   # checks passed: stream
        await send(tok)

What you gain: time to first token becomes max(check latency, model TTFT) instead of the sum. Model TTFT is often 300 to 800 ms, so a 400 ms check is nearly free.

Warning

Cancelling the asyncio task must close the upstream stream, or the provider keeps generating and billing until max_tokens. Check with your gateway logs that cancelled requests show short completions, not full-length ones.

Pattern 2: moderating streamed output in windows

Checking the whole answer at the end defeats streaming. Checking every token is too expensive and too noisy, because classifiers need context. The usual compromise is a hold-back window: keep the last N characters unreleased, check text in sentence-sized windows, and release text only once the window containing it has passed.

import re

SENTENCE_END = re.compile(r"[.!?\n]\s")

async def moderated_stream(queue, send, check_output, hold_chars=200):
    pending, checked_upto = "", 0
    while (tok := await queue.get()) is not None:
        pending += tok
        # check once we have a new sentence boundary past the hold-back window
        if len(pending) - checked_upto > hold_chars and SENTENCE_END.search(pending, checked_upto):
            window = pending[max(0, checked_upto - 200):]      # overlap for context
            if not await check_output(window):
                return await send("\n\n[Response stopped by content policy.]")
            release_to = len(pending) - hold_chars
            await send(pending[checked_upto:release_to])
            checked_upto = release_to
    if not await check_output(pending[max(0, checked_upto - 200):]):
        return await send("\n\n[Response stopped by content policy.]")
    await send(pending[checked_upto:])

Tuning notes:

  • Hold-back size trades latency for exposure. 150 to 300 characters is one or two sentences: the user sees steady streaming slightly behind the model.
  • Overlap matters. A harmful instruction split across two windows passes both checks if they don't overlap.
  • Check calls run concurrently with generation. If checks are slower than generation, the buffer grows; cap concurrent checks per stream at one and let windows grow instead of queueing.
  • Retraction is user-visible. Text already released can't be taken back. Decide per category whether a hold-back is enough (most content categories) or the full answer must be checked before release (regulated advice, anything quoting customer data).

Managed services take a similar approach. Azure OpenAI's content filtering has an asynchronous streaming mode that returns content before filtering completes and sends filter annotations afterwards; check whether that delay is acceptable for your categories before enabling it.

Pattern 3: tool calls wait, always

When the model returns a tool call, stop and run the checks that apply to it before execution: argument validation, authorisation for this user, and approval for write actions. These are on the critical path and should be. Make them fast instead (local schema validation, cached policy decisions), not parallel.

Fail-open or fail-closed, per check

A guardrail service that times out has to resolve one way or the other. Decide in advance and make it configuration:

Check On timeout or error Reason
Prompt injection on input with tools enabled Fail closed The cost of a miss is an action taken
Prompt injection, chat-only, no tools Fail open with logging The cost of a miss is a bad answer; availability matters more
PII redaction before logging Fail closed for logging, open for the answer Don't store unredacted data; still answer
Output harmful-content check Fail closed for public users, open for internal staff Exposure differs
Topic / scope check Fail open Low risk, high false-positive cost
POLICY = {"injection": "closed", "pii": "closed", "topic": "open"}

async def guarded(name, coro, timeout):
    try:
        return await asyncio.wait_for(coro, timeout)
    except Exception as e:
        log.warning("guardrail %s failed: %s", name, e)
        return POLICY[name] == "open"

Caution

A fail-open check that silently times out is a disabled check. Emit a metric for every timeout and alert when the rate rises, or an overloaded classifier quietly turns your guardrails off at peak load.

Measure it

Record per request: time to first token released to the user, each check's latency, whether it ran in parallel, how many tokens were generated and then discarded, and how many streams were stopped mid-answer. Compare TTFT before and after with real traffic, not a benchmark prompt.

AppDependencies
| where TimeGenerated > ago(1d) and Name startswith "guardrail."
| summarize p50=percentile(DurationMs, 50), p95=percentile(DurationMs, 95),
            failures=countif(Success == false) by Name

Prevent it next time

  • Give every guardrail a latency budget and a timeout, and track both as SLOs.
  • Keep classifiers close to the app (same region, warm replicas); network hops dominate small-model checks.
  • Test cancellation paths: a blocked input must produce no streamed text, no tool call and a short upstream completion.
  • Review fail-open/fail-closed choices when tools are added to an assistant; the right answer changes.