AI Agents 7 min read

Measure SERP API Latency: Queue Time and Request Time

Measure client queue time, request duration and accepted completion rate with a saved-log Python example. Separate synthetic arithmetic from provider benchmarks.

(Updated: ) • 1,274 words

Quick answer

Measure the delay you can observe before attributing it to a provider. A queued AI search can spend time waiting in your own scheduler, making an HTTP request, retrying, reading pages, and waiting for a model. More allowed concurrency does not prove that any one of those stages became faster.

Use these timings to diagnose a client request. The concurrency and throughput worksheet gives the capacity calculation separately; neither example reports a timed provider comparison or a customer speedup.

Give each attempt a clock and an acceptance state

Record queued when an attempt enters the client queue, started immediately before sending it, and ended after the response has been consumed or the attempt has failed. Use time.perf_counter() for durations within one process. It is a monotonic performance counter, not a calendar timestamp. Keep a separate UTC collection time in the log.

Observation Meaning What it cannot establish
started − queued Wait in the instrumented client queue Time inside a remote provider queue
ended − started Client-observed request duration, including transport and response handling Pure provider compute time or network-free server latency
Last ended − first queued Elapsed time of the recorded batch Complete agent-answer time if reading and generation occur later
Accepted attempts / batch elapsed Accepted request completion rate for this batch A sustained service guarantee or complete answer rate

Set acceptance before the test: HTTP success, business code == 0, and the response fields needed by your task. A completed failure remains an attempt. If the collector stops while requests are still running, mark the run incomplete; do not feed only its early successes into a supposedly complete batch report.

Summarize a saved log without a paid request

import math


def positive_number(value, allow_zero=False):
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise ValueError("Expected a finite number")
    if not math.isfinite(value) or value < 0 or (not allow_zero and value == 0):
        raise ValueError("Number is outside the accepted range")
    return value


def nearest_rank(values, fraction):
    ordered = sorted(values)
    return ordered[math.ceil(fraction * len(ordered)) - 1] if ordered else None


def summarize(attempts):
    if not attempts:
        raise ValueError("At least one completed attempt is required")
    queue, request, successful = [], [], []
    for row in attempts:
        q, s, e = [positive_number(row[k], True)
                   for k in ("queued", "started", "ended")]
        if not q <= s <= e or type(row.get("accepted")) is not bool:
            raise ValueError("Invalid timing order or acceptance state")
        queue.append(s - q)
        request.append(e - s)
        if row["accepted"]:
            successful.append(e - s)
    elapsed = max(r["ended"] for r in attempts) - min(r["queued"] for r in attempts)
    return {"attempts": len(attempts), "accepted": len(successful),
            "batch_elapsed_s": elapsed,
            "accepted_per_s": len(successful) / elapsed if elapsed else None,
            "client_queue_p95_s": nearest_rank(queue, .95),
            "all_attempt_request_p95_s": nearest_rank(request, .95),
            "accepted_request_p50_s": nearest_rank(successful, .5)}


if __name__ == "__main__":
    # Synthetic seconds from one monotonic clock, not provider measurements.
    sample = [{"queued": 0, "started": 0, "ended": 2, "accepted": True},
              {"queued": 0, "started": 2, "ended": 5, "accepted": True},
              {"queued": 0, "started": 5, "ended": 6, "accepted": False}]
    print(summarize(sample))

The synthetic input returns three attempts, two accepted requests and a six-second batch. Its accepted completion rate is 2/6 requests per second. The nearest-rank p95 request duration is three seconds. With only three attempts, that percentile is effectively the largest value; it says nothing reliable about the tail of a production distribution. These numbers demonstrate the calculation only.

Collect the timestamps around an actual request

Save the following as timing_collector.py. The caller supplies a finite job list and the send function. Each attempt gets its own queue timestamp before submission; the worker records the start and end. Failed HTTP requests and rejected response bodies remain in the output.

import json
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone
from urllib.request import Request, urlopen


