Queues, scaling and streaming

Step 11 of 14. Keep Store Assist steady through bursts with queues, balanced instances and streamed answers, and plan recovery before you need it.

Queues, scaling and streaming in 60 seconds

  • Two paths: interactive questions get an immediate answer path, while slower work goes through a queue with a job record.
  • Backpressure: a queue absorbs bursts but not unlimited work. Cap it, prioritise it and watch the age of the oldest job.
  • Scaling: keep services stateless, scale on in-flight work and queue age, not CPU alone, and remember that provider quotas cap everything.
  • Availability: write down RTO and RPO per path. Redundancy only counts if dependencies are redundant too.
  • Streaming: send text as it is produced, measure four kinds of latency separately, cancel work nobody is waiting for, and never present a partial answer as a finished one.

The problem it solves

Averages hide the moments that hurt. Store Assist sees 1 request a second over a trading day, but at 08:00, when a point-of-sale outage hits a region, thousands of colleagues ask the same question within minutes. Servers, provider quotas and connection pools can all be overrun by a burst that looks tiny on a daily chart.

Three tools help. Queues smooth work that can wait. Balancing and scaling add capacity where it helps. Streaming shortens the felt wait for work that cannot wait. They solve different problems, and mixing them up causes surprises.

Queues and the two paths

A message queue stores tasks until a worker is free. It evens out the gap between how fast tasks come in and how fast the system can safely get through them. Store Assist queues work that nobody is staring at:

  • Re-indexing manuals when a procedure changes.
  • Condensing lengthy incident write-ups.
  • Handling supplier manual uploads.
  • Offline evaluation runs.
  • Notifications after an incident is raised.

A queue is the wrong tool for an ordinary question. A colleague at a till expects an answer now, and pushing that request through a slow background flow makes things worse. So the design has two paths, chosen by how long the person can wait.

Interactive questions go straight through, while slower jobs wait on a queue and report progress through a job record.
  • Interactive path: the colleague asks, Store Assist retrieves, calls the model and streams or returns the answer in seconds.
  • Background path: the system accepts a job, stores its status as queued, puts it on a queue, and returns a job identifier. A worker takes it later. The colleague can check status or receive a notification.

Never report a job as finished until the worker has finished it. The status moves from queued to running to completed or failed, and each change is written by the worker.

Backpressure and resilient processing

A queue can soak up a surge, but it cannot conjure capacity. If tasks arrive faster than workers clear them, waits grow until a limit is hit. Backpressure means deliberately declining extra work. Useful controls:

  • A cap on queued jobs per store. For Store Assist, 20 is a reasonable start.
  • More workers, up to a defined ceiling.
  • Pausing low-priority work for a while.
  • A clear "try again shortly" reply instead of a silent delay.
  • Quotas for expensive jobs, such as large uploads.

Use a priority queue with a few classes. During the 08:00 outage, incident follow-ups and notifications outrank re-indexing, and nightly evaluation can wait until the evening. A sensible set is priority 0 for incident work, 1 for notifications, 2 for re-indexing and 3 for evaluation and batch jobs.

Watch the age of the oldest message as well as the depth. A long queue of fresh jobs can be healthy in a burst. A short queue whose oldest job is an hour old signals stuck workers. Alert on age by class, for example priority 1 older than 2 minutes, priority 2 older than 15 minutes, priority 3 older than 2 hours.

Most queues deliver at least once. A worker can see the same message twice, or crash halfway through. Make jobs safe to repeat:

  • Give every job a stable identifier. Indexing a document version twice must not create duplicate chunks, so the identifier is the document and its version.
  • Retry a bounded number of times for transient faults, with growing delays.
  • After 5 failed attempts, move the message to a dead-letter queue, where people can inspect it without blocking healthy work.
  • Separate temporary problems, such as a provider overload, from permanent ones, such as a corrupted file. Retrying a permanent fault forever only wastes money.

Remember what a queue does not do. It improves burst handling and decouples producers from workers. It does not make any single request faster.

Load balancing and autoscaling

A load balancer spreads requests over several application instances and stops sending to any that fail health checks. Behind it sit interchangeable API instances, a shared database and state store, separate workers for queued jobs, and central logs, metrics and traces. Statelessness makes instances easy to replace, so conversation state and job status live in shared stores, never only in one instance's memory.

Autoscaling adds or removes instances based on signals. The signals worth considering are CPU, memory, requests a second, in-flight requests, latency, queue depth and age, and the number of active jobs. For an AI service, CPU alone misleads. An API instance may spend nearly all its time waiting on a model, so CPU looks idle while it holds as many open requests as it can manage.

Scale on concurrency. If each instance handles 20 in-flight requests comfortably, and the agent flow produces 70 in flight at peak, you need at least 4 instances. Target about 60% utilisation, which means scaling out when the average passes 12 in flight per instance.

