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: enqueuessqlwith positionalparams(list) and returns aquery_id. The server deduplicates byrequest_id: repeating asubmitcall with an already-seenrequest_idreturns the originalquery_idwithout 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=Nonerequests the first page;"next_page"isNoneon 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
-
Configuration & Secret Hygiene (
ClientConfig):ClientConfig(account="", user="", password="")must omitpasswordfromrepr().ClientConfig.from_env(env)reads"WAREHOUSE_ACCOUNT","WAREHOUSE_USER", and"WAREHOUSE_PASSWORD"fromenv(defaulting absent keys to"").connect()validates thataccountanduserare non-blank (after stripping whitespace) andpasswordis non-empty before touching the network. If any are missing, raiseConfigErrornaming the missing field(s). Otherwise authenticate viaapi.loginand store the session token. Calling query operations beforeconnect()raisesQueryClientError.- If
api.loginraisesApiError("AUTH_FAILED", ...), raiseAuthenticationErrorwithout retrying and ensure the password never appears in the error text or chained exception traceback.
-
Retries & Error Mapping:
QueryClient(api, config, max_attempts=3, backoff_s=0.5, sleep=time.sleep, clock=time.monotonic)validatesmax_attempts >= 1andbackoff_s >= 0(raisingConfigErrorotherwise).- Every SDK call retries
ConnectionErrorandTimeoutErrorup tomax_attemptstotal attempts, sleepingbackoff_s,2 * backoff_s,4 * backoff_s, ... between attempts viasleep, and raisingNetworkErroronce attempts are exhausted. - Never retry
ApiError: map"AUTH_FAILED"toAuthenticationError,"INVALID_SQL"toInvalidSQLError,"UNKNOWN_QUERY"toUnknownQueryError, and any other code toQueryClientError.
-
Query Execution, Polling, Pagination, & Cancellation:
start_query(sql, params=None) -> str: raiseInvalidSQLErrorlocally (no SDK call) ifsqlis not a string or is whitespace-only. Pass bind parameters as a separatelist([]whenparamsisNone), never interpolated intosql. Reuse one generatedrequest_idacross retries of the samestart_querycall so a dropped response cannot duplicate execution.get_query_status(query_id) -> QueryState: return the mappedQueryStateenum member (QUEUED,RUNNING,SUCCEEDED,FAILED,CANCELED), or raiseQueryClientErrorif the status payload is malformed.get_results(query_id) -> QueryResult: check query status first. RaiseResultsNotReadyErrorifQUEUEDorRUNNING,QueryFailedError(including the server's error message) ifFAILED, orQueryCanceledErrorifCANCELED, without callingapi.fetch. WhenSUCCEEDED, iterateapi.fetchfrompage_token=Noneuntilnext_pageisNoneand return all rows concatenated in order insideQueryResult(columns, rows).wait_for_completion(query_id, timeout_s, poll_interval_s=1.0) -> QueryState: validatetimeout_s >= 0andpoll_interval_s > 0(ConfigErrorotherwise). Poll until the query reachesSUCCEEDED,FAILED, orCANCELED, sleepingmin(poll_interval_s, remaining_seconds)viasleepandclock. If the deadline expires first, raiseQueryTimeoutError(query_id, timeout_s)without canceling the query.cancel_query(query_id) -> None: cancelquery_idviaapi.cancel.run_query(sql, params=None, timeout_s=300.0, poll_interval_s=1.0) -> QueryResult: submit, wait for completion, and returnget_results(query_id). Ifwait_for_completionraisesQueryTimeoutError, make a best-effortcancel_query(query_id)call (ignoringQueryClientErrorfrom cleanup) before re-raisingQueryTimeoutError.
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 >= 1andbackoff_s >= 0.0(raiseConfigErrorotherwise).timeout_s >= 0.0andpoll_interval_s > 0.0(raiseConfigErrorotherwise).passwordvalues may contain arbitrary characters and must never appear inrepr(config), exception messages, or formatted tracebacks.- All time measurements and sleeps must go through the injected
clockandsleepcallables.
Step-by-step walkthrough
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..kLet us summarize what the low-level
apitransport can return or raise: -login(account, user, password) -> str(session token) -submit(token, sql, params, request_id) -> str(query_id; repeating an already-seenrequest_idreturns the originalquery_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 raiseConnectionErrororTimeoutError; server rejections raiseApiError(code, message).Our goal is to turn that raw transport into a safe, ergonomic
QueryClient.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 anEnumcatches typos immediately, and grouping the three finished states intoTERMINAL_STATESkeeps 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 userNotice that
QueryTimeoutErrorstoresself.query_idon the exception so a caller whose wait timed out still knows which query is active.Load configuration at runtime without leaking secrets
Hard-coding credentials in source code is a security hazard.
ClientConfig.from_env(env)readsWAREHOUSE_ACCOUNT,WAREHOUSE_USER, andWAREHOUSE_PASSWORDfrom a passed-in mapping (os.environin production, a plain dictionary in unit tests).Three safeguards keep secrets out of logs and crash reports: 1.
field(repr=False)onpassword: Printing or logging aClientConfigshowsClientConfig(account='northwind', user='svc_analytics')and never prints the password. 2. Fail-fast validation naming fields, never values:connect()checksmissing_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"). WhenApiError("AUTH_FAILED", ...)arrives, we returnAuthenticationErrorwith a fixed message AND raise it withfrom Noneso Python does not chain the rawApiErrorintologger.exceptiontracebacks!@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 missingCentralize 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 tomax_attemptstimes using exponential backoff: waitbackoff_safter attempt 1,2 * backoff_safter attempt 2,4 * backoff_safter 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_errormaps 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- Transient network failures (
Submit queries safely with bind parameters and an idempotency key
start_query(sql, params)protects against two classic bugs:- 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. Passingbound_params = list(params)separately lets the warehouse bind values safely. - Duplicate query execution on lost replies: Suppose
submitreaches the server and startsSELECT COUNT(*) FROM events(or anINSERT), but the network drops while the server's reply is traveling back. If_callretried with a brand-new request ID, the warehouse would run the statement twice! Creatingrequest_id = str(uuid.uuid4())once before calling_callgives every retry the same idempotency key so the warehouse recognizes the duplicate and returns the originalquery_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)- SQL injection and broken quoting: Never format parameter values into the SQL string! Passing
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.QUEUEDorQueryState.RUNNING->ResultsNotReadyError.Once the query is
SUCCEEDED, warehouse results can span multiple pages. Tracing Example 1, we start withpage_token = Nonefor the first page, appendpage["rows"]to ourrowslist, and advancepage_token = page["next_page"]untilnext_pagecomes backNone: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]]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-clocktime.time()can jump backward or forward when NTP adjusts the system clock; a monotonic clock only moves forward. Injectingclockandsleepinto__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_completionstarts att = 0.5swithtimeout_s = 2.5(deadline = 3.0s) andpoll_interval_s = 1.0. Polling runs att = 0.5,t = 1.5, andt = 2.5, then sleepsmin(1.0, 0.5) = 0.5sfor one final check right att = 3.0sbefore raisingQueryTimeoutError. 3. Who cancels on timeout? Inwait_for_completion, the caller already holdsquery_idand may choose to wait longer, so we leave the query running. Inrun_query, the caller never sawquery_id, so ifwait_for_completiontimes out,run_querycalls_cancel_quietly(query_id)(ignoring cleanup errors so the caller still receivesQueryTimeoutError) 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))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, andcancel_queryeach performO(1)SDK calls in the healthy case and at mostmax_attemptscalls under transient network failures, sleeping a total ofbackoff_s * (2^(max_attempts - 1) - 1)seconds (0.5 + 1.0 = 1.5swith defaults) before raisingNetworkError.wait_for_completionpolls status at mostceil(timeout_s / poll_interval_s) + 1times because each sleep advances toward the fixed deadline, andget_resultsperforms1status call plusPpage fetches for aP-page result (O(P)network calls andO(R)work to collectRrows). - Space:
O(R). Connection state, session token, and polling variables useO(1)memory, whileget_resultsaccumulates allRreturned rows in memory insideQueryResult(see the streaming follow-up for keeping memory atO(page_size)).
Edge cases
- Missing or whitespace-only configuration fields:
connect()raisesConfigErrornaming the missing field names (never values) before making any network call. - Invalid credentials:
AuthenticationErroruses a fixed message andraise ... from Noneso a server message that echoes the attempted password cannot leak through chained exception tracebacks; authentication rejections are never retried. - Calling methods before
connect()or afterclose():_require_session()immediately raisesQueryClientError("not connected: call connect() first")instead of sendingtoken=None. - Empty SQL or syntax errors: Blank SQL raises
InvalidSQLErrorlocally with zero network calls; server-detected syntax errors map toInvalidSQLErrorwithout retrying. - Lost submit response after the query was created: Because
request_idis generated once before_call, the retry sends the identicalrequest_idand receives the samequery_idrather than executing the SQL a second time. - Fetching results in non-succeeded states:
QUEUEDorRUNNINGraisesResultsNotReadyError,FAILEDraisesQueryFailedErrorwith the server's execution error (such as"Numeric overflow"), andCANCELEDraisesQueryCanceledErrorwithout callingfetch. - Zero timeout (
timeout_s = 0): Polls status once; returns immediately if already terminal, or raisesQueryTimeoutErrorwithout sleeping. - Invalid retry or polling settings:
max_attempts < 1,backoff_s < 0,timeout_s < 0, orpoll_interval_s <= 0raiseConfigErrorimmediately instead of looping infinitely or crashingtime.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_idinside 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_SQLorAUTH_FAILEDwastes 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 oftime.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_querycalls running: Whenrun_queryhidesquery_idfrom the caller, failing to cancel on timeout leaks warehouse compute credits on a result nobody can ever fetch. - Chaining
AuthenticationErrorfrom the rawApiError: Even if your wrapper message hides the password,raise error from excattachesexcas__cause__, causinglogger.exceptionto print the raw server message anyway. - Fetching only the first page: Ignoring
next_pagesilently 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
QueryClientso session expiration orAUTH_FAILEDtriggers a fresh credential fetch and re-login, enforce least-privilege roles and TLS in transit, and keep secrets scrubbed fromrepr, 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 persistentrequest_idso retries stay idempotent per item, and return per-statement outcomes (query_idorQueryClientError) 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 orasyncio.Semaphoresized below the account's rate limit. In await_for_allloop, poll only the shrinking subset of non-terminalquery_ids against a shared monotonic deadline and gradually widen poll intervals (such as0.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_resultsmaterializes allRrows inside one list (O(R)memory), which risks out-of-memory crashes on multi-gigabyte exports. Add a streaming generator (a Python function usingyieldthat produces items lazily one chunk at a time) such asiter_rows(query_id)oriter_pages(query_id)that fetches one page, yields its rows to the caller, and releases that page before requestingnext_page, bounding client memory atO(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
- How should production services store, authenticate with, and rotate warehouse credentials without downtime?
- How would you design bulk query submission and bulk status polling while respecting warehouse rate limits?
- How would you modify result retrieval when a query produces millions of rows that exceed available RAM?
Similar questions
- Reconstruct Call Trees from Shuffled Spans
- Windowed Metric Sums Filtered by Tag
- Thread-Safe Buffered File Writer
- In-Memory Indexed Log Store and Range Queries
- Prefix Match String Filter
- Chunked Buffered Byte Writer
More Datadog interview questions
- Subtree Deletion Using Restricted Filesystem Primitives Medium
- Reconstruct Call Trees from Shuffled Spans Medium
- Grouped-Query Attention Forward Pass Hard Pro
- Online Keyword Query Matching Over Log Streams Medium Pro
- Windowed Metric Sums Filtered by Tag Medium Pro
- End-to-End Technical Project Walkthrough Medium Pro
- Improving Brevity After Communication Feedback Medium Pro
- Autonomous LLM Coding Agent for Issue-to-PR Resolution Medium Pro
- Production Image Object Detection Service Hard Pro
- Real-Time Log and Query Stream Matcher Hard Pro