Skip to content

Offer filtering CPU work degrades server responsiveness #4519

Todo

Description

@r4victor

Getting offers is CPU-heavy pure Python, and although it runs in executor threads, it degrades the responsiveness of the whole server: while it runs, every request and background task on the event loop slows down.

Where the CPU goes

Backends that use ComputeWithAllOffersCached (AWS, GCP, Azure, Lambda, RunPod, and most others) cache all offers and filter them per request. With 8 such backends, the cache holds ~57k offers, ~38k of them GCP. Each filter pass converts every cached InstanceOffer into a gpuhunt.CatalogItem just to call gpuhunt.matches():

def filter_offers_by_requirements(
offers: Iterable[InstanceOfferT],
requirements: Optional[Requirements],
ignore_disk: bool = False,
) -> Iterator[InstanceOfferT]:
query_filter = requirements_to_query_filter(requirements, ignore_disk=ignore_disk)
for offer in offers:
catalog_item = offer_to_catalog_item(offer)
if gpuhunt.matches(catalog_item, q=query_filter):
yield offer

One pass over the 57k offers takes ~90ms of CPU: ~75% in offer_to_catalog_item() and ~25% in gpuhunt.matches().

The number of passes per request multiplies this:

  • Run planning queries offers separately for each candidate fleet, and each query filters the offers of all backends, even when fleets have identical specs:

for candidate_fleet_model in candidate_fleet_models:
offers_from_fleet = []
for offer in await _get_backend_offers_in_fleet(
project=project,
fleet_model=candidate_fleet_model,
run_spec=run_spec,
job=job,
volumes=volumes,
max_offers=max_offers_per_fleet,
full_offers=full_offers,
unallocated_resources=unallocated_resources,
):
offer_identity = _get_backend_offer_identity(offer)
if offer_identity not in seen_offer_identities:
offers_from_fleet.append(offer)
seen_offer_identities.add(offer_identity)
offers = list(heapq.merge(offers, offers_from_fleet, key=lambda o: o.price))
return offers

  • Filtering is lazy and stops after enough matches, so requirements that match most offers (e.g. CPU-only) scan only a part of the list, but requirements that match few offers (e.g. H100:8, ~300 of 57k) scan every offer every time.

Measured for one /runs/get_plan request (H100:8): ~0.2s of CPU in a project with 1 fleet (2 full passes) and ~3.8s with 40 fleets (2.3M offers scanned).

Why it stalls the server

The work runs in executor threads, so it doesn't block the event loop directly, but it holds the GIL. A CPU-bound thread releases the GIL only when another thread has waited for the switch interval (5ms by default). The event loop thread releases the GIL on every syscall (each socket read/write, each poll), and then waits up to 5ms to get it back. So while offers are being filtered, every I/O step on the event loop costs ~5ms instead of microseconds.

A standalone test: an asyncio client doing small TCP round trips takes 0.11ms per round trip, 14.4ms with one thread filtering offers, and 29ms with two. Requests doing tens of DB round trips get 50-100ms+ added, and pipelines slow down the same way.

In a local server with a production-like state (390 fleets, API traffic mix of production at ~1.3 RPS), offer filtering accounted for most of the process CPU. Compared with no get_plan traffic, get_plan requests lowered the apdex of all other endpoints from 0.90 to 0.68 and raised the event loop lag p99 from 18ms to 59ms. Production servers show the same pattern: a bimodal latency where ~1/3 of requests spend 50-95ms before their first DB query.

Proposed changes

  1. Make each pass cheaper by not converting offers to catalog items, e.g. by matching requirements against InstanceOffer fields directly (a prototype returned identical results on 57k offers for a grid of requirements and cut a pass from ~90ms to 17-40ms). Caching a CatalogItem for each cached offer gives the same speedup but adds ~21 MiB per 57k-offer cache, and caches are per project.
  2. Index cached offers by GPU name, so requests that name GPUs check only those offers (H100:8: ~26ms → ~0.5ms per pass).
  3. Query offers once for candidate fleets that yield identical requirements and backends instead of once per fleet.
  4. Optionally lower the GIL switch interval (e.g. sys.setswitchinterval(0.001)), which cuts the waits for any remaining CPU work in threads ~5x (14.4ms → 3.1ms per round trip in the test above; apdex 0.68 → 0.79 in the local server).

Backends with ComputeWithFilteredOffersCached (Vast.ai, Daytona, Lium, Seeweb) are not affected: they cache offers per requirements and only convert matching items.

