Call Stability and Token Usage Governance in Local LLM Deployments
This article examines call stability and token usage governance for local LLM deployments. It breaks down common disconnection causes, provides a lightweight health-check script and a layered troubleshooting order, explains token estimation and how to handle large question banks, and covers resumable batch processing plus retry, backoff, and degradation strategies.
1. Background
When calling large language models in a local or private environment, a common approach is to start an inference service on a host and have the upper-layer application send HTTP requests and receive results. This architecture has low deployment cost and keeps data inside the internal network, but the call chain is longer than that of a hosted cloud service. It involves the model process, gateway proxy, VRAM resources, client configuration, and other components. When any one of these fails, users often see only “connecting” or “not connected,” or a task is interrupted halfway through execution.
In engineering practice, handling such problems requires first breaking the symptoms into verifiable hypotheses and then ruling them out one by one. The following sections proceed in the order of connection stability, token usage, batch tasks, fault-tolerance strategies, and option evaluation.
2. Connection Stability: From Symptoms to Causes
2.1 Common Causes of Disconnection
- The inference process crashes or is reclaimed by the system. When VRAM or memory is insufficient, the process exits and the service port is closed.
- Port listening is abnormal. The address bound by the service does not match the address accessed by the client. For example, if the service listens only on the loopback address while the client accesses it through a container network address, the connection is rejected directly.
- Proxy configuration interferes. A system proxy may intercept requests to local addresses, forward them to an external network, and eventually return a timeout or error.
- Timeout settings are too short. Long-text generation takes time. If the client read timeout is shorter than the actual generation time, the client considers the connection broken while the server is still computing.
- Concurrency exceeds service capacity. After requests pile up in the queue, the server may actively close some connections.
2.2 Using a Script for Health Checks
Before running a long task formally, probe the service with a lightweight request. The example below depends only on the standard library and checks whether the service is reachable and how long a single response takes. The endpoint path must be replaced with the address provided by the actual service.
import jsonimport timeimport urllib.requestimport urllib.errorENDPOINT = "http://127.0.0.1:8000/chat" # Replace with the actual chat endpointPAYLOAD = {"model": "local-model","messages": [{"role": "user", "content": "ping"}],"max_tokens": 4,}def check_service(timeout: float = 5.0) -> bool:data = json.dumps(PAYLOAD).encode("utf-8")req = urllib.request.Request(ENDPOINT,data=data,headers={"Content-Type": "application/json"},method="POST",)start = time.monotonic()try:with urllib.request.urlopen(req, timeout=timeout) as resp:resp.read()print(f"Service is available; response time {time.monotonic() - start:.2f}s")return Trueexcept urllib.error.URLError as exc:print(f"Service unreachable: {exc.reason}")except TimeoutError:print("Request timed out; check whether the model is still loading")return Falseif __name__ == "__main__":check_service()
2.3 Layered Troubleshooting Order
Troubleshooting is more efficient when performed from the bottom layer upward:
- Confirm that the inference process exists and check the logs for VRAM- or memory-related errors.
- Use the system port query command to confirm that the service is indeed listening on the expected address and port.
- Check the system proxy settings to ensure that local addresses do not go through the proxy.
- Run the health-check script above to verify whether the simplest request can complete.
- Finally, adjust the timeout parameters on the business side and observe the actual duration of long-text tasks.
3. Token Usage: Estimate First, Then Control
3.1 What Token Usage Consists Of
Token usage mainly consists of three parts: input tokens (system prompt, history messages, attachment content), output tokens (content generated by the model), and other overhead that the server may count. In multi-turn conversations, history messages are sent again as input in each round, so the longer the conversation, the larger the input size of a single request. This is the main reason for rapid usage growth.
3.2 Rough Estimation Method
Chinese text can usually be estimated at about 1.5 tokens per Chinese character, and English text at about 1.3 tokens per English word. This estimation is only for judging the order of magnitude. The actual segmentation result depends on the tokenization method of the specific model, so before launch, the usage value returned by real calls should be used as the basis.
import redef estimate_tokens(text: str) -> int:"""Roughly estimate the token count of text; for order-of-magnitude judgment only."""cjk_chars = len(re.findall(r"[\u4e00-\u9fff]", text))latin_words = len(re.findall(r"[A-Za-z]+", text))return int(cjk_chars * 1.5 + latin_words * 1.3)
3.3 Handling a Large Question Bank
Take a question bank containing 2,000 questions as an example. Assume each question has an average of 100 Chinese characters for the stem and options. The full text is about 200,000 characters, estimated at about 300,000 tokens using the coefficients above. If the entire file is sent to the model at once, the context of a single request will be very large. This can easily exceed the model’s context limit and also makes the cost of a single failure very high.
A more reliable approach is:
- Split by question type or fixed quantity. For example, use 20 questions per batch to avoid excessively long content in a single batch.
- Constrain the output format. Require the model to return only structured results, such as JSON with fixed fields, to reduce invalid output.
- Summarize in steps. Persist the results of each batch first, and finally use a local script to calculate metrics such as accuracy and question-type distribution instead of asking the model to complete all statistics at once.
- Record usage. Save the input and output token counts for each batch request so that the most expensive stage can be identified.
4. Resuming Batch Tasks from Checkpoints
Long-running batch tasks often fail midway due to network fluctuations or process exits. Starting from the beginning every time wastes resources and consumes tokens repeatedly. The key to resuming from checkpoints is to record a batch as completed only after its results have been persisted.
import jsonimport osSTATE_FILE = "progress.json"def chunk(items: list, size: int):for start in range(0, len(items), size):yield start // size, items[start:start + size]def load_progress() -> set[int]:if not os.path.exists(STATE_FILE):return set()with open(STATE_FILE, "r", encoding="utf-8") as f:return set(json.load(f))def save_progress(done: set[int]) -> None:tmp = STATE_FILE + ".tmp"with open(tmp, "w", encoding="utf-8") as f:json.dump(sorted(done), f)os.replace(tmp, STATE_FILE) # Atomic replacement; an interrupted write will not leave a corrupted progress filedef run_batches(items: list, batch_size: int, handler) -> None:done = load_progress()for idx, batch in chunk(items, batch_size):if idx in done:continuehandler(batch) # handler must write results to disk before returningdone.add(idx)save_progress(done)
This code has two key points. First, the progress file is written through a temporary file and atomic replacement, preventing the progress file from being corrupted if the write is interrupted. Second, the responsibility of handler includes persisting results. If progress is recorded before results are written to disk, that batch of data will be lost after recovery.
5. Retry, Backoff, and Degradation
5.1 Retry Only Recoverable Errors
Not all errors are worth retrying. Network timeouts, connection resets, and temporary service unavailability are transient faults and can be retried. Parameter errors, authentication failures, and excessively long request content are deterministic errors; retrying only consumes resources repeatedly.
5.2 Exponential Backoff with Random Jitter
The retry interval should increase gradually and include random jitter to avoid pressure concentration caused by multiple tasks retrying at the same time.
import randomimport timedef call_with_retry(fn, max_retries: int = 4, base_delay: float = 1.0):for attempt in range(max_retries + 1):try:return fn()except (ConnectionError, TimeoutError) as exc:if attempt == max_retries:raisedelay = base_delay * (2 ** attempt) + random.uniform(0, 0.5)print(f"Attempt {attempt + 1} failed: {exc}; retrying in {delay:.1f}s")time.sleep(delay)
5.3 Degrade After Consecutive Failures
If retries still fail, the problem may not be occasional. In this case, the following degradation measures can be taken:
- Reduce the batch size to lower the load of a single request.
- Reduce the maximum number of tokens generated per request to shorten response time.
- Pause task concurrency and wait for the service to recover.
- When multiple usable models are available at the same time, switch to a backup model.
Furthermore, a circuit breaker mechanism can be introduced: after consecutive failures reach a threshold, pause calls for a period of time, and then use a small number of probe requests to determine whether the service has recovered.