def post_json(url, body, api_key=None, timeout=40):
    headers = {"Content-Type": "application/json"}
    if api_key:
        headers["Authorization"] = "Bearer " + api_key
    request = Request(url, data=json.dumps(body).encode(), headers=headers, method="POST")
    with urlopen(request, timeout=timeout) as response:
        return json.load(response)


def accepts_search(payload):
    return (isinstance(payload, dict) and type(payload.get("code")) is int
            and payload["code"] == 0 and isinstance(payload.get("data"), dict)
            and isinstance(payload["data"].get("organic"), list))


def collect(jobs, send, workers=3):
    if type(workers) is not int or not 1 <= workers <= 3:
        raise ValueError("This collector uses one to three workers")
    jobs = list(jobs)
    if not jobs:
        raise ValueError("Provide a bounded nonempty workload")

    def attempt(ident, job, queued):
        row = {"attempt_id": ident, "queued": queued,
               "collected_at": datetime.now(timezone.utc).isoformat(),
               "started": time.perf_counter(), "accepted": False}
        try:
            payload = send(job)
            row["accepted"] = accepts_search(payload)
            row["error"] = None if row["accepted"] else "response_contract"
        except Exception as exc:
            row["error"] = type(exc).__name__  # No key, body or private URL in the log.
        finally:
            row["ended"] = time.perf_counter()
        return row

    with ThreadPoolExecutor(max_workers=workers) as pool:
        futures = [pool.submit(attempt, i, job, time.perf_counter())
                   for i, job in enumerate(jobs)]
        rows = [future.result() for future in as_completed(futures)]
    return sorted(rows, key=lambda row: row["attempt_id"])

For SearchCans, pass a function that calls post_json("https://www.searchcans.com/api/v1/search", job, api_key), with request bodies such as {"t": "google", "s": "Python time perf_counter", "p": 1}. Write the returned rows to a JSON file and pass those completed rows to summarize above. Do not log the key. This collector deliberately performs no automatic retries; give a retry a new attempt record if your caller schedules one.

A local HTTP-server test checked an accepted search response, a business error inside HTTP 200, a server error and a client timeout. The test asserts timestamp ordering and retention of failed attempts; it makes no claim about SearchCans latency. If you terminate the process before the pool finishes, its partial file is still an incomplete run.

Keep retries and request types visible

  • Give retries separate attempt IDs and retain their parent operation ID. A successful retry does not erase the failed attempt or the time spent waiting.
  • Separate SERP requests from Reader requests. A completed search does not establish that a selected page was read or an answer was accepted.
  • Keep engine, country, language, requested depth and response-acceptance rules comparable. Record timeout and cache settings where supported.
  • Include failures, cancellations and outstanding requests in the run record. The summary function accepts only completed attempts.

Change one control, then rerun the same acceptance set

Run the same saved workload with a different client concurrency limit and compare the queue, request-duration and accepted-completion distributions. A shorter batch alongside a longer client request duration can still be a useful tradeoff, but report both. An overloaded client, source website, network or downstream model can move the bottleneck.

SearchCans Parallel Lanes describe simultaneous requests. They do not make client-observed latency a fixed value. Read the search response contract before deciding what counts as an accepted result, and budget additional source-page reads separately.

Evidence and limits

The example was checked locally on November 1, 2026 with synthetic logs. Python documents the performance counter. The p95 here uses the explicitly stated nearest-rank convention; there is no claim that it matches every monitoring system. No production latency, error rate, credit charge or performance advantage is inferred from this fixture.

Tags:

AI Agents SERP API High Concurrency Latency Reduction Cost Optimization
SearchCans Team

SearchCans Team

SERP API & Reader API Experts

The SearchCans engineering team builds high-performance search APIs serving developers worldwide. We share practical tutorials, best practices, and insights on SERP data, web scraping, RAG pipelines, and AI integration.

Ready to build with SearchCans?

Test SERP API and Reader API with 100 free credits. No credit card required.