Activity

  1. r4victor commented on Nov 25, 2026

    @r4victor
    CollaboratorAuthor

    Proposed solution for 1 and 2: index the cached offers once per cache refresh instead of filtering the whole list per request, and match offers with a dstack-owned matcher instead of converting them to gpuhunt.CatalogItem.

    Offer index

    ComputeWithAllOffersCached.get_offers() currently filters every cached offer on every call:

    def get_offers(
    self, requirements: Requirements, full_offers: bool, unallocated_resources: bool
    ) -> Iterator[InstanceOfferWithAvailability]:
    with self._offers_cache_execution_lock:
    # Cache lock does not prevent concurrent execution.
    # We use a separate lock to avoid requesting offers in parallel, re-doing the work and hitting rate limits.
    cached_offers = self._get_all_offers_with_availability_cached(unallocated_resources)
    offers = self.__apply_modifiers(
    cached_offers, self.get_offers_modifiers(requirements, full_offers)
    )
    offers = filter_offers_by_requirements(offers, requirements, ignore_disk=True)
    offers = self.__fit_disk_size(offers, requirements)
    post_filter = self.get_offers_post_filter(requirements)
    if post_filter is not None:
    offers = (o for o in offers if post_filter(o))
    return offers

    Instead, when the offers cache refreshes, group the cached offers by a key made of fields with few distinct values: GPU vendor, GPU name, GPU memory, GPU count, spot, CPU arch, and CPU count. The index is a list of groups, each holding its key and its offers sorted by price. Groups reference the cached offers, no copies.

    A query checks each group's key against the requirements, skips groups that cannot match, and lazily merges the offers of the remaining groups by price, checking each offer. get_offers() returns the same lazy, price-ordered iterator as today, so its signature and callers don't change.

    The key covers all GPU, spot, CPU arch, and CPU count checks, so requests constrained by those compare about as many offers as they match. Only price, memory, and disk are left for per-offer checks. Groups stay few: 205 for GCP, 495 for 7 providers combined, and checking all keys takes microseconds.

    One offer matcher

    OfferMatcher is built once per requirements, has the same semantics as gpuhunt.matches(), and reads InstanceOffer fields directly:

    • matches_offer(offer) is the full check. The index uses it for every offer it returns, and it replaces offer_to_catalog_item() + gpuhunt.matches() wherever offers are matched today, including existing instances:

    if requirements is not None:
    if instance.offer is None:
    return False
    offer = validate_json_extra_ignore(InstanceOffer, instance.offer)
    catalog_item = offer_to_catalog_item(offer)
    if not gpuhunt.matches(catalog_item, q=requirements_to_query_filter(requirements)):
    return False

    for blocks in range(min_blocks, total_blocks + 1):
    shared_offer = generate_shared_offer(offer, blocks, total_blocks)
    catalog_item = offer_to_catalog_item(shared_offer)
    if gpuhunt.matches(catalog_item, query_filter):

    • matches_key(key) is the group check. It must never reject a group that contains a matching offer, but it may be looser than matches_offer(), so it affects only how much is skipped, not the results.

    Tests: matches_offer() agrees with gpuhunt.matches(offer_to_catalog_item(offer)) on the real catalog for a grid of requirements, and matches_offer(o) implies matches_key(get_offer_key(o)).

    Unchanged: disk fitting and get_offers_post_filter() run on the matched offers as today. Backends with get_offers_modifiers() (Kubernetes, Slurm, GCP with a reservation) keep the current linear path, since modifiers change the fields being matched. Backends with ComputeWithFilteredOffersCached are not affected.

    Prototype results

    55,233 offers from the gpuhunt catalog of 7 providers, 495 groups, index built in 28ms. Results are identical to filter_offers_by_requirements() in all cases. "Compared" is the number of offers checked to produce all matches (today it is all 55,233); times are for the first 50 matches and for all matches, measured locally.

    Requirements Matching Compared Top 50, now → new All, now → new
    default (on-demand) 27,276 29,413 4.0 → 0.8ms 81 → 35ms
    default, spot: auto 50,726 54,798 0.4 → 1.1ms 94 → 65ms
    default, max_price 0.5 5,189 29,413 4.0 → 3.4ms 66 → 10ms
    gpu: 0, cpu: 96.. 4,347 4,347 49 → 0.1ms 68 → 3.9ms
    memory: 1TB.. 2,717 29,413 59 → 9.0ms 71 → 12ms
    gpu: 1.. 7,014 7,818 23 → 0.7ms 77 → 11ms
    gpu: A100 477 477 48 → 0.2ms 74 → 0.7ms
    gpu: H100:8 178 178 72 → 0.2ms 72 → 0.3ms

    Narrow requests stop scanning the whole catalog: matching offers are the most expensive ones, so today even the first 50 require a near-full pass.

    Remaining costs:

    • Broad requests (default, spot: auto) match most offers, so getting all matches still touches each of them, and the gain comes only from the cheaper per-offer check. The first N offers are cheap either way.
    • max_price and memory-heavy requests compare ~29k offers to find 3-5k matches, since price and memory are not in the key. Groups are sorted by price, so a query can stop reading a group at max_price. Per-group min/max memory in matches_key() would cover memory if needed.
    • TODO: get_offers_post_filter() returns an opaque function, so it still runs on every matched offer and can't be used to skip groups (AWS reservations, RunPod and JarvisLabs multinode). Its cost isn't in the numbers above. Post-filters have to stay cheap per offer, and GCP's isn't: it validates backend_data into a pydantic model for each offer to read one flag, ~11ms for the ~17.7k GCP offers matching default requirements. Reading the flag from the dict directly cuts that to ~0.6ms:

    def get_offers_post_filter(
    self, requirements: Requirements
    ) -> Optional[Callable[[InstanceOfferWithAvailability], bool]]:
    if requirements.reservation is None:
    def reserved_offers_filter(offer: InstanceOfferWithAvailability) -> bool:
    """Remove reserved-only offers"""
    if validate_extra_ignore(
    GCPOfferBackendData, offer.backend_data
    ).is_dws_calendar_mode:
    return False
    return True
    return reserved_offers_filter

    Next steps

    • 3 is still needed: run planning queries offers for every candidate fleet. Querying once with the run requirements and checking the fleet constraints on the result removes the per-fleet multiplier.
    • Plans require all matches only for total_offers and max_price. Showing the top offers without an exact total, or caching results per requirements until the index is rebuilt, would make broad requests cheap as well.
    • 4 becomes less important once requests take milliseconds.
  2. self-assigned this
    on Nov 25, 2026
  3. r4victor commented on Nov 25, 2026

    @r4victor
    CollaboratorAuthor

    #4528 replaces the gpuhunt.matches() filtering with a dstack-owned OfferMatcher, which makes a full get_offers() pass over ~55k offers about 4x faster (121ms → 31ms with default requirements).

    Disk fitting remains expensive: if the requested disk differs from the default, every matching offer with a configurable disk is copied to set its disk size, which adds ~100ms per full pass (31ms → 133ms for disk: 200GB..).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions