Sub topic 4
When to ask: triggering, debouncing and cancelling requests
This chapter assumes you have read the earlier chapters on inline completions and context assembly. You should know what ghost text is and how a prefix and suffix are built. You should also read basic TypeScript or Python, and know what a promise and a timer are.
An editor assistant could send a request on every keystroke. Doing that wastes compute and money, and it shows suggestions that are already out of date. This chapter covers how an editor decides when to ask, how it waits for typing to settle, and how it cancels work that is no longer useful.
Why timing matters
A completion is only useful if it arrives while it still fits the code at the cursor. Typing speed makes this hard. A fast typist produces several keystrokes per second, and a model call often takes hundreds of milliseconds or more.
Consider what happens if you send one request per keystroke:
- Most responses describe a cursor position that no longer exists by the time they arrive.
- The backend does work that nobody sees, which costs money and uses rate limit quota.
- Responses can arrive out of order, so an old answer can replace a newer one.
- Ghost text flickers as each late response appears and disappears.
Three techniques address these problems. Triggering decides which events may start a request. Debouncing delays the request until typing pauses. Cancellation stops requests whose result is no longer wanted.
Triggering
A trigger is an event that allows the editor to start a completion request. Editors distinguish two kinds.
- Automatic triggers fire as you type. The editor decides on its own that a suggestion might help.
- Explicit triggers fire when you ask, for example with a keyboard shortcut.
In VS Code, the provider receives a context object whose triggerKind tells it which kind occurred. The value Invoke means the user asked explicitly. The value Automatic means the editor fired the request while typing. A provider can use this to be more selective with automatic requests and more generous with explicit ones.
Common reasons to skip an automatic request
A good provider rejects many automatic triggers before it spends any money. Typical checks include:
- The file type is disabled in settings, or the file is too large.
- The cursor is inside a region where completion is unwelcome, such as a password field or a file the user excluded.
- The line is empty and nothing has been typed since the cursor moved there, so there is little signal about intent.
- The user is in the middle of a selection or an active IntelliSense popup that already shows suggestions.
- A suggestion for the same prefix is already cached or already displayed.
- The user has paused the feature or the network is offline.
Each check is cheap compared to a model call. Placing them first keeps the expensive path rare.
Multiline or single-line
Many assistants decide how much to request based on the cursor position. If the cursor is in the middle of a line, a short single-line completion is usually right. If the cursor sits at the end of a line that opens a block, such as after a colon or an opening brace, a multiline completion is more likely to be useful. Asking for fewer tokens when a long answer is unlikely also reduces latency.
Debouncing
Debouncing means waiting for a quiet period before acting. Each new event resets the timer, so the action runs only after the events stop for the full delay.
For completions, the delay is short. The TypeScript example from the chapter on provider APIs uses 150 ms. A typical range is 75 to 300 ms. The trade-off is direct:
| Delay | Effect |
|---|---|
| Too short | Many wasted requests, flicker, higher cost |
| Too long | Suggestions feel slow, users type past them |
| Adaptive | Delay changes with typing speed or recent acceptance |
An adaptive delay can start low and rise when the user rejects many suggestions, or drop when they accept often. This adds complexity, so measure before adopting it. The chapter on evaluation metrics covers how.
Debounce versus throttle
A debounce waits for silence. A throttle allows at most one call per interval, no matter how much activity there is. Completions generally prefer debounce, because the latest cursor state is the only one that matters. A throttle would send requests for intermediate states you do not care about.
A debounce in Python
The following function wraps a coroutine so that only the last call within the delay window actually runs. It is complete and runs as shown.
import asyncio
class Debouncer:
def __init__(self, delay: float):
self.delay = delay
self._task: asyncio.Task | None = None
def call(self, make_coro):
"""Schedule make_coro() after the delay; replace any pending call."""
if self._task is not None and not self._task.done():
self._task.cancel()
self._task = asyncio.create_task(self._run(make_coro))
return self._task
async def _run(self, make_coro):
await asyncio.sleep(self.delay)
return await make_coro()
async def main():
debouncer = Debouncer(delay=0.15)
results = []
async def request(text: str):
results.append(text)
return text
for text in ["d", "de", "def"]:
debouncer.call(lambda t=text: request(t))
await asyncio.sleep(0.05) # typing faster than the delay
await asyncio.sleep(0.4)
print(results) # ['def']
asyncio.run(main())Three keystrokes arrive 50 ms apart, which is faster than the 150 ms delay. Each new call cancels the previous pending one, so only def reaches the request function.
Note that _run also cancels an in-flight request, because cancelling the task raises CancelledError at the current await. In a real client the awaited call would be an HTTP request, and cancellation should close that connection.
Cancellation
Debouncing prevents requests from starting. Cancellation handles requests that have already started and then become stale. A request becomes stale when:
- The user types another character.
- The cursor moves to a different line or file.
- The user accepts or dismisses a suggestion.
- The editor window loses focus.
VS Code signals this through a CancellationToken passed to the provider. The provider should check the token, and it should also abort the network request. Checking the token alone only stops the editor from showing the result. Aborting the request is what saves backend work.
Aborting the backend call
The provider example from the earlier chapter creates an AbortController and links it to the token:
const controller = new AbortController();
token.onCancellationRequested(() => controller.abort());
const text = await fetchCompletion(prefix, suffix, controller.signal);When abort() is called, the HTTP client closes the connection. A server that streams tokens can notice the closed connection and stop generating. If the server ignores disconnects, it keeps generating tokens that nobody will read, so check that your backend honors them.
Handling out-of-order responses
Cancellation is best effort. A response can still arrive after you cancelled. Two defenses are common:
- Check the token again after every
awaitbefore touching any state. - Attach a request identifier or a document version number, and discard any response whose identifier is not the latest.
The document version is the more robust option, because it catches changes that did not trigger a cancellation event. Compare the version at request time with the version at response time, and drop the result if they differ.
const versionAtRequest = document.version;
const text = await fetchCompletion(prefix, suffix, controller.signal);
if (token.isCancellationRequested || document.version !== versionAtRequest) {
return [];
}Reusing results instead of asking again
Some typing makes a new request unnecessary. Suppose the model suggested print(value) and you type p, r, i, n, t. Each typed character matches the start of the existing suggestion. The editor can keep showing the remaining ghost text and send no request at all.
VS Code supports this in part: when typed text matches the beginning of the shown suggestion, the suggestion stays visible with the rest displayed. A provider can add its own cache keyed by the prefix and suffix. A cache hit costs nothing and appears instantly, which improves both cost and perceived latency.
A cache has an edge case. If the suffix changed, a cached result may no longer fit, so include the suffix, or a hash of it, in the key.
A request lifecycle
The diagram shows the order of decisions for one automatic trigger.
Common errors
- Debouncing on the server only. The client still sends every request and pays for the connection. Debounce on the client.
- Forgetting to abort. The token is checked, but the HTTP request keeps running. Cost and rate limit use stay high.
- No staleness check after the await. An old response overwrites a newer state.
- A delay that is never tuned. A fixed value that feels fine on your machine may feel sluggish on a slow connection, where the total delay is the debounce plus network time.
- Triggering on every character class. Whitespace-only edits and pasted blocks often deserve different handling than ordinary typing.
Summary of decisions
| Question | Common answer |
|---|---|
| Which events start a request? | Typing and explicit invoke, after cheap filters |
| How long to wait? | About 75 to 300 ms, reset on each keystroke |
| What to do on new input? | Cancel the pending timer and abort the in-flight request |
| How to catch late responses? | Compare the document version or request id |
| How to avoid repeat requests? | Cache by prefix and suffix, and reuse matching ghost text |
Exercise
A user types five characters in one second, with about 200 ms between keystrokes. Your debounce delay is 150 ms and each model call takes 600 ms. Roughly how many requests are sent, how many are cancelled mid-flight, and what would you change to reduce waste?
Show answer
Because each gap of 200 ms is longer than the 150 ms delay, the timer expires before the next key, so a request is sent after nearly every keystroke, about five in total. Each takes 600 ms, so the next keystroke arrives while the previous request is still running. Four of the five requests are cancelled mid-flight, and only the last one can finish. To reduce waste, raise the delay above the typing gap (for example 250 ms), or use an adaptive delay based on recent typing speed. Also abort the HTTP request on cancellation so the backend stops generating.
Exercise
Your provider checks token.isCancellationRequested before sending a request but not after the response arrives. Describe a failure that can result and give two fixes.
Show answer
A request can start, the user can type more, and the old response can then arrive and be shown for a cursor state that no longer exists, or overwrite a newer suggestion. Fix one: check the token again after every await. Fix two: record document.version when the request starts and discard the response if the version differs when it returns. Linking an AbortController to the token also stops the backend work.