When Personalisation Costs 15 Seconds: Redesigning an LLM Feature for Reliability
Taking the LLM off the Critical Path: Parlato’s Cache-First Redesign

How I changed personalised vocabulary practice so learners could start a session without waiting for generated sentences.
Parlato already had a usable exercise sentence, yet loading a learning session could take approximately 10–15 seconds. The wait came from generating a personalised alternative before returning the session.
I had introduced personalised example sentences to make vocabulary practice more relevant to each learner. The first implementation generated them while the learning session was being assembled. That gave the feature an appealing property: the first time somebody encountered a word, its sentence could already reflect their interests.
It also meant that an optional enhancement could delay the entire session.
What personalisation was meant to add
Parlato is a language-learning application built with TypeScript and the Next.js 16 App Router. Its main interaction is deliberately small: read a sentence in the language you are learning and supply the missing word.
The learning engine selects vocabulary using deterministic rules, including an SM-2 spaced-repetition scheduler, an Elo-based ability estimate and frequency ranking. Those decisions can be tested with fixed inputs and do not require a model provider.
Personalisation changes the sentence around the selected word. Learners can choose a speaking style and favourite films or television series; the application also supplies default titles for the target language. The model receives the word, its meaning, the target and translation languages, the learner’s level and the selected context, and is asked to produce an original example with a translation.
Generated content replaces the exercise sentence and its native-language translation. The word hint remains the reviewed, deterministic content already associated with the card.
The intention is to evoke a familiar setting or tone while keeping the sentence suitable for practice. The prompt asks the model to avoid spoilers and authentic-quotation claims. Those are content requirements; asking for them does not prove that every response satisfies them.
Title selection uses TMDB catalogue entries, giving the application a stable reference for the chosen film or series. The generation prompt includes that content context without including the learner’s account identity.
The exercise remains useful with its curated sentence. That existing content eventually became the basis of the redesign.
Why the first implementation waited
During session construction, applyPersonalisation processed the selected words. For up to 12 cards, it called getPersonalisedSentence, which checked the cache and generated a sentence when the required entry was missing.
A successful response was validated, stored and included in the session. If generation failed, the application retained the curated sentence.
This kept the execution flow straightforward. The same operation populated the cache and consumed the result, and the learner could see personalisation immediately. For short generated sentences, the extra work initially seemed reasonable.
The project notes attribute the 10–15-second stalls to awaiting these generation calls. The requests ran concurrently in the original design, but session construction waited for their combined result through Promise.all. Concurrency avoided adding every request’s duration together; it did not remove the wait for the slowest outstanding request when failures were handled within each call.
Each generation request had a 12-second timeout. That limited how long an individual attempt could wait, but still allowed an optional feature to consume seconds of the loading experience.
The original wait.
Simplified request flow. The original cache checks are grouped for readability; this does not imply a batched query in the first implementation.
The curated fallback was already available in memory. The application waited until the generation attempt finished before returning it, so the fallback did little to protect responsiveness.
That was the decision I needed to revisit: when should the application stop waiting for an enhancement it could already do without?
Returning the content we already had
A shorter model timeout would have reduced the permitted delay. Generating fewer sentences would have reduced the number of external calls. Both approaches would still have made session delivery depend on model response time.
Pre-generating every combination was also unattractive. Vocabulary, target language, translation language, favourite title, proficiency level and speaking style all influence the output. Much of that content might never be requested.
I changed session construction to read generated sentences from the cache and retain curated content wherever a usable entry was unavailable. Missing entries could trigger generation, but the session would no longer await its result.
The new request flow is:
Build the session with curated sentences.
Look up the required generated sentences in one PostgreSQL batch.
Merge matching cache entries into the selected cards.
Retain the curated sentence for each miss.
Start a capped number of generation attempts without awaiting their completion.
The cache lookup has its own 200-millisecond waiting budget, implemented by racing the batch read against a timer. If the timer wins, the function returns the curated cards and does not start cache warming for that session build. The database query itself is not cancelled by this race.
A read failure follows a different path. The cache helper logs the error and returns missing entries. If that result arrives before the timer, those entries can still trigger warming. An unavailable cache and a confirmed absent row therefore have the same generation behaviour in this implementation; separating them would avoid attempting generation when the cache cannot be read.
This is a budget for waiting on optional personalisation. Authentication, vocabulary selection, database access elsewhere in the request and rendering still contribute to loading time.
After a completed lookup, up to 12 misses can trigger the generation service. The warmer skips a redundant cache read because the batch has already supplied the result. Cached sentences can be reused beyond that cap.
The new request and generation paths.
The two branches express independent completion. They do not promise that generation starts only after the response has been sent.
The visible compromise is delayed personalisation. A learner’s first encounter with a word may use the curated sentence. If generation succeeds, a later matching load can use the generated version. The application does not replace a sentence already shown in the current session.
Deciding when a sentence can be reused
The generated-sentence cache is shared across learners. Its identity describes the content being requested, including the proficiency level defined by the Common European Framework of Reference for Languages (CEFR):
Native language belongs in the key because the cached record includes a translation. Two learners studying the same word with the same film preference may still need different translations. Omitting that dimension would allow an otherwise valid cache hit to supply the wrong content.
Conversely, learner ID would prevent reuse where the complete generation context is already equivalent. Sharing by context allows one successful generation to serve more than one learner.
The selected title is derived from the stable word ID and the available favourites list. Reordering the cards therefore keeps the same title association when that list is unchanged. Changing the favourites list can change the association and lead to a different cache entry.
That makes cache identity part of the feature’s behaviour. The current key has no prompt or generation-policy version, and the generated-sentence reads apply no time-based expiry. Changes to the prompt, validation rules or vocabulary meaning therefore need an explicit decision about existing entries. The separate vocabulary cache has a time-to-live; that policy does not automatically apply to personalised sentences.
The database enforces uniqueness across all six key fields, and inserts ignore a conflicting key. That prevents a competing insert from adding a duplicate row. It does not establish that the model was called only once: separate application instances can both observe a miss and generate before either stores its result.
Shared caching reduces repeat work when contexts recur. Its cost still depends on new combinations, failed attempts and concurrency across instances. A flat model bill as usage grows would be too strong a claim.
What “background” means in this design
The implementation starts generation with an unawaited call in the application process and attaches a rejection handler. This path uses neither a durable job queue nor a framework hook that extends request execution after the response.
Parlato includes a production Docker configuration for running the standalone Next.js server in Node.js. In a long-lived server process, unawaited work can continue after the response while the process remains alive. That configuration supports this execution model, but does not identify the live host or provide retries and recovery after a restart.
If execution stops before generation and storage finish, the cache can remain empty. A later request still receives curated content and may encounter the same miss again. Successful warming depends on the process lifecycle, provider response and database write.
This was a tolerable compromise for optional cache population. It would be a poor completion guarantee for work that the product had promised to finish.
The current provider adapter uses Gemini’s generateContent API, requests JSON output and retains the 12-second request timeout. It also admits only one active provider request per process. Attempts made while that request is running return without generating; they are not queued or combined with the active request. A rate-limit response starts a cooldown, using a positive numeric Retry-After value in seconds when available and otherwise waiting 60 seconds.
Consequently, a cap of 12 warming attempts does not promise 12 provider calls or 12 new cache entries. The local guard reduces bursts, but it neither coordinates separate instances nor guarantees that every missing sentence will eventually be generated.
Checking what the model returned
The response still crosses a trust boundary. A parseable JSON object is only the beginning of validation.
Before accepting a generated sentence, the service checks for a sentence and translation, locates the target word or an accepted alternative as a complete token, and applies the configured sentence-length range for the requested CEFR level. Matching normalises case and accents. The service also rejects embedded newlines and terms in its blocked-word set.
The application replaces the first accepted occurrence of the vocabulary word with ___ to create the exercise blank. Invalid output is discarded.
These checks enforce useful mechanical constraints. They do not establish that the translation is accurate, that the sentence is genuinely appropriate for the requested proficiency level, or that it avoids every spoiler. Sentence length is a practical heuristic for difficulty, and a blocked-word list covers only the terms it contains.
The blank also deserves its own invariant. The current implementation replaces the first matching occurrence; it does not separately reject existing blank markers or repeated target words that could reveal the answer. I would add those checks, together with runtime validation that both response fields are non-empty strings, before treating every accepted response as a verified single-blank exercise.
Missing credentials, provider failures and rejected output leave the delivered curated sentence in place. A failed cache write is logged but does not make the generated result available to later requests. Failure reasons deserve separate diagnostic categories, even when the learner sees the same fallback.
What changed, and what remains to be measured
The architectural change is specific: session construction no longer awaits fresh model generation. The learner can practise using the content already available while personalisation remains an optional enrichment.
The project notes record the original 10–15-second symptom and describe the redesign as removing that generation-related stall. They do not include the measurement environment, sample size or comparable latency distributions. The supported result is that fresh generation no longer holds up session construction. A numerical speed-up would require additional evidence.
This change also addresses only one source of waiting. Parlato’s documentation separately identifies slow Auth0 token refreshes and an empty initial exercise queue as loading problems. The client’s fallback session fetch has a 15-second abort timeout and a retry state. Those protections have different purposes from the model timeout and cache budget.
There is already a basis for investigating the remaining delay: /learn records timed authentication, store-initialisation, user-record and daily-session stages against a request ID. The project also has a token-gated learning diagnostic and a k6 load-test script with percentile thresholds. Their existence does not establish the result of a before-and-after performance test.
The next measurements should answer three questions:
Can learners start reliably? Track session-construction time and browser time to a usable first card, separating cache hits, misses and provider failures.
Does personalisation actually reach them? Track successful cache writes, later consumption of those entries and the proportion of cards using generated sentences. A completed generation has little product value if the same context is never requested again.
What does that availability cost? Track generation attempts, duplicate requests, timeouts, validation rejections and cache lookup failures.
The existing personalisation test verifies that cache retrieval uses one batch and preserves context order. The most useful next regression test would hold a model response pending and verify that session construction still completes with curated content. Other focused tests should cover the lookup budget, cache-key separation, invalid output, failed writes and the interaction between the generation cap, busy guard and cooldown.
The project’s 90 per cent coverage gate applies to deterministic domain logic. It should not be presented as evidence that these generation and lifecycle behaviours have been tested.
The decision I would keep
Personalisation introduced a useful capability and an unpredictable dependency. The initial implementation allowed that dependency to determine when a learner could begin practising.
The revised design gives generated content a narrower responsibility: enrich an exercise when it is available. Curated sentences remain maintained product content, and delayed personalisation is an explicit compromise.
That is the engineering decision I would keep. The application should be able to deliver its core interaction using the content it already trusts, while optional generation earns its place through usable results.
About the author
- Full-stack engineer with 6+ years building scalable backend systems and web platforms. Specializes in database optimization, API architecture, and performance engineering with TypeScript, Python, and Node.js.
Comments
Join the discussionThe separation between core functionality and optional generation is the strongest part of this redesign. At IT Path Solutions, we’ve found that removing an LLM from the critical path is only half the reliability problem; the fallback still needs a clear product contract. If curated and generated content differ in difficulty, ambiguity, or expected behavior, the system can remain technically available while becoming inconsistent for users. Defining what the fallback must guarantee makes the architecture much stronger: the background model can improve the experience when it succeeds, but it should never change the guarantees of the core interaction. That turns AI into a true enrichment layer rather than a hidden dependency.
Tool schemas that say almost anything get almost anything back. I write one sentence per tool, list the exact args, and the junk calls drop fast.



