Asynchronous Warehouse Query Client

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Analytical data warehouses execute SQL statements asynchronously: submitting a statement immediately returns an execution handle, the job progresses through server-side lifecycle states, and completed row sets are retrieved page by page. Your task is to implement ClientConfig and QueryClient, a resilient Python wrapper around a low-level warehouse transport object (api).

Provided SDK Contract

The api instance passed to QueryClient exposes five methods:

  • api.login(account, user, password) -> str: authenticates credentials and returns a session token string.
  • api.submit(token, sql, params, request_id) -> str: enqueues sql with positional params (list) and returns a query_id. The server deduplicates by request_id: repeating a submit call with an already-seen request_id returns the original query_id without executing the statement twice.
  • api.status(token, query_id) -> {"state": str, "error": Optional[str]}: reports the current state string ("QUEUED", "RUNNING", "SUCCEEDED", "FAILED", or "CANCELED") and an optional failure description.
  • api.fetch(token, query_id, page_token) -> {"columns": List[str], "rows": List[List[Any]], "next_page": Optional[str]}: fetches one page of rows (page_token=None requests the first page; "next_page" is None on the final page).
  • api.cancel(token, query_id) -> None: aborts an in-flight query.

Transient transport problems raise ConnectionError or TimeoutError. Server-side rejections raise ApiError(code, message), where code may be "AUTH_FAILED", "INVALID_SQL", "UNKNOWN_QUERY", or another warehouse error code.