Autoscaling is slow. A new instance may take 90 seconds to start and warm its connections, and the 08:00 spike does not wait. Combine reactive scaling with a schedule that raises the floor before 07:45 on trading days, and keep a small pool of warm spare instances.

Application capacity versus model capacity

More application servers do not mean more answered questions. A provider limits requests a minute, tokens a minute, concurrent calls and spend per account. Scale past those and the extra instances simply collect more rejections. Capacity is a stack of layers, each with its own metric, alerts and failure behaviour:

Capacity is a stack of layers, and the narrowest one sets the real limit.

The layers are application servers (in-flight requests), database and retrieval (query rate), queues and workers (job age), provider quotas (requests and tokens a minute) and spending limits (pounds a day).

Do not scale everything together. A cheap API call may trigger a costly model call, while a re-indexing job may burn processor and embedding capacity with almost no public connections. In a single shared pool, one starves the other. Give them separate pools once their profiles, priorities or scaling needs differ enough to repay the extra moving parts. Small deployments can stay together until measurements show interference.

High availability, RTO and RPO

High availability is about making sure no single fault stops the whole service. Store Assist might run instances in three zones, use a managed database with replicas, and use health checks to remove sick instances. At 20 in-flight requests each, 2 instances per zone gives 120 capacity. If a whole zone is lost, 4 instances remain with 80 capacity, still above the 70 needed at peak.

Redundancy only counts if every dependency is also redundant. Three healthy API instances are useless if they all rely on one database or one network route. For each important path, write down two targets: how quickly service must return (recovery time objective, RTO) and how much recent data you can afford to lose (recovery point objective, RPO).

PathRTORPOWhat it implies
Procedure answers1 hourIndex: 24 hoursDaily index snapshots are enough. A restore in under an hour is acceptable.
Refund and incident paths15 minutesZeroSynchronous replication, tested failover and no reliance on a single zone.
Background jobsHoursRe-queue from sourceJobs can be replayed, so durable messages and idempotent workers are enough.

Business impact sets these numbers, not the number of servers on a diagram. A manual lookup service and a refund workflow rightly have different targets.

Streaming responses

Colleagues do not need to wait for a complete answer before seeing anything. Models produce text piece by piece, and streaming forwards those pieces as they appear. It makes a 6 second answer feel much quicker. A common choice is Server-Sent Events, a standard way for a server to push a stream of events over ordinary HTTP. The sequence is:

  • The colleague sends a question.
  • Store Assist authenticates the request and validates it.
  • Retrieval and the model workflow start.
  • The server sends an opening event, or begins streaming text straight away.
  • The model produces text, and the server passes on only what output checks allow.
  • A final "done" event closes the stream, or a clearly marked error event does.

Measure latency in four ways, because one number hides too much:

MeasureQuestion it answersStore Assist example
Time to first byteWhen does anything arrive?0.3 seconds
Time to first tokenWhen does the first useful text appear?1.2 seconds, against a p95 target under 1.5
Inter-token delayHow smoothly does the text flow?About 19 milliseconds for 250 tokens
Time to completionWhen is the whole answer ready?6.0 seconds, against a p95 target under 8
A stream timeline separates first byte, first token, token spacing and completion.

An application with a fast first token can still finish slowly. Another can do long retrieval before it says anything, so the first token is slow even though the total time is fine. Set targets for each, based on the experience you need.

When streams go wrong, and choosing the protocol

Streaming adds real engineering concerns:

  • Disconnects. A colleague may close the app or ask something new. Propagate the cancellation from the browser to the gateway to the provider call, and check it works. If 5% of streams are abandoned halfway, cancelling saves about 225,000 output tokens a day at the Store Assist volume. The money is small, but the freed capacity matters in a burst.
  • Partial failures. If a provider fails after three sentences, send a clear error event. The interface must show the answer as incomplete, and the system must neither cache it nor record it as a success.
  • Tools while streaming. Mark text as status or as result. Store Assist may stream "checking stock now", but must wait for the inventory service before it states a count.
  • Long silences. For flows of 7 seconds or more, send a heartbeat comment every 15 seconds, so proxies do not close an apparently idle connection. Turn off response buffering on every proxy in the path.
  • Reconnects. Give events identifiers, keep a short buffer of 60 seconds, and let a client resume from the last identifier it saw.

Pick the protocol for the job. Streaming suits conversations and long explanations where instant feedback matters. For server-to-client text, Server-Sent Events is simple and works through most infrastructure. For two-way audio or live collaboration, WebSockets fit better. A job that takes minutes is better as a stored job record with progress updates, which the client can poll, subscribe to, or hear about through a notification. Whatever you choose, make it obvious whether the output is partial or complete.

Store Assist, worked through

