Cost Governance and Quota Design for Web Search and Crawling in LLMs

    Integrating web search and crawling into LLM services introduces significant additional costs beyond pure inference, including API fees, bandwidth, CPU consumption, and increased input tokens. This article explores the technical implications of these costs, details engineering implementation strategies using token buckets and search gateways, and outlines best practices for tiered quota design, observability, and avoiding common pitfalls in resource management.

    1. Why Web-Enabled Capabilities Cost More Than Pure Inference

    The cost of pure inference primarily comes from model computation and output tokens. Web-enabled capabilities add several other types of overhead on top of this: retrieval API call fees, bandwidth consumed by downloading web pages, CPU used for HTML parsing and text extraction, and the additional input tokens generated when crawled content is inserted into the context.

    A seemingly simple query might trigger multiple searches. The system retrieves several web pages for each search, and the main text of each page might contain tens of thousands of characters. Without truncation, the context size expands rapidly, leading to increased inference latency and per-request costs. Therefore, the cost of web-enabled capabilities cannot be estimated solely by “number of requests”; it must also account for the actual number of pages crawled and the volume of content per request.

    2. Resource Model: Dual Occupation of Inference Compute and External Calls

    Resources for LLM services can be divided into two categories. The first is inference compute, which is affected by concurrency, context length, and output length. The second is external dependencies, including search service quotas, target website access frequency limits, and network egress bandwidth.

    The occupation patterns of these two resource types differ. Inference compute is occupied intensively when a request arrives, whereas crawling tasks have more unstable durations. When a target site is slow or times out, a single request might hold a connection and worker thread for a long time.

    When a specific group of users has usage habits like high-frequency queries, long conversations, and default auto-search enabled, they significantly amplify the occupation of both resource types. Determining whether a group is “consuming too many resources” should rely on monitoring data, such as the number of searches per user per day, the average number of pages crawled, and the token distribution per request. Relying solely on subjective impressions or anecdotal discussions cannot yield reliable conclusions.

    3. Technical Implications of Tiered Strategies

    Setting differentiated rules for different user tiers is a common resource management approach. From a technical perspective, tiered strategies are typically implemented through the following mechanisms:

    • Quotas: Limiting the number of searches per minute, hour, or day.
    • Concurrency limits: Restricting the number of simultaneous crawling tasks for a single user.
    • Priority queues: Prioritizing higher-tier user requests when resources are constrained.
    • Feature toggles: Enabling or disabling certain capabilities (like automatic full-text crawling) based on the tier.

    For developers, the biggest risk of tiered strategies often lies not in the rules themselves, but in the lack of prior notice when rules change. If quotas are adjusted without a transition period, businesses relying on these capabilities will suffer directly. Therefore, integrators should decouple quota reading from retry logic in their code and subscribe to the service provider’s change notifications.

    4. Engineering Implementation

    4.1 Token Bucket Rate Limiting

    The token bucket is a common algorithm for handling burst traffic and smoothing rate limits. The bucket refills tokens at a fixed rate, each request consumes a corresponding number of tokens, and new tokens are discarded when the bucket is full. The following implementation uses a monotonic clock to calculate the refill amount, avoiding errors caused by system clock jumps.

    1. import time
    2. import threading
    3. class TokenBucket:
    4. def __init__(self, rate: float, capacity: int):
    5. self.rate = rate # Tokens refilled per second
    6. self.capacity = capacity # Bucket capacity, determines allowed burst requests
    7. self.tokens = float(capacity)
    8. self.updated = time.monotonic()
    9. self.lock = threading.Lock()
    10. def acquire(self, cost: float = 1.0) -> bool:
    11. with self.lock:
    12. now = time.monotonic()
    13. elapsed = now - self.updated
    14. self.updated = now
    15. self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
    16. if self.tokens >= cost:
    17. self.tokens -= cost
    18. return True
    19. return False

    4.2 Tiered Policy Table

    Centralizing the parameters for each tier makes them easier to audit and adjust, and convenient to manage uniformly in a configuration center.

    1. TIER_POLICY = {
    2. "free": {"searches_per_min": 3, "max_pages": 2, "priority": 2},
    3. "standard": {"searches_per_min": 20, "max_pages": 5, "priority": 1},
    4. "premium": {"searches_per_min": 60, "max_pages": 8, "priority": 0},
    5. }

    The parameter values are for illustration only. Actual values should be determined based on your own cost models and capacity testing.

    4.3 Search Gateway: Rate Limiting, Caching, and Degradation

    The gateway is responsible for chaining rate limiting, caching, crawling, and degradation into a complete pipeline. The specific implementations of searching and crawling are injected by the caller; the gateway itself is not bound to any external service.

    1. import hashlib
    2. class SearchGateway:
    3. def __init__(self, search_fn, fetch_fn, cache):
    4. self.search_fn = search_fn # Search interface, injected by the caller
    5. self.fetch_fn = fetch_fn # Fetch interface, injected by the caller
    6. self.cache = cache # Key-value cache with expiration
    7. self.buckets = {}
    8. def _bucket(self, user_id, tier):
    9. if user_id not in self.buckets:
    10. limit = TIER_POLICY[tier]["searches_per_min"]
    11. self.buckets[user_id] = TokenBucket(rate=limit / 60, capacity=limit)
    12. return self.buckets[user_id]
    13. def answer_context(self, user_id, tier, query):
    14. policy = TIER_POLICY[tier]
    15. # Cache key is generated only from the query, excluding user ID to prevent privacy leaks
    16. key = "search:" + hashlib.sha256(query.strip().lower().encode()).hexdigest()
    17. cached = self.cache.get(key)
    18. if cached is not None:
    19. return cached
    20. if not self._bucket(user_id, tier).acquire():
    21. # Degrade when quota is exceeded: stop crawling, answer based on existing model knowledge and explain the situation
    22. return {"status": "degraded", "reason": "quota_exceeded", "snippets": []}
    23. results = self.search_fn(query)[: policy["max_pages"]]
    24. pages = []
    25. for item in results:
    26. page = self.fetch_fn(item["url"], max_bytes=512_000)
    27. if page:
    28. pages.append(page)
    29. context = {"status": "ok", "snippets": pages}
    30. self.cache.set(key, context, ttl=900)
    31. return context

    This code illustrates several key points. First, cache hits do not consume quotas and do not generate external calls. Second, both the number of crawled pages and the bytes per page are capped to prevent infinite context growth. Third, when quotas are exceeded, the system returns a clear degraded status, allowing the caller to inform the user that the result might be incomplete.

    4.4 Necessary Constraints on the Crawling Side

    The crawling module needs to adhere to the following constraints, regardless of user tiers:

    • Read and comply with the target site’s crawling protocol file (e.g., robots.txt).
    • Set connection and read timeouts; abandon timed-out tasks directly without waiting indefinitely.
    • Limit the number of concurrent requests to a single site to avoid putting pressure on the target site.
    • Deduplicate and truncate the main text, removing navigation bars, ads, and script content.
    • Comply with copyright and terms of use when caching content, and set reasonable expiration times.

    5. Observability: Data-Driven Adjustments Over Guesswork

    After launching a tiered strategy, you should continuously observe the following metrics:

    • Average daily searches and crawled pages per user, broken down by tier.
    • Cache hit rate. If the cache hit rate is low, check if query normalization is reasonable.
    • The proportion of retrieved content within the input tokens per request.
    • P95 latency and failure rates for search and crawling stages.
    • Unit request costs broken down by tier.

    These metrics can answer key questions: Does a specific tier actually drive up costs? How many resources can be saved by adjusting quotas? And does the degradation strategy affect answer quality? Without this data, any judgment regarding resource allocation lacks a factual basis.

    6. Common Pitfalls

    Pitfall 1: Rate limiting solely by request count. Crawling two pages versus ten pages in a single request consumes vastly different amounts of resources. Quotas should consider both the number of requests and the bytes crawled.

    Pitfall 2: Including user identifiers in cache keys. This eliminates the reuse value of the cache and increases privacy risks. Search results for public web pages can typically share a cache based on the query content.

    Pitfall 3: Silently returning empty results on failure. Callers cannot distinguish between “no relevant information” and “service degradation,” which affects answer quality. Explicit status fields allow upper-layer logic to handle situations correctly.

    Pitfall 4: Adjusting rules without a transition plan. Even if the service provider’s rule changes are reasonable, integrators need to prepare fault-tolerance logic in advance, such as fallback degradation paths and retry backoff strategies.

    7. Practical Recommendations

    It is recommended to proceed in the following order: first, establish monitoring to obtain real usage data for each tier; second, design rate limiting and caching parameters, and validate them on a small scale; finally, gradually adjust quotas based on the observed results. Every adjustment should record the reason for the change and the metrics before and after, facilitating subsequent reviews.

    The value of a technical solution lies in providing a measurable basis for resource allocation. Both service providers and integrators should focus the discussion on measurable costs, latency, and quality, ensuring that rule changes are predictable and reversible.