Client Requirements

  1. Configuration & Secret Hygiene (ClientConfig):

    • ClientConfig(account="", user="", password="") must omit password from repr().
    • ClientConfig.from_env(env) reads "WAREHOUSE_ACCOUNT", "WAREHOUSE_USER", and "WAREHOUSE_PASSWORD" from env (defaulting absent keys to "").
    • connect() validates that account and user are non-blank (after stripping whitespace) and password is non-empty before touching the network. If any are missing, raise ConfigError naming the missing field(s). Otherwise authenticate via api.login and store the session token. Calling query operations before connect() raises QueryClientError.
    • If api.login raises ApiError("AUTH_FAILED", ...), raise AuthenticationError without retrying and ensure the password never appears in the error text or chained exception traceback.
  2. Retries & Error Mapping:

    • QueryClient(api, config, max_attempts=3, backoff_s=0.5, sleep=time.sleep, clock=time.monotonic) validates max_attempts >= 1 and backoff_s >= 0 (raising ConfigError otherwise).
    • Every SDK call retries ConnectionError and TimeoutError up to max_attempts total attempts, sleeping backoff_s, 2 * backoff_s, 4 * backoff_s, ... between attempts via sleep, and raising NetworkError once attempts are exhausted.
    • Never retry ApiError: map "AUTH_FAILED" to AuthenticationError, "INVALID_SQL" to InvalidSQLError, "UNKNOWN_QUERY" to UnknownQueryError, and any other code to QueryClientError.
  3. Query Execution, Polling, Pagination, & Cancellation:

    • start_query(sql, params=None) -> str: raise InvalidSQLError locally (no SDK call) if sql is not a string or is whitespace-only. Pass bind parameters as a separate list ([] when params is None), never interpolated into sql. Reuse one generated request_id across retries of the same start_query call so a dropped response cannot duplicate execution.
    • get_query_status(query_id) -> QueryState: return the mapped QueryState enum member (QUEUED, RUNNING, SUCCEEDED, FAILED, CANCELED), or raise QueryClientError if the status payload is malformed.
    • get_results(query_id) -> QueryResult: check query status first. Raise ResultsNotReadyError if QUEUED or RUNNING, QueryFailedError (including the server's error message) if FAILED, or QueryCanceledError if CANCELED, without calling api.fetch. When SUCCEEDED, iterate api.fetch from page_token=None until next_page is None and return all rows concatenated in order inside QueryResult(columns, rows).
    • wait_for_completion(query_id, timeout_s, poll_interval_s=1.0) -> QueryState: validate timeout_s >= 0 and poll_interval_s > 0 (ConfigError otherwise). Poll until the query reaches SUCCEEDED, FAILED, or CANCELED, sleeping min(poll_interval_s, remaining_seconds) via sleep and clock. If the deadline expires first, raise QueryTimeoutError(query_id, timeout_s) without canceling the query.
    • cancel_query(query_id) -> None: cancel query_id via api.cancel.
    • run_query(sql, params=None, timeout_s=300.0, poll_interval_s=1.0) -> QueryResult: submit, wait for completion, and return get_results(query_id). If wait_for_completion raises QueryTimeoutError, make a best-effort cancel_query(query_id) call (ignoring QueryClientError from cleanup) before re-raising QueryTimeoutError.

Examples

Example 1

config = ClientConfig.from_env({
    "WAREHOUSE_ACCOUNT": "northwind",
    "WAREHOUSE_USER": "svc_analytics",
    "WAREHOUSE_PASSWORD": "p@ss-99",
})
client = QueryClient(api, config, max_attempts=3, backoff_s=0.5, sleep=clock.sleep, clock=clock.time)
client.connect()

qid = client.start_query(
    "SELECT host, cpu_pct FROM metrics WHERE region = ? AND cpu_pct >= ?",
    ("us-east", 85),
)
final_state = client.wait_for_completion(qid, timeout_s=10.0, poll_interval_s=1.5)
result = client.get_results(qid)

Suppose status reports "QUEUED", then "RUNNING", then "SUCCEEDED", and fetch returns two pages: (["host", "cpu_pct"], [["web-01", 91], ["web-02", 88]], next_page="1") followed by (["host", "cpu_pct"], [["db-01", 95]], next_page=None).

Output: - final_state == QueryState.SUCCEEDED - result == QueryResult(columns=["host", "cpu_pct"], rows=[["web-01", 91], ["web-02", 88], ["db-01", 95]])

Walk-through: start_query sends ["us-east", 85] separately from the SQL template and obtains "q1". wait_for_completion polls at t = 0.0s (QUEUED), sleeps 1.5s, polls at t = 1.5s (RUNNING), sleeps 1.5s, and sees SUCCEEDED at t = 3.0s. get_results then fetches both pages in cursor order and combines all three rows.

Example 2

# Submit drops the network once after creating q1; status stays RUNNING forever.
client.run_query("SELECT COUNT(*) FROM events", timeout_s=2.5, poll_interval_s=1.0)

Output: Raises QueryTimeoutError("q1", 2.5), records sleep intervals [0.5, 1.0, 1.0, 0.5], creates only 1 server-side query, and cancels "q1".

Walk-through: Attempt 1 of submit raises ConnectionError, so _call sleeps 0.5s and retries with the identical request_id, recovering "q1" at t = 0.5s without duplicating the query. wait_for_completion sets deadline = 3.0s, polls at t = 0.5s (sleeps 1.0s), t = 1.5s (sleeps 1.0s), t = 2.5s (clamps sleep to 0.5s), and t = 3.0s (remaining == 0), then raises QueryTimeoutError. Because the caller of run_query never received "q1", run_query cancels "q1" before re-raising.

Constraints

  • max_attempts >= 1 and backoff_s >= 0.0 (raise ConfigError otherwise).
  • timeout_s >= 0.0 and poll_interval_s > 0.0 (raise ConfigError otherwise).
  • password values may contain arbitrary characters and must never appear in repr(config), exception messages, or formatted tracebacks.
  • All time measurements and sleeps must go through the injected clock and sleep callables.

Step-by-step walkthrough

  1. Understand the asynchronous warehouse lifecycle

    Unlike an embedded database that returns rows synchronously on a single function call, an analytical data warehouse executes statements asynchronously: submitting SQL immediately returns a query_id, the job progresses through server-side execution states, and completed rows arrive across paginated fetches.

    Client calls                         Warehouse state machine
    ------------                         -----------------------
    connect()          --login()------>  issues session token
    start_query()      --submit()----->  [ QUEUED ]
    get_query_status() --status()----->      |
                                             v
                                         [ RUNNING ]
                                          /   |    \
                   cancel_query() -------+    |     +----> [ FAILED ]
                         |                    v
                         v               [ SUCCEEDED ]
                   [ CANCELED ]               |
                                         get_results() --fetch(page_token)--> pages 0..k
    

    Let us summarize what the low-level api transport can return or raise: - login(account, user, password) -> str (session token) - submit(token, sql, params, request_id) -> str (query_id; repeating an already-seen request_id returns the original query_id) - status(token, query_id) -> {"state": str, "error": Optional[str]} - fetch(token, query_id, page_token) -> {"columns": [...], "rows": [[...]], "next_page": Optional[str]} - cancel(token, query_id) -> None - Network failures raise ConnectionError or TimeoutError; server rejections raise ApiError(code, message).

    Our goal is to turn that raw transport into a safe, ergonomic QueryClient.

  2. Design typed states and an actionable error hierarchy

    Comparing raw strings like if status == "SUCCEDED": silently misbehaves when someone misspells a state name. Representing states with an Enum catches typos immediately, and grouping the three finished states into TERMINAL_STATES keeps polling loops clean:

    class QueryState(Enum):
        QUEUED = "QUEUED"
        RUNNING = "RUNNING"
        SUCCEEDED = "SUCCEEDED"
        FAILED = "FAILED"
        CANCELED = "CANCELED"
    
    
    TERMINAL_STATES = (QueryState.SUCCEEDED, QueryState.FAILED, QueryState.CANCELED)
    

    Similarly, callers should never have to catch half a dozen unrelated SDK and socket exceptions. Every error raised by our client inherits from one base class, QueryClientError, with specific subclasses chosen by what the caller should do next:

    QueryClientError (catch-all base class)
     ├── ConfigError, AuthenticationError   --> fix deployment / credentials (do not retry)
     ├── InvalidSQLError, UnknownQueryError --> fix caller bug in SQL or query_id (do not retry)
     ├── NetworkError                       --> warehouse unreachable after retries
     ├── ResultsNotReadyError               --> still QUEUED or RUNNING; poll again later
     ├── QueryTimeoutError(query_id, ...)   --> deadline expired; caller can keep waiting or cancel
     └── QueryFailedError, QueryCanceledError -> terminal non-success; report to user
    

    Notice that QueryTimeoutError stores self.query_id on the exception so a caller whose wait timed out still knows which query is active.

  3. Load configuration at runtime without leaking secrets

    Hard-coding credentials in source code is a security hazard. ClientConfig.from_env(env) reads WAREHOUSE_ACCOUNT, WAREHOUSE_USER, and WAREHOUSE_PASSWORD from a passed-in mapping (os.environ in production, a plain dictionary in unit tests).

    Three safeguards keep secrets out of logs and crash reports: 1. field(repr=False) on password: Printing or logging a ClientConfig shows ClientConfig(account='northwind', user='svc_analytics') and never prints the password. 2. Fail-fast validation naming fields, never values: connect() checks missing_fields() before making any network call and reports only which field names are blank (for example "missing configuration: password"). 3. Scrubbed authentication errors: Some servers echo attempted credentials in error text (such as "login failed for svc_analytics with password wrong-secret-42"). When ApiError("AUTH_FAILED", ...) arrives, we return AuthenticationError with a fixed message AND raise it with from None so Python does not chain the raw ApiError into logger.exception tracebacks!

    @dataclass
    class ClientConfig:
        account: str = ""
        user: str = ""
        # repr=False hides password whenever ClientConfig is printed or logged
        password: str = field(default="", repr=False)
    
        @classmethod
        def from_env(cls, env: Mapping[str, str]) -> "ClientConfig":
            return cls(
                account=env.get("WAREHOUSE_ACCOUNT", ""),
                user=env.get("WAREHOUSE_USER", ""),
                password=env.get("WAREHOUSE_PASSWORD", ""),
            )
    
        def missing_fields(self) -> List[str]:
            missing: List[str] = []
            if not self.account.strip():
                missing.append("account")
            if not self.user.strip():
                missing.append("user")
            if not self.password:
                missing.append("password")
            return missing
    
  4. Centralize retries, exponential backoff, and error translation

    Every SDK call flows through a single helper, _call(method, *args), so retry and error-mapping rules live in one place rather than being copy-pasted across five methods:

    • Transient network failures (ConnectionError, TimeoutError) are retried up to max_attempts times using exponential backoff: wait backoff_s after attempt 1, 2 * backoff_s after attempt 2, 4 * backoff_s after attempt 3, and so on. Doubling the pause gives a congested network or overloaded gateway time to recover.
    • Server rejections (ApiError) are never retried: bad SQL or bad credentials will fail the exact same way 0.5 seconds later. Instead, translate_api_error maps the error code immediately.
    Example with max_attempts = 3, backoff_s = 0.5:
      Attempt 1 --(ConnectionError)--> sleep 0.5s
      Attempt 2 --(TimeoutError)-----> sleep 1.0s
      Attempt 3 --(ConnectionError)--> raise NetworkError (total sleep = 1.5s)
    
    def _call(self, method: Callable[..., Any], *args: Any) -> Any:
        """Invoke an SDK method with exponential-backoff retries on transient network errors."""
        attempt = 1
        while True:
            try:
                return method(*args)
            except (ConnectionError, TimeoutError) as exc:
                if attempt >= self._max_attempts:
                    raise NetworkError(
                        f"warehouse unreachable after {attempt} attempts: {exc}"
                    ) from exc
                # Exponential backoff: wait backoff_s, 2 * backoff_s, 4 * backoff_s, ...
                wait_seconds = self._backoff_s * (2 ** (attempt - 1))
                self._sleep(wait_seconds)
                attempt += 1
            except ApiError as exc:
                error = translate_api_error(exc)
                if isinstance(error, AuthenticationError):
                    # Drop __cause__ (`from None`) so echoed passwords never appear in tracebacks
                    raise error from None
                raise error from exc
    
  5. Submit queries safely with bind parameters and an idempotency key

    start_query(sql, params) protects against two classic bugs:

    1. SQL injection and broken quoting: Never format parameter values into the SQL string! Passing last_name = "D'Angelo" into an f-string breaks SQL syntax, and malicious input like "' OR 1=1 --" alters the query logic. Passing bound_params = list(params) separately lets the warehouse bind values safely.
    2. Duplicate query execution on lost replies: Suppose submit reaches the server and starts SELECT COUNT(*) FROM events (or an INSERT), but the network drops while the server's reply is traveling back. If _call retried with a brand-new request ID, the warehouse would run the statement twice! Creating request_id = str(uuid.uuid4()) once before calling _call gives every retry the same idempotency key so the warehouse recognizes the duplicate and returns the original query_id.
    def start_query(self, sql: str, params: Optional[Sequence[Any]] = None) -> str:
        """Submit SQL with separate bind parameters and return the server's query_id."""
        if not isinstance(sql, str) or not sql.strip():
            raise InvalidSQLError("sql must be a non-empty string")
        bound_params = list(params) if params is not None else []
        # Generate one idempotency key BEFORE _call() so retries reuse the exact same request_id
        request_id = str(uuid.uuid4())
        session_token = self._require_session()
        return self._call(self._api.submit, session_token, sql, bound_params, request_id)
    
  6. Poll status and fetch paginated results

    Before fetching any rows in get_results(query_id), we check _fetch_status(query_id) so non-succeeded queries get clear, specific exceptions: - QueryState.FAILED -> QueryFailedError (including the server's error message, such as "Numeric overflow"). - QueryState.CANCELED -> QueryCanceledError. - QueryState.QUEUED or QueryState.RUNNING -> ResultsNotReadyError.

    Once the query is SUCCEEDED, warehouse results can span multiple pages. Tracing Example 1, we start with page_token = None for the first page, append page["rows"] to our rows list, and advance page_token = page["next_page"] until next_page comes back None:

    fetch("q1", page_token=None) --> rows [["web-01", 91], ["web-02", 88]], next_page="1"
    fetch("q1", page_token="1")  --> rows [["db-01", 95]],                  next_page=None  (stop!)
    Combined rows: [["web-01", 91], ["web-02", 88], ["db-01", 95]]
    
  7. Wait with a monotonic deadline and cancel orphaned queries

    When polling in wait_for_completion(query_id, timeout_s, poll_interval_s), three timing details matter: 1. Use a monotonic clock (time.monotonic): Wall-clock time.time() can jump backward or forward when NTP adjusts the system clock; a monotonic clock only moves forward. Injecting clock and sleep into __init__ also lets unit tests use a fake clock and run in microseconds! 2. Clamp the sleep to the remaining budget (min(poll_interval_s, remaining)): In Example 2, wait_for_completion starts at t = 0.5s with timeout_s = 2.5 (deadline = 3.0s) and poll_interval_s = 1.0. Polling runs at t = 0.5, t = 1.5, and t = 2.5, then sleeps min(1.0, 0.5) = 0.5s for one final check right at t = 3.0s before raising QueryTimeoutError. 3. Who cancels on timeout? In wait_for_completion, the caller already holds query_id and may choose to wait longer, so we leave the query running. In run_query, the caller never saw query_id, so if wait_for_completion times out, run_query calls _cancel_quietly(query_id) (ignoring cleanup errors so the caller still receives QueryTimeoutError) rather than leaving an orphaned query burning warehouse credits.

    def wait_for_completion(
        self,
        query_id: str,
        timeout_s: float,
        poll_interval_s: float = 1.0,
    ) -> QueryState:
        if timeout_s < 0:
            raise ConfigError("timeout_s must be non-negative")
        if poll_interval_s <= 0:
            raise ConfigError("poll_interval_s must be positive")
    
        deadline = self._clock() + timeout_s
        while True:
            state = self.get_query_status(query_id)
            if state in TERMINAL_STATES:
                return state
            remaining = deadline - self._clock()
            if remaining <= 0:
                raise QueryTimeoutError(query_id, timeout_s)
            # Clamp sleep to `remaining` so we never oversleep past the deadline
            self._sleep(min(poll_interval_s, remaining))
    
  8. Complete solution

    from typing import Any, Callable, List, Mapping, Optional, Sequence, Tuple
    import time
    import uuid
    from dataclasses import dataclass, field
    from enum import Enum
    
    
    class ApiError(Exception):
        """Raised by the SDK when the server rejects a request.
    
        code: "AUTH_FAILED", "INVALID_SQL", "UNKNOWN_QUERY", or another server code.
        """
    
        def __init__(self, code: str, message: str = ""):
            super().__init__(f"{code}: {message}")
            self.code = code
            self.message = message
    
    
    class QueryClientError(Exception):
        """Base class for every error the client raises."""
    
    
    class ConfigError(QueryClientError):
        """Configuration is missing or invalid; raised before any network call."""
    
    
    class AuthenticationError(QueryClientError):
        """The warehouse rejected the credentials."""
    
    
    class InvalidSQLError(QueryClientError):
        """The SQL is empty or the warehouse rejected it."""
    
    
    class UnknownQueryError(QueryClientError):
        """The warehouse does not know this query id."""
    
    
    class NetworkError(QueryClientError):
        """The warehouse could not be reached, even after retries."""
    
    
    class QueryTimeoutError(QueryClientError):
        """The query did not finish before the deadline; it may still be running."""
    
        def __init__(self, query_id: str, timeout_s: float):
            super().__init__(f"query {query_id} did not finish within {timeout_s}s")
            self.query_id = query_id
    
    
    class QueryFailedError(QueryClientError):
        """Results were requested for a query that ended in FAILED."""
    
    
    class QueryCanceledError(QueryClientError):
        """Results were requested for a query that ended in CANCELED."""
    
    
    class ResultsNotReadyError(QueryClientError):
        """Results were requested while the query is still QUEUED or RUNNING."""
    
    
    class QueryState(Enum):
        QUEUED = "QUEUED"
        RUNNING = "RUNNING"
        SUCCEEDED = "SUCCEEDED"
        FAILED = "FAILED"
        CANCELED = "CANCELED"
    
    
    # Once a query enters any of these three states, its status will never change again
    TERMINAL_STATES = (QueryState.SUCCEEDED, QueryState.FAILED, QueryState.CANCELED)
    
    
    @dataclass
    class QueryResult:
        columns: List[str]
        rows: List[List[Any]]
    
    
    @dataclass
    class ClientConfig:
        """Connection settings. The password must never show up in repr() or in error messages."""
        account: str = ""
        user: str = ""
        # repr=False hides password whenever ClientConfig is printed or logged
        password: str = field(default="", repr=False)
    
        @classmethod
        def from_env(cls, env: Mapping[str, str]) -> "ClientConfig":
            """Read WAREHOUSE_ACCOUNT, WAREHOUSE_USER and WAREHOUSE_PASSWORD (pass os.environ in production)."""
            return cls(
                account=env.get("WAREHOUSE_ACCOUNT", ""),
                user=env.get("WAREHOUSE_USER", ""),
                password=env.get("WAREHOUSE_PASSWORD", ""),
            )
    
        def missing_fields(self) -> List[str]:
            """Return the names (never the secret values) of any required settings that are empty."""
            missing: List[str] = []
            if not self.account.strip():
                missing.append("account")
            if not self.user.strip():
                missing.append("user")
            if not self.password:
                missing.append("password")
            return missing
    
    
    def translate_api_error(err: ApiError) -> QueryClientError:
        """Map an SDK server rejection code to a typed QueryClientError subclass."""
        if err.code == "AUTH_FAILED":
            # Use a fixed message so echoed credentials from the server never leak into logs
            return AuthenticationError("authentication failed; check the user and password")
        if err.code == "INVALID_SQL":
            return InvalidSQLError(err.message)
        if err.code == "UNKNOWN_QUERY":
            return UnknownQueryError(err.message)
        return QueryClientError(f"warehouse error {err.code}: {err.message}")
    
    
    class QueryClient:
        """Wraps the SDK: connect, start a query, poll it, fetch its results, and map every failure
        to a QueryClientError subclass."""
    
        def __init__(
            self,
            api: Any,
            config: ClientConfig,
            max_attempts: int = 3,
            backoff_s: float = 0.5,
            sleep: Callable[[float], None] = time.sleep,
            clock: Callable[[], float] = time.monotonic,
        ):
            if max_attempts < 1:
                raise ConfigError("max_attempts must be at least 1")
            if backoff_s < 0:
                raise ConfigError("backoff_s must be non-negative")
            self._api = api
            self._config = config
            self._max_attempts = max_attempts
            self._backoff_s = backoff_s
            self._sleep = sleep
            self._clock = clock
            # self._token: active session token string from login(), e.g. "token-1", or None before connect()
            self._token: Optional[str] = None
    
        # ----- Phase 1: Connection management -----
    
        def connect(self) -> None:
            """Validate configuration locally, then authenticate to obtain a session token."""
            missing = self._config.missing_fields()
            if missing:
                raise ConfigError("missing configuration: " + ", ".join(missing))
            self._token = self._call(
                self._api.login,
                self._config.account,
                self._config.user,
                self._config.password,
            )
    
        def close(self) -> None:
            self._token = None
    
        def __enter__(self) -> "QueryClient":
            self.connect()
            return self
    
        def __exit__(self, exc_type, exc, tb) -> None:
            self.close()
    
        # ----- Phase 2: Asynchronous query lifecycle -----
    
        def start_query(self, sql: str, params: Optional[Sequence[Any]] = None) -> str:
            """Submit SQL with separate bind parameters and return the server's query_id."""
            if not isinstance(sql, str) or not sql.strip():
                raise InvalidSQLError("sql must be a non-empty string")
            bound_params = list(params) if params is not None else []
            # Generate one idempotency key BEFORE _call() so retries reuse the exact same request_id
            request_id = str(uuid.uuid4())
            session_token = self._require_session()
            return self._call(self._api.submit, session_token, sql, bound_params, request_id)
    
        def get_query_status(self, query_id: str) -> QueryState:
            state, _ = self._fetch_status(query_id)
            return state
    
        def get_results(self, query_id: str) -> QueryResult:
            """Verify the query succeeded, then fetch and concatenate all result pages."""
            state, error_text = self._fetch_status(query_id)
            if state == QueryState.FAILED:
                raise QueryFailedError(f"query {query_id} failed: {error_text}")
            if state == QueryState.CANCELED:
                raise QueryCanceledError(f"query {query_id} was canceled")
            if state != QueryState.SUCCEEDED:
                raise ResultsNotReadyError(f"query {query_id} is still {state.value}")
    
            session_token = self._require_session()
            columns: List[str] = []
            rows: List[List[Any]] = []
            # page_token: None requests the first page; subsequent pages pass the server's cursor string
            page_token: Optional[str] = None
            first_page = True
    
            while True:
                page = self._call(self._api.fetch, session_token, query_id, page_token)
                if first_page or page.get("columns"):
                    columns = list(page["columns"])
                    first_page = False
                rows.extend(page["rows"])
                page_token = page["next_page"]
                if page_token is None:
                    break
    
            return QueryResult(columns=columns, rows=rows)
    
        def wait_for_completion(
            self,
            query_id: str,
            timeout_s: float,
            poll_interval_s: float = 1.0,
        ) -> QueryState:
            """Poll until the query enters a terminal state, or raise QueryTimeoutError at timeout_s."""
            if timeout_s < 0:
                raise ConfigError("timeout_s must be non-negative")
            if poll_interval_s <= 0:
                raise ConfigError("poll_interval_s must be positive")
    
            deadline = self._clock() + timeout_s
            while True:
                state = self.get_query_status(query_id)
                if state in TERMINAL_STATES:
                    return state
                remaining = deadline - self._clock()
                if remaining <= 0:
                    raise QueryTimeoutError(query_id, timeout_s)
                # Clamp sleep to `remaining` so we never oversleep past the deadline
                self._sleep(min(poll_interval_s, remaining))
    
        def cancel_query(self, query_id: str) -> None:
            session_token = self._require_session()
            self._call(self._api.cancel, session_token, query_id)
    
        def run_query(
            self,
            sql: str,
            params: Optional[Sequence[Any]] = None,
            timeout_s: float = 300.0,
            poll_interval_s: float = 1.0,
        ) -> QueryResult:
            """Submit, wait, and fetch results; cancel the orphaned query if waiting times out."""
            query_id = self.start_query(sql, params)
            try:
                self.wait_for_completion(query_id, timeout_s, poll_interval_s)
            except QueryTimeoutError:
                # The caller never received query_id, so cancel on their behalf to stop billing
                self._cancel_quietly(query_id)
                raise
            return self.get_results(query_id)
    
        # ----- Phase 3: Internal transport & retry helpers -----
    
        def _require_session(self) -> str:
            if self._token is None:
                raise QueryClientError("not connected: call connect() first")
            return self._token
    
        def _fetch_status(self, query_id: str) -> Tuple[QueryState, Optional[str]]:
            session_token = self._require_session()
            info = self._call(self._api.status, session_token, query_id)
            try:
                state = QueryState(info["state"])
            except (KeyError, ValueError):
                raise QueryClientError(f"unexpected status response for {query_id}: {info!r}")
            return state, info.get("error")
    
        def _cancel_quietly(self, query_id: str) -> None:
            try:
                self.cancel_query(query_id)
            except QueryClientError:
                # Best-effort cleanup: preserve the original QueryTimeoutError for the caller
                pass
    
        def _call(self, method: Callable[..., Any], *args: Any) -> Any:
            """Invoke an SDK method with exponential-backoff retries on transient network errors."""
            attempt = 1
            while True:
                try:
                    return method(*args)
                except (ConnectionError, TimeoutError) as exc:
                    if attempt >= self._max_attempts:
                        raise NetworkError(
                            f"warehouse unreachable after {attempt} attempts: {exc}"
                        ) from exc
                    # Exponential backoff: wait backoff_s, 2 * backoff_s, 4 * backoff_s, ...
                    wait_seconds = self._backoff_s * (2 ** (attempt - 1))
                    self._sleep(wait_seconds)
                    attempt += 1
                except ApiError as exc:
                    error = translate_api_error(exc)
                    if isinstance(error, AuthenticationError):
                        # Drop __cause__ (`from None`) so echoed passwords never appear in tracebacks
                        raise error from None
                    raise error from exc
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Querying an analytical data warehouse is like ordering custom-built furniture from a workshop rather than grabbing a snack from a vending machine. Instead of blocking a single socket for minutes while terabytes of data are scanned, you submit your order and immediately receive a claim ticket (query_id), check the status board periodically (QUEUED -> RUNNING -> SUCCEEDED), and carry the finished pieces out one box at a time (paginated result fetching). QueryClient acts as a disciplined concierge in front of that workshop: it validates configuration up front, keeps passwords off printed paperwork, retries brief line drops without accidentally placing the same order twice, and cancels orders nobody is waiting for anymore.

A naive wrapper that calls the raw SDK directly, splices values into SQL with f-strings, and retries every exception in a tight loop breaks in production right away. Splicing strings opens SQL injection bugs (where untrusted input alters the SQL command itself), retrying without deduplication runs an INSERT twice if a network reply drops, retrying bad SQL or bad passwords wastes requests on errors that can never succeed, and giving up on a slow query without canceling it leaves the warehouse burning compute credits on an orphaned job.

Trace Example 1's workflow (SELECT host, cpu_pct FROM metrics WHERE region = ? AND cpu_pct >= ? with ("us-east", 85), timeout_s=10.0, poll_interval_s=1.5): 1. Submit (t = 0.0s): start_query generates one idempotency key (a unique request_id sent with every retry of the same logical request so the server runs it at most once) and sends the SQL template plus ["us-east", 85] separately, receiving query_id = "q1". 2. Poll (t = 0.0s -> 3.0s): wait_for_completion checks status at t = 0.0s (QUEUED), sleeps 1.5s, checks at t = 1.5s (RUNNING), sleeps 1.5s, and sees SUCCEEDED at t = 3.0s, returning immediately because SUCCEEDED is a terminal state. 3. Paginate (t = 3.0s): get_results confirms SUCCEEDED, fetches page_token = None (getting [["web-01", 91], ["web-02", 88]] and next_page = "1"), then fetches page_token = "1" (getting [["db-01", 95]] and next_page = None), returning QueryResult(columns=["host", "cpu_pct"], rows=[["web-01", 91], ["web-02", 88], ["db-01", 95]]).

Complexity

  • Time (SDK round trips and waiting): connect, start_query, get_query_status, and cancel_query each perform O(1) SDK calls in the healthy case and at most max_attempts calls under transient network failures, sleeping a total of backoff_s * (2^(max_attempts - 1) - 1) seconds (0.5 + 1.0 = 1.5s with defaults) before raising NetworkError. wait_for_completion polls status at most ceil(timeout_s / poll_interval_s) + 1 times because each sleep advances toward the fixed deadline, and get_results performs 1 status call plus P page fetches for a P-page result (O(P) network calls and O(R) work to collect R rows).
  • Space: O(R). Connection state, session token, and polling variables use O(1) memory, while get_results accumulates all R returned rows in memory inside QueryResult (see the streaming follow-up for keeping memory at O(page_size)).

Edge cases

  • Missing or whitespace-only configuration fields: connect() raises ConfigError naming the missing field names (never values) before making any network call.
  • Invalid credentials: AuthenticationError uses a fixed message and raise ... from None so a server message that echoes the attempted password cannot leak through chained exception tracebacks; authentication rejections are never retried.
  • Calling methods before connect() or after close(): _require_session() immediately raises QueryClientError("not connected: call connect() first") instead of sending token=None.
  • Empty SQL or syntax errors: Blank SQL raises InvalidSQLError locally with zero network calls; server-detected syntax errors map to InvalidSQLError without retrying.
  • Lost submit response after the query was created: Because request_id is generated once before _call, the retry sends the identical request_id and receives the same query_id rather than executing the SQL a second time.
  • Fetching results in non-succeeded states: QUEUED or RUNNING raises ResultsNotReadyError, FAILED raises QueryFailedError with the server's execution error (such as "Numeric overflow"), and CANCELED raises QueryCanceledError without calling fetch.
  • Zero timeout (timeout_s = 0): Polls status once; returns immediately if already terminal, or raises QueryTimeoutError without sleeping.
  • Invalid retry or polling settings: max_attempts < 1, backoff_s < 0, timeout_s < 0, or poll_interval_s <= 0 raise ConfigError immediately instead of looping infinitely or crashing time.sleep.

Common mistakes

  • Interpolating parameters into SQL strings: Using f-strings or % formatting breaks on quotes like "D'Angelo" and introduces SQL injection; always send bind parameters separately.
  • Generating request_id inside the retry loop: Creating a fresh UUID on every attempt defeats idempotency and causes duplicate writes when a response packet is dropped.
  • Retrying deterministic errors or retrying without backoff: Retrying INVALID_SQL or AUTH_FAILED wastes time and can lock out accounts, while retrying immediately in a tight loop turns a brief hiccup into a retry storm (many clients hammering a recovering server simultaneously).
  • Measuring deadlines with time.time() instead of time.monotonic(): A monotonic clock (a timer guaranteed to move only forward at a steady rate regardless of system clock adjustments) prevents premature timeouts or stalled waits when NTP steps the system clock.
  • Leaving timed-out run_query calls running: When run_query hides query_id from the caller, failing to cancel on timeout leaks warehouse compute credits on a result nobody can ever fetch.
  • Chaining AuthenticationError from the raw ApiError: Even if your wrapper message hides the password, raise error from exc attaches exc as __cause__, causing logger.exception to print the raw server message anyway.
  • Fetching only the first page: Ignoring next_page silently truncates large query results.

Follow-up questions

  • How should production services store, authenticate with, and rotate warehouse credentials without downtime? Never embed secrets in source files, git history, or container images; fetch them at runtime from a dedicated secrets manager (such as Vault or cloud secret stores) or mounted workload-identity tokens. Prefer key-pair authentication (signing a short-lived assertion with a private cryptographic key that never leaves the host) or OAuth tokens (short-lived, scoped access tokens issued by an identity provider) over static passwords. To rotate credentials cleanly without restarting workers, inject a credential-provider callback into QueryClient so session expiration or AUTH_FAILED triggers a fresh credential fetch and re-login, enforce least-privilege roles and TLS in transit, and keep secrets scrubbed from repr, tracebacks, and structured logs.
  • How would you design bulk query submission and bulk status polling while respecting warehouse rate limits? Expose a start_queries(statements) method that assigns each statement its own persistent request_id so retries stay idempotent per item, and return per-statement outcomes (query_id or QueryClientError) so one syntax error does not abort valid statements in the batch. When the warehouse SDK offers batch submit or multi-ID status endpoints, pack multiple IDs into single RPCs to cut request volume dramatically; otherwise bound parallel calls with a worker pool or asyncio.Semaphore sized below the account's rate limit. In a wait_for_all loop, poll only the shrinking subset of non-terminal query_ids against a shared monotonic deadline and gradually widen poll intervals (such as 0.5s -> 1s -> 2s -> 5s) for long analytical runs.
  • How would you modify result retrieval when a query produces millions of rows that exceed available RAM? get_results materializes all R rows inside one list (O(R) memory), which risks out-of-memory crashes on multi-gigabyte exports. Add a streaming generator (a Python function using yield that produces items lazily one chunk at a time) such as iter_rows(query_id) or iter_pages(query_id) that fetches one page, yields its rows to the caller, and releases that page before requesting next_page, bounding client memory at O(page_size). At massive scale, cloud warehouses also return pre-signed URLs to compressed Apache Arrow or Parquet partitions in object storage so worker threads can stream and decode partitions in parallel without bottlenecking on a single gateway node.

Follow-up questions

Similar questions

More Datadog interview questions

All 18 Datadog questions →