At 08:00 a regional point-of-sale outage lands. About 4,000 colleagues ask a similar question within 5 minutes, which is 13.3 requests a second, above the 10 a second planning peak. The scheduled scale-out has already lifted the floor to 6 instances. The in-flight number heads towards 33 for plain questions, well inside 120 capacity. The queue pauses re-indexing and evaluation, and priority 0 and 1 jobs continue. Queue age alerts stay quiet because only priority 2 and 3 work is waiting, and its limits are generous.

Streaming makes the burst bearable: text starts at about 1.2 seconds even though completion takes 6. When the scanner sync guide changes on Monday, a change event creates an indexing job keyed by document and version, so a duplicate event changes nothing.

Streaming endpoint with cancellation and heartbeat (illustrative) (python)
import asyncio, time

HEARTBEAT_S = 15          # idle comment interval so proxies keep the stream open
MAX_STREAM_S = 30         # hard ceiling for any one stream
BUFFER_S = 60             # how long events stay available for resume

async def stream_answer(request, gateway, outbox):
    deadline = time.time() + MAX_STREAM_S
    call = gateway.start_stream(request.messages, deadline=deadline)  # placeholder
    last_sent = time.time()
    seq = 0
    try:
        async for piece in call:
            if await request.is_disconnected():
                call.cancel()                 # stop paying for text nobody will read
                return
            seq += 1
            await outbox.send(event="text", id=seq, data=piece)
            last_sent = time.time()
            if time.time() > deadline:
                raise TimeoutError
        await outbox.send(event="done", id=seq + 1, data="complete")
    except Exception:
        call.cancel()
        # Mark clearly as incomplete. Never cache or log as a success.
        await outbox.send(event="error", id=seq + 1, data="incomplete")

async def heartbeat(outbox, state):
    while not state.finished:
        await asyncio.sleep(HEARTBEAT_S)
        if time.time() - state.last_sent >= HEARTBEAT_S:
            await outbox.send_comment("keep-alive")   # comment line, not content

The gateway, request and outbox objects are placeholders. The limits are explicit: 15 second heartbeat, 30 second ceiling and a 60 second resume buffer.

Design decisions

  • Path split: list every request type and assign it to the interactive or background path, with a reason.
  • Queue classes: define priorities, per-store caps and age alert thresholds.
  • Scaling signal: use in-flight requests per instance, with a schedule for known peaks.
  • Pool separation: put indexing, evaluation and interactive serving in separate pools once measurements justify it.
  • Zone layout: at least three zones, sized so that losing one still carries peak.
  • Recovery targets: write RTO and RPO per path and test them with an exercise.
  • Stream contract: fix the event types, identifiers, heartbeat and error format, and version them.

Measuring it

  • Latency split: first byte, first token, inter-token delay and completion, at the median and 95th percentile, by route.
  • Effect of load on quality: check that answer quality does not drop when capacity is tight and shorter contexts or cheaper routes kick in.
  • Abandonment: the share of streams cancelled, and at which point, which shows when answers feel too slow.
  • Partial answer rate: streams ending in an error, and whether those answers were wrongly stored.
  • Queue health: age of the oldest job by class, and the dead-letter volume.

When to use it, and how much of it

SituationWhat to useWhy
A question someone is waiting onInteractive path with streamingPeople notice delays above a second or two.
Work that can take minutesQueue, job record and notificationDecouples effort from the colleague's screen.
Known daily peakScheduled scale-out plus warm sparesReactive scaling is too slow for 08:00.
Two-way voice or live useWebSockets or a realtime channelServer push alone cannot carry both directions.
Small pilotOne shared pool and simple streamingSplit pools on evidence.

Trade-offs

DimensionEffectWhat to do about it
Feel of speedStreaming makes answers feel faster without changing total time.Still measure completion time, and keep answers concise.
CostSpare capacity and extra zones cost money all day.Size spares to the peak, not to the average, and review monthly.
ComplexityQueues, pools and streams are more parts to run.Add each on evidence, and give each an owner.
FairnessPriorities decide who waits.Publish the classes.

What this means for your role

Common mistakes

Step checklist

  • Each request type is assigned to the interactive or background path.
  • Queues have priority classes, per-store caps and age alerts.
  • Jobs have stable identifiers, bounded retries and a dead-letter queue.
  • Instances are stateless, and scaling follows in-flight requests, with a pre-peak schedule.
  • Provider quotas are known and compared with peak token rates.
  • Pools are split where measurement shows interference.
  • RTO and RPO are written per path and tested.
  • At least three zones are used, and the loss of one still carries peak.
  • Streams have event types, identifiers, heartbeats and an explicit error event.
  • Cancellation reaches the provider call, and partial answers are never cached.

Further reading

Queues, balanced instances and streaming keep Store Assist steady when the day starts badly. Next: Step 12: Observability and evaluation.

Search topics

↑↓ to move · Enter to open · Esc to close